iterable.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. """
  2. Contains all classes and functions to deal with lists, dicts, generators and
  3. iterators in general.
  4. """
  5. from jedi.inference import compiled
  6. from jedi.inference import analysis
  7. from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \
  8. LazyTreeValue
  9. from jedi.inference.helpers import get_int_or_none, is_string, \
  10. reraise_getitem_errors, SimpleGetItemNotFound
  11. from jedi.inference.utils import safe_property, to_list
  12. from jedi.inference.cache import inference_state_method_cache
  13. from jedi.inference.filters import LazyAttributeOverwrite, publish_method
  14. from jedi.inference.base_value import ValueSet, Value, NO_VALUES, \
  15. ContextualizedNode, iterate_values, sentinel, \
  16. LazyValueWrapper
  17. from jedi.parser_utils import get_sync_comp_fors
  18. from jedi.inference.context import CompForContext
  19. from jedi.inference.value.dynamic_arrays import check_array_additions
  20. class IterableMixin:
  21. def py__next__(self, contextualized_node=None):
  22. return self.py__iter__(contextualized_node)
  23. def py__stop_iteration_returns(self):
  24. return ValueSet([compiled.builtin_from_name(self.inference_state, 'None')])
  25. # At the moment, safe values are simple values like "foo", 1 and not
  26. # lists/dicts. Therefore as a small speed optimization we can just do the
  27. # default instead of resolving the lazy wrapped values, that are just
  28. # doing this in the end as well.
  29. # This mostly speeds up patterns like `sys.version_info >= (3, 0)` in
  30. # typeshed.
  31. get_safe_value = Value.get_safe_value
  32. class GeneratorBase(LazyAttributeOverwrite, IterableMixin):
  33. array_type = None
  34. def _get_wrapped_value(self):
  35. instance, = self._get_cls().execute_annotation()
  36. return instance
  37. def _get_cls(self):
  38. generator, = self.inference_state.typing_module.py__getattribute__('Generator')
  39. return generator
  40. def py__bool__(self):
  41. return True
  42. @publish_method('__iter__')
  43. def _iter(self, arguments):
  44. return ValueSet([self])
  45. @publish_method('send')
  46. @publish_method('__next__')
  47. def _next(self, arguments):
  48. return ValueSet.from_sets(lazy_value.infer() for lazy_value in self.py__iter__())
  49. def py__stop_iteration_returns(self):
  50. return ValueSet([compiled.builtin_from_name(self.inference_state, 'None')])
  51. @property
  52. def name(self):
  53. return compiled.CompiledValueName(self, 'Generator')
  54. def get_annotated_class_object(self):
  55. from jedi.inference.gradual.generics import TupleGenericManager
  56. gen_values = self.merge_types_of_iterate().py__class__()
  57. gm = TupleGenericManager((gen_values, NO_VALUES, NO_VALUES))
  58. return self._get_cls().with_generics(gm)
  59. class Generator(GeneratorBase):
  60. """Handling of `yield` functions."""
  61. def __init__(self, inference_state, func_execution_context):
  62. super().__init__(inference_state)
  63. self._func_execution_context = func_execution_context
  64. def py__iter__(self, contextualized_node=None):
  65. iterators = self._func_execution_context.infer_annotations()
  66. if iterators:
  67. return iterators.iterate(contextualized_node)
  68. return self._func_execution_context.get_yield_lazy_values()
  69. def py__stop_iteration_returns(self):
  70. return self._func_execution_context.get_return_values()
  71. def __repr__(self):
  72. return "<%s of %s>" % (type(self).__name__, self._func_execution_context)
  73. def comprehension_from_atom(inference_state, value, atom):
  74. bracket = atom.children[0]
  75. test_list_comp = atom.children[1]
  76. if bracket == '{':
  77. if atom.children[1].children[1] == ':':
  78. sync_comp_for = test_list_comp.children[3]
  79. if sync_comp_for.type == 'comp_for':
  80. sync_comp_for = sync_comp_for.children[1]
  81. return DictComprehension(
  82. inference_state,
  83. value,
  84. sync_comp_for_node=sync_comp_for,
  85. key_node=test_list_comp.children[0],
  86. value_node=test_list_comp.children[2],
  87. )
  88. else:
  89. cls = SetComprehension
  90. elif bracket == '(':
  91. cls = GeneratorComprehension
  92. elif bracket == '[':
  93. cls = ListComprehension
  94. sync_comp_for = test_list_comp.children[1]
  95. if sync_comp_for.type == 'comp_for':
  96. sync_comp_for = sync_comp_for.children[1]
  97. return cls(
  98. inference_state,
  99. defining_context=value,
  100. sync_comp_for_node=sync_comp_for,
  101. entry_node=test_list_comp.children[0],
  102. )
  103. class ComprehensionMixin:
  104. @inference_state_method_cache()
  105. def _get_comp_for_context(self, parent_context, comp_for):
  106. return CompForContext(parent_context, comp_for)
  107. def _nested(self, comp_fors, parent_context=None):
  108. comp_for = comp_fors[0]
  109. is_async = comp_for.parent.type == 'comp_for'
  110. input_node = comp_for.children[3]
  111. parent_context = parent_context or self._defining_context
  112. input_types = parent_context.infer_node(input_node)
  113. cn = ContextualizedNode(parent_context, input_node)
  114. iterated = input_types.iterate(cn, is_async=is_async)
  115. exprlist = comp_for.children[1]
  116. for i, lazy_value in enumerate(iterated):
  117. types = lazy_value.infer()
  118. dct = unpack_tuple_to_dict(parent_context, types, exprlist)
  119. context = self._get_comp_for_context(
  120. parent_context,
  121. comp_for,
  122. )
  123. with context.predefine_names(comp_for, dct):
  124. try:
  125. yield from self._nested(comp_fors[1:], context)
  126. except IndexError:
  127. iterated = context.infer_node(self._entry_node)
  128. if self.array_type == 'dict':
  129. yield iterated, context.infer_node(self._value_node)
  130. else:
  131. yield iterated
  132. @inference_state_method_cache(default=[])
  133. @to_list
  134. def _iterate(self):
  135. comp_fors = tuple(get_sync_comp_fors(self._sync_comp_for_node))
  136. yield from self._nested(comp_fors)
  137. def py__iter__(self, contextualized_node=None):
  138. for set_ in self._iterate():
  139. yield LazyKnownValues(set_)
  140. def __repr__(self):
  141. return "<%s of %s>" % (type(self).__name__, self._sync_comp_for_node)
  142. class _DictMixin:
  143. def _get_generics(self):
  144. return tuple(c_set.py__class__() for c_set in self.get_mapping_item_values())
  145. class Sequence(LazyAttributeOverwrite, IterableMixin):
  146. api_type = 'instance'
  147. @property
  148. def name(self):
  149. return compiled.CompiledValueName(self, self.array_type)
  150. def _get_generics(self):
  151. return (self.merge_types_of_iterate().py__class__(),)
  152. @inference_state_method_cache(default=())
  153. def _cached_generics(self):
  154. return self._get_generics()
  155. def _get_wrapped_value(self):
  156. from jedi.inference.gradual.base import GenericClass
  157. from jedi.inference.gradual.generics import TupleGenericManager
  158. klass = compiled.builtin_from_name(self.inference_state, self.array_type)
  159. c, = GenericClass(
  160. klass,
  161. TupleGenericManager(self._cached_generics())
  162. ).execute_annotation()
  163. return c
  164. def py__bool__(self):
  165. return None # We don't know the length, because of appends.
  166. @safe_property
  167. def parent(self):
  168. return self.inference_state.builtins_module
  169. def py__getitem__(self, index_value_set, contextualized_node):
  170. if self.array_type == 'dict':
  171. return self._dict_values()
  172. return iterate_values(ValueSet([self]))
  173. class _BaseComprehension(ComprehensionMixin):
  174. def __init__(self, inference_state, defining_context, sync_comp_for_node, entry_node):
  175. assert sync_comp_for_node.type == 'sync_comp_for'
  176. super().__init__(inference_state)
  177. self._defining_context = defining_context
  178. self._sync_comp_for_node = sync_comp_for_node
  179. self._entry_node = entry_node
  180. class ListComprehension(_BaseComprehension, Sequence):
  181. array_type = 'list'
  182. def py__simple_getitem__(self, index):
  183. if isinstance(index, slice):
  184. return ValueSet([self])
  185. all_types = list(self.py__iter__())
  186. with reraise_getitem_errors(IndexError, TypeError):
  187. lazy_value = all_types[index]
  188. return lazy_value.infer()
  189. class SetComprehension(_BaseComprehension, Sequence):
  190. array_type = 'set'
  191. class GeneratorComprehension(_BaseComprehension, GeneratorBase):
  192. pass
  193. class _DictKeyMixin:
  194. # TODO merge with _DictMixin?
  195. def get_mapping_item_values(self):
  196. return self._dict_keys(), self._dict_values()
  197. def get_key_values(self):
  198. # TODO merge with _dict_keys?
  199. return self._dict_keys()
  200. class DictComprehension(ComprehensionMixin, Sequence, _DictKeyMixin):
  201. array_type = 'dict'
  202. def __init__(self, inference_state, defining_context, sync_comp_for_node, key_node, value_node):
  203. assert sync_comp_for_node.type == 'sync_comp_for'
  204. super().__init__(inference_state)
  205. self._defining_context = defining_context
  206. self._sync_comp_for_node = sync_comp_for_node
  207. self._entry_node = key_node
  208. self._value_node = value_node
  209. def py__iter__(self, contextualized_node=None):
  210. for keys, values in self._iterate():
  211. yield LazyKnownValues(keys)
  212. def py__simple_getitem__(self, index):
  213. for keys, values in self._iterate():
  214. for k in keys:
  215. # Be careful in the future if refactoring, index could be a
  216. # slice object.
  217. if k.get_safe_value(default=object()) == index:
  218. return values
  219. raise SimpleGetItemNotFound()
  220. def _dict_keys(self):
  221. return ValueSet.from_sets(keys for keys, values in self._iterate())
  222. def _dict_values(self):
  223. return ValueSet.from_sets(values for keys, values in self._iterate())
  224. @publish_method('values')
  225. def _imitate_values(self, arguments):
  226. lazy_value = LazyKnownValues(self._dict_values())
  227. return ValueSet([FakeList(self.inference_state, [lazy_value])])
  228. @publish_method('items')
  229. def _imitate_items(self, arguments):
  230. lazy_values = [
  231. LazyKnownValue(
  232. FakeTuple(
  233. self.inference_state,
  234. [LazyKnownValues(key),
  235. LazyKnownValues(value)]
  236. )
  237. )
  238. for key, value in self._iterate()
  239. ]
  240. return ValueSet([FakeList(self.inference_state, lazy_values)])
  241. def exact_key_items(self):
  242. # NOTE: A smarter thing can probably done here to achieve better
  243. # completions, but at least like this jedi doesn't crash
  244. return []
  245. class SequenceLiteralValue(Sequence):
  246. _TUPLE_LIKE = 'testlist_star_expr', 'testlist', 'subscriptlist'
  247. mapping = {'(': 'tuple',
  248. '[': 'list',
  249. '{': 'set'}
  250. def __init__(self, inference_state, defining_context, atom):
  251. super().__init__(inference_state)
  252. self.atom = atom
  253. self._defining_context = defining_context
  254. if self.atom.type in self._TUPLE_LIKE:
  255. self.array_type = 'tuple'
  256. else:
  257. self.array_type = SequenceLiteralValue.mapping[atom.children[0]]
  258. """The builtin name of the array (list, set, tuple or dict)."""
  259. def _get_generics(self):
  260. if self.array_type == 'tuple':
  261. return tuple(x.infer().py__class__() for x in self.py__iter__())
  262. return super()._get_generics()
  263. def py__simple_getitem__(self, index):
  264. """Here the index is an int/str. Raises IndexError/KeyError."""
  265. if isinstance(index, slice):
  266. return ValueSet([self])
  267. else:
  268. with reraise_getitem_errors(TypeError, KeyError, IndexError):
  269. node = self.get_tree_entries()[index]
  270. if node == ':' or node.type == 'subscript':
  271. return NO_VALUES
  272. return self._defining_context.infer_node(node)
  273. def py__iter__(self, contextualized_node=None):
  274. """
  275. While values returns the possible values for any array field, this
  276. function returns the value for a certain index.
  277. """
  278. for node in self.get_tree_entries():
  279. if node == ':' or node.type == 'subscript':
  280. # TODO this should probably use at least part of the code
  281. # of infer_subscript_list.
  282. yield LazyKnownValue(Slice(self._defining_context, None, None, None))
  283. else:
  284. yield LazyTreeValue(self._defining_context, node)
  285. yield from check_array_additions(self._defining_context, self)
  286. def py__len__(self):
  287. # This function is not really used often. It's more of a try.
  288. return len(self.get_tree_entries())
  289. def get_tree_entries(self):
  290. c = self.atom.children
  291. if self.atom.type in self._TUPLE_LIKE:
  292. return c[::2]
  293. array_node = c[1]
  294. if array_node in (']', '}', ')'):
  295. return [] # Direct closing bracket, doesn't contain items.
  296. if array_node.type == 'testlist_comp':
  297. # filter out (for now) pep 448 single-star unpacking
  298. return [value for value in array_node.children[::2]
  299. if value.type != "star_expr"]
  300. elif array_node.type == 'dictorsetmaker':
  301. kv = []
  302. iterator = iter(array_node.children)
  303. for key in iterator:
  304. if key == "**":
  305. # dict with pep 448 double-star unpacking
  306. # for now ignoring the values imported by **
  307. next(iterator)
  308. next(iterator, None) # Possible comma.
  309. else:
  310. op = next(iterator, None)
  311. if op is None or op == ',':
  312. if key.type == "star_expr":
  313. # pep 448 single-star unpacking
  314. # for now ignoring values imported by *
  315. pass
  316. else:
  317. kv.append(key) # A set.
  318. else:
  319. assert op == ':' # A dict.
  320. kv.append((key, next(iterator)))
  321. next(iterator, None) # Possible comma.
  322. return kv
  323. else:
  324. if array_node.type == "star_expr":
  325. # pep 448 single-star unpacking
  326. # for now ignoring values imported by *
  327. return []
  328. else:
  329. return [array_node]
  330. def __repr__(self):
  331. return "<%s of %s>" % (self.__class__.__name__, self.atom)
  332. class DictLiteralValue(_DictMixin, SequenceLiteralValue, _DictKeyMixin):
  333. array_type = 'dict'
  334. def __init__(self, inference_state, defining_context, atom):
  335. # Intentionally don't call the super class. This is definitely a sign
  336. # that the architecture is bad and we should refactor.
  337. Sequence.__init__(self, inference_state)
  338. self._defining_context = defining_context
  339. self.atom = atom
  340. def py__simple_getitem__(self, index):
  341. """Here the index is an int/str. Raises IndexError/KeyError."""
  342. compiled_value_index = compiled.create_simple_object(self.inference_state, index)
  343. for key, value in self.get_tree_entries():
  344. for k in self._defining_context.infer_node(key):
  345. for key_v in k.execute_operation(compiled_value_index, '=='):
  346. if key_v.get_safe_value():
  347. return self._defining_context.infer_node(value)
  348. raise SimpleGetItemNotFound('No key found in dictionary %s.' % self)
  349. def py__iter__(self, contextualized_node=None):
  350. """
  351. While values returns the possible values for any array field, this
  352. function returns the value for a certain index.
  353. """
  354. # Get keys.
  355. types = NO_VALUES
  356. for k, _ in self.get_tree_entries():
  357. types |= self._defining_context.infer_node(k)
  358. # We don't know which dict index comes first, therefore always
  359. # yield all the types.
  360. for _ in types:
  361. yield LazyKnownValues(types)
  362. @publish_method('values')
  363. def _imitate_values(self, arguments):
  364. lazy_value = LazyKnownValues(self._dict_values())
  365. return ValueSet([FakeList(self.inference_state, [lazy_value])])
  366. @publish_method('items')
  367. def _imitate_items(self, arguments):
  368. lazy_values = [
  369. LazyKnownValue(FakeTuple(
  370. self.inference_state,
  371. (LazyTreeValue(self._defining_context, key_node),
  372. LazyTreeValue(self._defining_context, value_node))
  373. )) for key_node, value_node in self.get_tree_entries()
  374. ]
  375. return ValueSet([FakeList(self.inference_state, lazy_values)])
  376. def exact_key_items(self):
  377. """
  378. Returns a generator of tuples like dict.items(), where the key is
  379. resolved (as a string) and the values are still lazy values.
  380. """
  381. for key_node, value in self.get_tree_entries():
  382. for key in self._defining_context.infer_node(key_node):
  383. if is_string(key):
  384. yield key.get_safe_value(), LazyTreeValue(self._defining_context, value)
  385. def _dict_values(self):
  386. return ValueSet.from_sets(
  387. self._defining_context.infer_node(v)
  388. for k, v in self.get_tree_entries()
  389. )
  390. def _dict_keys(self):
  391. return ValueSet.from_sets(
  392. self._defining_context.infer_node(k)
  393. for k, v in self.get_tree_entries()
  394. )
  395. class _FakeSequence(Sequence):
  396. def __init__(self, inference_state, lazy_value_list):
  397. """
  398. type should be one of "tuple", "list"
  399. """
  400. super().__init__(inference_state)
  401. self._lazy_value_list = lazy_value_list
  402. def py__simple_getitem__(self, index):
  403. if isinstance(index, slice):
  404. return ValueSet([self])
  405. with reraise_getitem_errors(IndexError, TypeError):
  406. lazy_value = self._lazy_value_list[index]
  407. return lazy_value.infer()
  408. def py__iter__(self, contextualized_node=None):
  409. return self._lazy_value_list
  410. def py__bool__(self):
  411. return bool(len(self._lazy_value_list))
  412. def __repr__(self):
  413. return "<%s of %s>" % (type(self).__name__, self._lazy_value_list)
  414. class FakeTuple(_FakeSequence):
  415. array_type = 'tuple'
  416. class FakeList(_FakeSequence):
  417. array_type = 'tuple'
  418. class FakeDict(_DictMixin, Sequence, _DictKeyMixin):
  419. array_type = 'dict'
  420. def __init__(self, inference_state, dct):
  421. super().__init__(inference_state)
  422. self._dct = dct
  423. def py__iter__(self, contextualized_node=None):
  424. for key in self._dct:
  425. yield LazyKnownValue(compiled.create_simple_object(self.inference_state, key))
  426. def py__simple_getitem__(self, index):
  427. with reraise_getitem_errors(KeyError, TypeError):
  428. lazy_value = self._dct[index]
  429. return lazy_value.infer()
  430. @publish_method('values')
  431. def _values(self, arguments):
  432. return ValueSet([FakeTuple(
  433. self.inference_state,
  434. [LazyKnownValues(self._dict_values())]
  435. )])
  436. def _dict_values(self):
  437. return ValueSet.from_sets(lazy_value.infer() for lazy_value in self._dct.values())
  438. def _dict_keys(self):
  439. return ValueSet.from_sets(lazy_value.infer() for lazy_value in self.py__iter__())
  440. def exact_key_items(self):
  441. return self._dct.items()
  442. def __repr__(self):
  443. return '<%s: %s>' % (self.__class__.__name__, self._dct)
  444. class MergedArray(Sequence):
  445. def __init__(self, inference_state, arrays):
  446. super().__init__(inference_state)
  447. self.array_type = arrays[-1].array_type
  448. self._arrays = arrays
  449. def py__iter__(self, contextualized_node=None):
  450. for array in self._arrays:
  451. yield from array.py__iter__()
  452. def py__simple_getitem__(self, index):
  453. return ValueSet.from_sets(lazy_value.infer() for lazy_value in self.py__iter__())
  454. def unpack_tuple_to_dict(context, types, exprlist):
  455. """
  456. Unpacking tuple assignments in for statements and expr_stmts.
  457. """
  458. if exprlist.type == 'name':
  459. return {exprlist.value: types}
  460. elif exprlist.type == 'atom' and exprlist.children[0] in ('(', '['):
  461. return unpack_tuple_to_dict(context, types, exprlist.children[1])
  462. elif exprlist.type in ('testlist', 'testlist_comp', 'exprlist',
  463. 'testlist_star_expr'):
  464. dct = {}
  465. parts = iter(exprlist.children[::2])
  466. n = 0
  467. for lazy_value in types.iterate(ContextualizedNode(context, exprlist)):
  468. n += 1
  469. try:
  470. part = next(parts)
  471. except StopIteration:
  472. analysis.add(context, 'value-error-too-many-values', part,
  473. message="ValueError: too many values to unpack (expected %s)" % n)
  474. else:
  475. dct.update(unpack_tuple_to_dict(context, lazy_value.infer(), part))
  476. has_parts = next(parts, None)
  477. if types and has_parts is not None:
  478. analysis.add(context, 'value-error-too-few-values', has_parts,
  479. message="ValueError: need more than %s values to unpack" % n)
  480. return dct
  481. elif exprlist.type == 'power' or exprlist.type == 'atom_expr':
  482. # Something like ``arr[x], var = ...``.
  483. # This is something that is not yet supported, would also be difficult
  484. # to write into a dict.
  485. return {}
  486. elif exprlist.type == 'star_expr': # `a, *b, c = x` type unpackings
  487. # Currently we're not supporting them.
  488. return {}
  489. raise NotImplementedError
  490. class Slice(LazyValueWrapper):
  491. def __init__(self, python_context, start, stop, step):
  492. self.inference_state = python_context.inference_state
  493. self._context = python_context
  494. # All of them are either a Precedence or None.
  495. self._start = start
  496. self._stop = stop
  497. self._step = step
  498. def _get_wrapped_value(self):
  499. value = compiled.builtin_from_name(self._context.inference_state, 'slice')
  500. slice_value, = value.execute_with_values()
  501. return slice_value
  502. def get_safe_value(self, default=sentinel):
  503. """
  504. Imitate CompiledValue.obj behavior and return a ``builtin.slice()``
  505. object.
  506. """
  507. def get(element):
  508. if element is None:
  509. return None
  510. result = self._context.infer_node(element)
  511. if len(result) != 1:
  512. # For simplicity, we want slices to be clear defined with just
  513. # one type. Otherwise we will return an empty slice object.
  514. raise IndexError
  515. value, = result
  516. return get_int_or_none(value)
  517. try:
  518. return slice(get(self._start), get(self._stop), get(self._step))
  519. except IndexError:
  520. return slice(None, None, None)