function.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. from parso.python import tree
  2. from jedi import debug
  3. from jedi.inference.cache import inference_state_method_cache, CachedMetaClass
  4. from jedi.inference import compiled
  5. from jedi.inference import recursion
  6. from jedi.inference import docstrings
  7. from jedi.inference import flow_analysis
  8. from jedi.inference.signature import TreeSignature
  9. from jedi.inference.filters import ParserTreeFilter, FunctionExecutionFilter, \
  10. AnonymousFunctionExecutionFilter
  11. from jedi.inference.names import ValueName, AbstractNameDefinition, \
  12. AnonymousParamName, ParamName, NameWrapper
  13. from jedi.inference.base_value import ContextualizedNode, NO_VALUES, \
  14. ValueSet, TreeValue, ValueWrapper
  15. from jedi.inference.lazy_value import LazyKnownValues, LazyKnownValue, \
  16. LazyTreeValue
  17. from jedi.inference.context import ValueContext, TreeContextMixin
  18. from jedi.inference.value import iterable
  19. from jedi import parser_utils
  20. from jedi.inference.parser_cache import get_yield_exprs
  21. from jedi.inference.helpers import values_from_qualified_names
  22. from jedi.inference.gradual.generics import TupleGenericManager
  23. class LambdaName(AbstractNameDefinition):
  24. string_name = '<lambda>'
  25. api_type = 'function'
  26. def __init__(self, lambda_value):
  27. self._lambda_value = lambda_value
  28. self.parent_context = lambda_value.parent_context
  29. @property
  30. def start_pos(self):
  31. return self._lambda_value.tree_node.start_pos
  32. def infer(self):
  33. return ValueSet([self._lambda_value])
  34. class FunctionAndClassBase(TreeValue):
  35. def get_qualified_names(self):
  36. if self.parent_context.is_class():
  37. n = self.parent_context.get_qualified_names()
  38. if n is None:
  39. # This means that the parent class lives within a function.
  40. return None
  41. return n + (self.py__name__(),)
  42. elif self.parent_context.is_module():
  43. return (self.py__name__(),)
  44. else:
  45. return None
  46. class FunctionMixin:
  47. api_type = 'function'
  48. def get_filters(self, origin_scope=None):
  49. cls = self.py__class__()
  50. for instance in cls.execute_with_values():
  51. yield from instance.get_filters(origin_scope=origin_scope)
  52. def py__get__(self, instance, class_value):
  53. from jedi.inference.value.instance import BoundMethod
  54. if instance is None:
  55. # Calling the Foo.bar results in the original bar function.
  56. return ValueSet([self])
  57. return ValueSet([BoundMethod(instance, class_value.as_context(), self)])
  58. def get_param_names(self):
  59. return [AnonymousParamName(self, param.name)
  60. for param in self.tree_node.get_params()]
  61. @property
  62. def name(self):
  63. if self.tree_node.type == 'lambdef':
  64. return LambdaName(self)
  65. return ValueName(self, self.tree_node.name)
  66. def is_function(self):
  67. return True
  68. def py__name__(self):
  69. return self.name.string_name
  70. def get_type_hint(self, add_class_info=True):
  71. return_annotation = self.tree_node.annotation
  72. if return_annotation is None:
  73. def param_name_to_str(n):
  74. s = n.string_name
  75. annotation = n.infer().get_type_hint()
  76. if annotation is not None:
  77. s += ': ' + annotation
  78. if n.default_node is not None:
  79. s += '=' + n.default_node.get_code(include_prefix=False)
  80. return s
  81. function_execution = self.as_context()
  82. result = function_execution.infer()
  83. return_hint = result.get_type_hint()
  84. body = self.py__name__() + '(%s)' % ', '.join([
  85. param_name_to_str(n)
  86. for n in function_execution.get_param_names()
  87. ])
  88. if return_hint is None:
  89. return body
  90. else:
  91. return_hint = return_annotation.get_code(include_prefix=False)
  92. body = self.py__name__() + self.tree_node.children[2].get_code(include_prefix=False)
  93. return body + ' -> ' + return_hint
  94. def py__call__(self, arguments):
  95. function_execution = self.as_context(arguments)
  96. return function_execution.infer()
  97. def _as_context(self, arguments=None):
  98. if arguments is None:
  99. return AnonymousFunctionExecution(self)
  100. return FunctionExecutionContext(self, arguments)
  101. def get_signatures(self):
  102. return [TreeSignature(f) for f in self.get_signature_functions()]
  103. class FunctionValue(FunctionMixin, FunctionAndClassBase, metaclass=CachedMetaClass):
  104. @classmethod
  105. def from_context(cls, context, tree_node):
  106. def create(tree_node):
  107. if context.is_class():
  108. return MethodValue(
  109. context.inference_state,
  110. context,
  111. parent_context=parent_context,
  112. tree_node=tree_node
  113. )
  114. else:
  115. return cls(
  116. context.inference_state,
  117. parent_context=parent_context,
  118. tree_node=tree_node
  119. )
  120. overloaded_funcs = list(_find_overload_functions(context, tree_node))
  121. parent_context = context
  122. while parent_context.is_class() or parent_context.is_instance():
  123. parent_context = parent_context.parent_context
  124. function = create(tree_node)
  125. if overloaded_funcs:
  126. return OverloadedFunctionValue(
  127. function,
  128. # Get them into the correct order: lower line first.
  129. list(reversed([create(f) for f in overloaded_funcs]))
  130. )
  131. return function
  132. def py__class__(self):
  133. c, = values_from_qualified_names(self.inference_state, 'types', 'FunctionType')
  134. return c
  135. def get_default_param_context(self):
  136. return self.parent_context
  137. def get_signature_functions(self):
  138. return [self]
  139. class FunctionNameInClass(NameWrapper):
  140. def __init__(self, class_context, name):
  141. super().__init__(name)
  142. self._class_context = class_context
  143. def get_defining_qualified_value(self):
  144. return self._class_context.get_value() # Might be None.
  145. class MethodValue(FunctionValue):
  146. def __init__(self, inference_state, class_context, *args, **kwargs):
  147. super().__init__(inference_state, *args, **kwargs)
  148. self.class_context = class_context
  149. def get_default_param_context(self):
  150. return self.class_context
  151. def get_qualified_names(self):
  152. # Need to implement this, because the parent value of a method
  153. # value is not the class value but the module.
  154. names = self.class_context.get_qualified_names()
  155. if names is None:
  156. return None
  157. return names + (self.py__name__(),)
  158. @property
  159. def name(self):
  160. return FunctionNameInClass(self.class_context, super().name)
  161. class BaseFunctionExecutionContext(ValueContext, TreeContextMixin):
  162. def infer_annotations(self):
  163. raise NotImplementedError
  164. @inference_state_method_cache(default=NO_VALUES)
  165. @recursion.execution_recursion_decorator()
  166. def get_return_values(self, check_yields=False):
  167. funcdef = self.tree_node
  168. if funcdef.type == 'lambdef':
  169. return self.infer_node(funcdef.children[-1])
  170. if check_yields:
  171. value_set = NO_VALUES
  172. returns = get_yield_exprs(self.inference_state, funcdef)
  173. else:
  174. value_set = self.infer_annotations()
  175. if value_set:
  176. # If there are annotations, prefer them over anything else.
  177. # This will make it faster.
  178. return value_set
  179. value_set |= docstrings.infer_return_types(self._value)
  180. returns = funcdef.iter_return_stmts()
  181. for r in returns:
  182. if check_yields:
  183. value_set |= ValueSet.from_sets(
  184. lazy_value.infer()
  185. for lazy_value in self._get_yield_lazy_value(r)
  186. )
  187. else:
  188. check = flow_analysis.reachability_check(self, funcdef, r)
  189. if check is flow_analysis.UNREACHABLE:
  190. debug.dbg('Return unreachable: %s', r)
  191. else:
  192. try:
  193. children = r.children
  194. except AttributeError:
  195. ctx = compiled.builtin_from_name(self.inference_state, 'None')
  196. value_set |= ValueSet([ctx])
  197. else:
  198. value_set |= self.infer_node(children[1])
  199. if check is flow_analysis.REACHABLE:
  200. debug.dbg('Return reachable: %s', r)
  201. break
  202. return value_set
  203. def _get_yield_lazy_value(self, yield_expr):
  204. if yield_expr.type == 'keyword':
  205. # `yield` just yields None.
  206. ctx = compiled.builtin_from_name(self.inference_state, 'None')
  207. yield LazyKnownValue(ctx)
  208. return
  209. node = yield_expr.children[1]
  210. if node.type == 'yield_arg': # It must be a yield from.
  211. cn = ContextualizedNode(self, node.children[1])
  212. yield from cn.infer().iterate(cn)
  213. else:
  214. yield LazyTreeValue(self, node)
  215. @recursion.execution_recursion_decorator(default=iter([]))
  216. def get_yield_lazy_values(self, is_async=False):
  217. # TODO: if is_async, wrap yield statements in Awaitable/async_generator_asend
  218. for_parents = [(y, tree.search_ancestor(y, 'for_stmt', 'funcdef',
  219. 'while_stmt', 'if_stmt'))
  220. for y in get_yield_exprs(self.inference_state, self.tree_node)]
  221. # Calculate if the yields are placed within the same for loop.
  222. yields_order = []
  223. last_for_stmt = None
  224. for yield_, for_stmt in for_parents:
  225. # For really simple for loops we can predict the order. Otherwise
  226. # we just ignore it.
  227. parent = for_stmt.parent
  228. if parent.type == 'suite':
  229. parent = parent.parent
  230. if for_stmt.type == 'for_stmt' and parent == self.tree_node \
  231. and parser_utils.for_stmt_defines_one_name(for_stmt): # Simplicity for now.
  232. if for_stmt == last_for_stmt:
  233. yields_order[-1][1].append(yield_)
  234. else:
  235. yields_order.append((for_stmt, [yield_]))
  236. elif for_stmt == self.tree_node:
  237. yields_order.append((None, [yield_]))
  238. else:
  239. types = self.get_return_values(check_yields=True)
  240. if types:
  241. yield LazyKnownValues(types, min=0, max=float('inf'))
  242. return
  243. last_for_stmt = for_stmt
  244. for for_stmt, yields in yields_order:
  245. if for_stmt is None:
  246. # No for_stmt, just normal yields.
  247. for yield_ in yields:
  248. yield from self._get_yield_lazy_value(yield_)
  249. else:
  250. input_node = for_stmt.get_testlist()
  251. cn = ContextualizedNode(self, input_node)
  252. ordered = cn.infer().iterate(cn)
  253. ordered = list(ordered)
  254. for lazy_value in ordered:
  255. dct = {str(for_stmt.children[1].value): lazy_value.infer()}
  256. with self.predefine_names(for_stmt, dct):
  257. for yield_in_same_for_stmt in yields:
  258. yield from self._get_yield_lazy_value(yield_in_same_for_stmt)
  259. def merge_yield_values(self, is_async=False):
  260. return ValueSet.from_sets(
  261. lazy_value.infer()
  262. for lazy_value in self.get_yield_lazy_values()
  263. )
  264. def is_generator(self):
  265. return bool(get_yield_exprs(self.inference_state, self.tree_node))
  266. def infer(self):
  267. """
  268. Created to be used by inheritance.
  269. """
  270. inference_state = self.inference_state
  271. is_coroutine = self.tree_node.parent.type in ('async_stmt', 'async_funcdef')
  272. from jedi.inference.gradual.base import GenericClass
  273. if is_coroutine:
  274. if self.is_generator():
  275. async_generator_classes = inference_state.typing_module \
  276. .py__getattribute__('AsyncGenerator')
  277. yield_values = self.merge_yield_values(is_async=True)
  278. # The contravariant doesn't seem to be defined.
  279. generics = (yield_values.py__class__(), NO_VALUES)
  280. return ValueSet(
  281. GenericClass(c, TupleGenericManager(generics))
  282. for c in async_generator_classes
  283. ).execute_annotation()
  284. else:
  285. async_classes = inference_state.typing_module.py__getattribute__('Coroutine')
  286. return_values = self.get_return_values()
  287. # Only the first generic is relevant.
  288. generics = (return_values.py__class__(), NO_VALUES, NO_VALUES)
  289. return ValueSet(
  290. GenericClass(c, TupleGenericManager(generics)) for c in async_classes
  291. ).execute_annotation()
  292. else:
  293. # If there are annotations, prefer them over anything else.
  294. if self.is_generator() and not self.infer_annotations():
  295. return ValueSet([iterable.Generator(inference_state, self)])
  296. else:
  297. return self.get_return_values()
  298. class FunctionExecutionContext(BaseFunctionExecutionContext):
  299. def __init__(self, function_value, arguments):
  300. super().__init__(function_value)
  301. self._arguments = arguments
  302. def get_filters(self, until_position=None, origin_scope=None):
  303. yield FunctionExecutionFilter(
  304. self, self._value,
  305. until_position=until_position,
  306. origin_scope=origin_scope,
  307. arguments=self._arguments
  308. )
  309. def infer_annotations(self):
  310. from jedi.inference.gradual.annotation import infer_return_types
  311. return infer_return_types(self._value, self._arguments)
  312. def get_param_names(self):
  313. return [
  314. ParamName(self._value, param.name, self._arguments)
  315. for param in self._value.tree_node.get_params()
  316. ]
  317. class AnonymousFunctionExecution(BaseFunctionExecutionContext):
  318. def infer_annotations(self):
  319. # I don't think inferring anonymous executions is a big thing.
  320. # Anonymous contexts are mostly there for the user to work in. ~ dave
  321. return NO_VALUES
  322. def get_filters(self, until_position=None, origin_scope=None):
  323. yield AnonymousFunctionExecutionFilter(
  324. self, self._value,
  325. until_position=until_position,
  326. origin_scope=origin_scope,
  327. )
  328. def get_param_names(self):
  329. return self._value.get_param_names()
  330. class OverloadedFunctionValue(FunctionMixin, ValueWrapper):
  331. def __init__(self, function, overloaded_functions):
  332. super().__init__(function)
  333. self._overloaded_functions = overloaded_functions
  334. def py__call__(self, arguments):
  335. debug.dbg("Execute overloaded function %s", self._wrapped_value, color='BLUE')
  336. function_executions = []
  337. for signature in self.get_signatures():
  338. function_execution = signature.value.as_context(arguments)
  339. function_executions.append(function_execution)
  340. if signature.matches_signature(arguments):
  341. return function_execution.infer()
  342. if self.inference_state.is_analysis:
  343. # In this case we want precision.
  344. return NO_VALUES
  345. return ValueSet.from_sets(fe.infer() for fe in function_executions)
  346. def get_signature_functions(self):
  347. return self._overloaded_functions
  348. def get_type_hint(self, add_class_info=True):
  349. return 'Union[%s]' % ', '.join(f.get_type_hint() for f in self._overloaded_functions)
  350. def _find_overload_functions(context, tree_node):
  351. def _is_overload_decorated(funcdef):
  352. if funcdef.parent.type == 'decorated':
  353. decorators = funcdef.parent.children[0]
  354. if decorators.type == 'decorator':
  355. decorators = [decorators]
  356. else:
  357. decorators = decorators.children
  358. for decorator in decorators:
  359. dotted_name = decorator.children[1]
  360. if dotted_name.type == 'name' and dotted_name.value == 'overload':
  361. # TODO check with values if it's the right overload
  362. return True
  363. return False
  364. if tree_node.type == 'lambdef':
  365. return
  366. if _is_overload_decorated(tree_node):
  367. yield tree_node
  368. while True:
  369. filter = ParserTreeFilter(
  370. context,
  371. until_position=tree_node.start_pos
  372. )
  373. names = filter.get(tree_node.name.value)
  374. assert isinstance(names, list)
  375. if not names:
  376. break
  377. found = False
  378. for name in names:
  379. funcdef = name.tree_name.parent
  380. if funcdef.type == 'funcdef' and _is_overload_decorated(funcdef):
  381. tree_node = funcdef
  382. found = True
  383. yield funcdef
  384. if not found:
  385. break