instance.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. from abc import abstractproperty
  2. from parso.tree import search_ancestor
  3. from jedi import debug
  4. from jedi import settings
  5. from jedi.inference import compiled
  6. from jedi.inference.compiled.value import CompiledValueFilter
  7. from jedi.inference.helpers import values_from_qualified_names, is_big_annoying_library
  8. from jedi.inference.filters import AbstractFilter, AnonymousFunctionExecutionFilter
  9. from jedi.inference.names import ValueName, TreeNameDefinition, ParamName, \
  10. NameWrapper
  11. from jedi.inference.base_value import Value, NO_VALUES, ValueSet, \
  12. iterator_to_value_set, ValueWrapper
  13. from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues
  14. from jedi.inference.cache import inference_state_method_cache
  15. from jedi.inference.arguments import ValuesArguments, TreeArgumentsWrapper
  16. from jedi.inference.value.function import \
  17. FunctionValue, FunctionMixin, OverloadedFunctionValue, \
  18. BaseFunctionExecutionContext, FunctionExecutionContext, FunctionNameInClass
  19. from jedi.inference.value.klass import ClassFilter
  20. from jedi.inference.value.dynamic_arrays import get_dynamic_array_instance
  21. from jedi.parser_utils import function_is_staticmethod, function_is_classmethod
  22. class InstanceExecutedParamName(ParamName):
  23. def __init__(self, instance, function_value, tree_name):
  24. super().__init__(
  25. function_value, tree_name, arguments=None)
  26. self._instance = instance
  27. def infer(self):
  28. return ValueSet([self._instance])
  29. def matches_signature(self):
  30. return True
  31. class AnonymousMethodExecutionFilter(AnonymousFunctionExecutionFilter):
  32. def __init__(self, instance, *args, **kwargs):
  33. super().__init__(*args, **kwargs)
  34. self._instance = instance
  35. def _convert_param(self, param, name):
  36. if param.position_index == 0:
  37. if function_is_classmethod(self._function_value.tree_node):
  38. return InstanceExecutedParamName(
  39. self._instance.py__class__(),
  40. self._function_value,
  41. name
  42. )
  43. elif not function_is_staticmethod(self._function_value.tree_node):
  44. return InstanceExecutedParamName(
  45. self._instance,
  46. self._function_value,
  47. name
  48. )
  49. return super()._convert_param(param, name)
  50. class AnonymousMethodExecutionContext(BaseFunctionExecutionContext):
  51. def __init__(self, instance, value):
  52. super().__init__(value)
  53. self.instance = instance
  54. def get_filters(self, until_position=None, origin_scope=None):
  55. yield AnonymousMethodExecutionFilter(
  56. self.instance, self, self._value,
  57. until_position=until_position,
  58. origin_scope=origin_scope,
  59. )
  60. def get_param_names(self):
  61. param_names = list(self._value.get_param_names())
  62. # set the self name
  63. param_names[0] = InstanceExecutedParamName(
  64. self.instance,
  65. self._value,
  66. param_names[0].tree_name
  67. )
  68. return param_names
  69. class MethodExecutionContext(FunctionExecutionContext):
  70. def __init__(self, instance, *args, **kwargs):
  71. super().__init__(*args, **kwargs)
  72. self.instance = instance
  73. class AbstractInstanceValue(Value):
  74. api_type = 'instance'
  75. def __init__(self, inference_state, parent_context, class_value):
  76. super().__init__(inference_state, parent_context)
  77. # Generated instances are classes that are just generated by self
  78. # (No arguments) used.
  79. self.class_value = class_value
  80. def is_instance(self):
  81. return True
  82. def get_qualified_names(self):
  83. return self.class_value.get_qualified_names()
  84. def get_annotated_class_object(self):
  85. return self.class_value # This is the default.
  86. def py__class__(self):
  87. return self.class_value
  88. def py__bool__(self):
  89. # Signalize that we don't know about the bool type.
  90. return None
  91. @abstractproperty
  92. def name(self):
  93. raise NotImplementedError
  94. def get_signatures(self):
  95. call_funcs = self.py__getattribute__('__call__').py__get__(self, self.class_value)
  96. return [s.bind(self) for s in call_funcs.get_signatures()]
  97. def get_function_slot_names(self, name):
  98. # Python classes don't look at the dictionary of the instance when
  99. # looking up `__call__`. This is something that has to do with Python's
  100. # internal slot system (note: not __slots__, but C slots).
  101. for filter in self.get_filters(include_self_names=False):
  102. names = filter.get(name)
  103. if names:
  104. return names
  105. return []
  106. def execute_function_slots(self, names, *inferred_args):
  107. return ValueSet.from_sets(
  108. name.infer().execute_with_values(*inferred_args)
  109. for name in names
  110. )
  111. def get_type_hint(self, add_class_info=True):
  112. return self.py__name__()
  113. def py__getitem__(self, index_value_set, contextualized_node):
  114. names = self.get_function_slot_names('__getitem__')
  115. if not names:
  116. return super().py__getitem__(
  117. index_value_set,
  118. contextualized_node,
  119. )
  120. args = ValuesArguments([index_value_set])
  121. return ValueSet.from_sets(name.infer().execute(args) for name in names)
  122. def py__iter__(self, contextualized_node=None):
  123. iter_slot_names = self.get_function_slot_names('__iter__')
  124. if not iter_slot_names:
  125. return super().py__iter__(contextualized_node)
  126. def iterate():
  127. for generator in self.execute_function_slots(iter_slot_names):
  128. yield from generator.py__next__(contextualized_node)
  129. return iterate()
  130. def __repr__(self):
  131. return "<%s of %s>" % (self.__class__.__name__, self.class_value)
  132. class CompiledInstance(AbstractInstanceValue):
  133. # This is not really a compiled class, it's just an instance from a
  134. # compiled class.
  135. def __init__(self, inference_state, parent_context, class_value, arguments):
  136. super().__init__(inference_state, parent_context, class_value)
  137. self._arguments = arguments
  138. def get_filters(self, origin_scope=None, include_self_names=True):
  139. class_value = self.get_annotated_class_object()
  140. class_filters = class_value.get_filters(
  141. origin_scope=origin_scope,
  142. is_instance=True,
  143. )
  144. for f in class_filters:
  145. yield CompiledInstanceClassFilter(self, f)
  146. @property
  147. def name(self):
  148. return compiled.CompiledValueName(self, self.class_value.name.string_name)
  149. def is_stub(self):
  150. return False
  151. class _BaseTreeInstance(AbstractInstanceValue):
  152. @property
  153. def array_type(self):
  154. name = self.class_value.py__name__()
  155. if name in ['list', 'set', 'dict'] \
  156. and self.parent_context.get_root_context().is_builtins_module():
  157. return name
  158. return None
  159. @property
  160. def name(self):
  161. return ValueName(self, self.class_value.name.tree_name)
  162. def get_filters(self, origin_scope=None, include_self_names=True):
  163. class_value = self.get_annotated_class_object()
  164. if include_self_names:
  165. for cls in class_value.py__mro__():
  166. if not cls.is_compiled():
  167. # In this case we're excluding compiled objects that are
  168. # not fake objects. It doesn't make sense for normal
  169. # compiled objects to search for self variables.
  170. yield SelfAttributeFilter(self, class_value, cls.as_context(), origin_scope)
  171. class_filters = class_value.get_filters(
  172. origin_scope=origin_scope,
  173. is_instance=True,
  174. )
  175. for f in class_filters:
  176. if isinstance(f, ClassFilter):
  177. yield InstanceClassFilter(self, f)
  178. elif isinstance(f, CompiledValueFilter):
  179. yield CompiledInstanceClassFilter(self, f)
  180. else:
  181. # Propably from the metaclass.
  182. yield f
  183. @inference_state_method_cache()
  184. def create_instance_context(self, class_context, node):
  185. new = node
  186. while True:
  187. func_node = new
  188. new = search_ancestor(new, 'funcdef', 'classdef')
  189. if class_context.tree_node is new:
  190. func = FunctionValue.from_context(class_context, func_node)
  191. bound_method = BoundMethod(self, class_context, func)
  192. if func_node.name.value == '__init__':
  193. context = bound_method.as_context(self._arguments)
  194. else:
  195. context = bound_method.as_context()
  196. break
  197. return context.create_context(node)
  198. def py__getattribute__alternatives(self, string_name):
  199. '''
  200. Since nothing was inferred, now check the __getattr__ and
  201. __getattribute__ methods. Stubs don't need to be checked, because
  202. they don't contain any logic.
  203. '''
  204. if self.is_stub():
  205. return NO_VALUES
  206. name = compiled.create_simple_object(self.inference_state, string_name)
  207. # This is a little bit special. `__getattribute__` is in Python
  208. # executed before `__getattr__`. But: I know no use case, where
  209. # this could be practical and where Jedi would return wrong types.
  210. # If you ever find something, let me know!
  211. # We are inversing this, because a hand-crafted `__getattribute__`
  212. # could still call another hand-crafted `__getattr__`, but not the
  213. # other way around.
  214. if is_big_annoying_library(self.parent_context):
  215. return NO_VALUES
  216. names = (self.get_function_slot_names('__getattr__')
  217. or self.get_function_slot_names('__getattribute__'))
  218. return self.execute_function_slots(names, name)
  219. def py__next__(self, contextualized_node=None):
  220. name = u'__next__'
  221. next_slot_names = self.get_function_slot_names(name)
  222. if next_slot_names:
  223. yield LazyKnownValues(
  224. self.execute_function_slots(next_slot_names)
  225. )
  226. else:
  227. debug.warning('Instance has no __next__ function in %s.', self)
  228. def py__call__(self, arguments):
  229. names = self.get_function_slot_names('__call__')
  230. if not names:
  231. # Means the Instance is not callable.
  232. return super().py__call__(arguments)
  233. return ValueSet.from_sets(name.infer().execute(arguments) for name in names)
  234. def py__get__(self, instance, class_value):
  235. """
  236. obj may be None.
  237. """
  238. # Arguments in __get__ descriptors are obj, class.
  239. # `method` is the new parent of the array, don't know if that's good.
  240. for cls in self.class_value.py__mro__():
  241. result = cls.py__get__on_class(self, instance, class_value)
  242. if result is not NotImplemented:
  243. return result
  244. names = self.get_function_slot_names('__get__')
  245. if names:
  246. if instance is None:
  247. instance = compiled.builtin_from_name(self.inference_state, 'None')
  248. return self.execute_function_slots(names, instance, class_value)
  249. else:
  250. return ValueSet([self])
  251. class TreeInstance(_BaseTreeInstance):
  252. def __init__(self, inference_state, parent_context, class_value, arguments):
  253. # I don't think that dynamic append lookups should happen here. That
  254. # sounds more like something that should go to py__iter__.
  255. if class_value.py__name__() in ['list', 'set'] \
  256. and parent_context.get_root_context().is_builtins_module():
  257. # compare the module path with the builtin name.
  258. if settings.dynamic_array_additions:
  259. arguments = get_dynamic_array_instance(self, arguments)
  260. super().__init__(inference_state, parent_context, class_value)
  261. self._arguments = arguments
  262. self.tree_node = class_value.tree_node
  263. # This can recurse, if the initialization of the class includes a reference
  264. # to itself.
  265. @inference_state_method_cache(default=None)
  266. def _get_annotated_class_object(self):
  267. from jedi.inference.gradual.annotation import py__annotations__, \
  268. infer_type_vars_for_execution
  269. args = InstanceArguments(self, self._arguments)
  270. for signature in self.class_value.py__getattribute__('__init__').get_signatures():
  271. # Just take the first result, it should always be one, because we
  272. # control the typeshed code.
  273. funcdef = signature.value.tree_node
  274. if funcdef is None or funcdef.type != 'funcdef' \
  275. or not signature.matches_signature(args):
  276. # First check if the signature even matches, if not we don't
  277. # need to infer anything.
  278. continue
  279. bound_method = BoundMethod(self, self.class_value.as_context(), signature.value)
  280. all_annotations = py__annotations__(funcdef)
  281. type_var_dict = infer_type_vars_for_execution(bound_method, args, all_annotations)
  282. if type_var_dict:
  283. defined, = self.class_value.define_generics(
  284. infer_type_vars_for_execution(signature.value, args, all_annotations),
  285. )
  286. debug.dbg('Inferred instance value as %s', defined, color='BLUE')
  287. return defined
  288. return None
  289. def get_annotated_class_object(self):
  290. return self._get_annotated_class_object() or self.class_value
  291. def get_key_values(self):
  292. values = NO_VALUES
  293. if self.array_type == 'dict':
  294. for i, (key, instance) in enumerate(self._arguments.unpack()):
  295. if key is None and i == 0:
  296. values |= ValueSet.from_sets(
  297. v.get_key_values()
  298. for v in instance.infer()
  299. if v.array_type == 'dict'
  300. )
  301. if key:
  302. values |= ValueSet([compiled.create_simple_object(
  303. self.inference_state,
  304. key,
  305. )])
  306. return values
  307. def py__simple_getitem__(self, index):
  308. if self.array_type == 'dict':
  309. # Logic for dict({'foo': bar}) and dict(foo=bar)
  310. # reversed, because:
  311. # >>> dict({'a': 1}, a=3)
  312. # {'a': 3}
  313. # TODO tuple initializations
  314. # >>> dict([('a', 4)])
  315. # {'a': 4}
  316. for key, lazy_context in reversed(list(self._arguments.unpack())):
  317. if key is None:
  318. values = ValueSet.from_sets(
  319. dct_value.py__simple_getitem__(index)
  320. for dct_value in lazy_context.infer()
  321. if dct_value.array_type == 'dict'
  322. )
  323. if values:
  324. return values
  325. else:
  326. if key == index:
  327. return lazy_context.infer()
  328. return super().py__simple_getitem__(index)
  329. def __repr__(self):
  330. return "<%s of %s(%s)>" % (self.__class__.__name__, self.class_value,
  331. self._arguments)
  332. class AnonymousInstance(_BaseTreeInstance):
  333. _arguments = None
  334. class CompiledInstanceName(NameWrapper):
  335. @iterator_to_value_set
  336. def infer(self):
  337. for result_value in self._wrapped_name.infer():
  338. if result_value.api_type == 'function':
  339. yield CompiledBoundMethod(result_value)
  340. else:
  341. yield result_value
  342. class CompiledInstanceClassFilter(AbstractFilter):
  343. def __init__(self, instance, f):
  344. self._instance = instance
  345. self._class_filter = f
  346. def get(self, name):
  347. return self._convert(self._class_filter.get(name))
  348. def values(self):
  349. return self._convert(self._class_filter.values())
  350. def _convert(self, names):
  351. return [CompiledInstanceName(n) for n in names]
  352. class BoundMethod(FunctionMixin, ValueWrapper):
  353. def __init__(self, instance, class_context, function):
  354. super().__init__(function)
  355. self.instance = instance
  356. self._class_context = class_context
  357. def is_bound_method(self):
  358. return True
  359. @property
  360. def name(self):
  361. return FunctionNameInClass(
  362. self._class_context,
  363. super().name
  364. )
  365. def py__class__(self):
  366. c, = values_from_qualified_names(self.inference_state, 'types', 'MethodType')
  367. return c
  368. def _get_arguments(self, arguments):
  369. assert arguments is not None
  370. return InstanceArguments(self.instance, arguments)
  371. def _as_context(self, arguments=None):
  372. if arguments is None:
  373. return AnonymousMethodExecutionContext(self.instance, self)
  374. arguments = self._get_arguments(arguments)
  375. return MethodExecutionContext(self.instance, self, arguments)
  376. def py__call__(self, arguments):
  377. if isinstance(self._wrapped_value, OverloadedFunctionValue):
  378. return self._wrapped_value.py__call__(self._get_arguments(arguments))
  379. function_execution = self.as_context(arguments)
  380. return function_execution.infer()
  381. def get_signature_functions(self):
  382. return [
  383. BoundMethod(self.instance, self._class_context, f)
  384. for f in self._wrapped_value.get_signature_functions()
  385. ]
  386. def get_signatures(self):
  387. return [sig.bind(self) for sig in super().get_signatures()]
  388. def __repr__(self):
  389. return '<%s: %s>' % (self.__class__.__name__, self._wrapped_value)
  390. class CompiledBoundMethod(ValueWrapper):
  391. def is_bound_method(self):
  392. return True
  393. def get_signatures(self):
  394. return [sig.bind(self) for sig in self._wrapped_value.get_signatures()]
  395. class SelfName(TreeNameDefinition):
  396. """
  397. This name calculates the parent_context lazily.
  398. """
  399. def __init__(self, instance, class_context, tree_name):
  400. self._instance = instance
  401. self.class_context = class_context
  402. self.tree_name = tree_name
  403. @property
  404. def parent_context(self):
  405. return self._instance.create_instance_context(self.class_context, self.tree_name)
  406. def get_defining_qualified_value(self):
  407. return self._instance
  408. def infer(self):
  409. stmt = search_ancestor(self.tree_name, 'expr_stmt')
  410. if stmt is not None:
  411. if stmt.children[1].type == "annassign":
  412. from jedi.inference.gradual.annotation import infer_annotation
  413. values = infer_annotation(
  414. self.parent_context, stmt.children[1].children[1]
  415. ).execute_annotation()
  416. if values:
  417. return values
  418. return super().infer()
  419. class LazyInstanceClassName(NameWrapper):
  420. def __init__(self, instance, class_member_name):
  421. super().__init__(class_member_name)
  422. self._instance = instance
  423. @iterator_to_value_set
  424. def infer(self):
  425. for result_value in self._wrapped_name.infer():
  426. yield from result_value.py__get__(self._instance, self._instance.py__class__())
  427. def get_signatures(self):
  428. return self.infer().get_signatures()
  429. def get_defining_qualified_value(self):
  430. return self._instance
  431. class InstanceClassFilter(AbstractFilter):
  432. """
  433. This filter is special in that it uses the class filter and wraps the
  434. resulting names in LazyInstanceClassName. The idea is that the class name
  435. filtering can be very flexible and always be reflected in instances.
  436. """
  437. def __init__(self, instance, class_filter):
  438. self._instance = instance
  439. self._class_filter = class_filter
  440. def get(self, name):
  441. return self._convert(self._class_filter.get(name))
  442. def values(self):
  443. return self._convert(self._class_filter.values())
  444. def _convert(self, names):
  445. return [
  446. LazyInstanceClassName(self._instance, n)
  447. for n in names
  448. ]
  449. def __repr__(self):
  450. return '<%s for %s>' % (self.__class__.__name__, self._class_filter)
  451. class SelfAttributeFilter(ClassFilter):
  452. """
  453. This class basically filters all the use cases where `self.*` was assigned.
  454. """
  455. def __init__(self, instance, instance_class, node_context, origin_scope):
  456. super().__init__(
  457. class_value=instance_class,
  458. node_context=node_context,
  459. origin_scope=origin_scope,
  460. is_instance=True,
  461. )
  462. self._instance = instance
  463. def _filter(self, names):
  464. start, end = self._parser_scope.start_pos, self._parser_scope.end_pos
  465. names = [n for n in names if start < n.start_pos < end]
  466. return self._filter_self_names(names)
  467. def _filter_self_names(self, names):
  468. for name in names:
  469. trailer = name.parent
  470. if trailer.type == 'trailer' \
  471. and len(trailer.parent.children) == 2 \
  472. and trailer.children[0] == '.':
  473. if name.is_definition() and self._access_possible(name):
  474. # TODO filter non-self assignments instead of this bad
  475. # filter.
  476. if self._is_in_right_scope(trailer.parent.children[0], name):
  477. yield name
  478. def _is_in_right_scope(self, self_name, name):
  479. self_context = self._node_context.create_context(self_name)
  480. names = self_context.goto(self_name, position=self_name.start_pos)
  481. return any(
  482. n.api_type == 'param'
  483. and n.tree_name.get_definition().position_index == 0
  484. and n.parent_context.tree_node is self._parser_scope
  485. for n in names
  486. )
  487. def _convert_names(self, names):
  488. return [SelfName(self._instance, self._node_context, name) for name in names]
  489. def _check_flows(self, names):
  490. return names
  491. class InstanceArguments(TreeArgumentsWrapper):
  492. def __init__(self, instance, arguments):
  493. super().__init__(arguments)
  494. self.instance = instance
  495. def unpack(self, func=None):
  496. yield None, LazyKnownValue(self.instance)
  497. yield from self._wrapped_arguments.unpack(func)