stdlib.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. """
  2. Implementations of standard library functions, because it's not possible to
  3. understand them with Jedi.
  4. To add a new implementation, create a function and add it to the
  5. ``_implemented`` dict at the bottom of this module.
  6. Note that this module exists only to implement very specific functionality in
  7. the standard library. The usual way to understand the standard library is the
  8. compiled module that returns the types for C-builtins.
  9. """
  10. import parso
  11. import os
  12. from inspect import Parameter
  13. from jedi import debug
  14. from jedi.inference.utils import safe_property
  15. from jedi.inference.helpers import get_str_or_none
  16. from jedi.inference.arguments import iterate_argument_clinic, ParamIssue, \
  17. repack_with_argument_clinic, AbstractArguments, TreeArgumentsWrapper
  18. from jedi.inference import analysis
  19. from jedi.inference import compiled
  20. from jedi.inference.value.instance import \
  21. AnonymousMethodExecutionContext, MethodExecutionContext
  22. from jedi.inference.base_value import ContextualizedNode, \
  23. NO_VALUES, ValueSet, ValueWrapper, LazyValueWrapper
  24. from jedi.inference.value import ClassValue, ModuleValue
  25. from jedi.inference.value.klass import ClassMixin
  26. from jedi.inference.value.function import FunctionMixin
  27. from jedi.inference.value import iterable
  28. from jedi.inference.lazy_value import LazyTreeValue, LazyKnownValue, \
  29. LazyKnownValues
  30. from jedi.inference.names import ValueName, BaseTreeParamName
  31. from jedi.inference.filters import AttributeOverwrite, publish_method, \
  32. ParserTreeFilter, DictFilter
  33. from jedi.inference.signature import AbstractSignature, SignatureWrapper
  34. # Copied from Python 3.6's stdlib.
  35. _NAMEDTUPLE_CLASS_TEMPLATE = """\
  36. _property = property
  37. _tuple = tuple
  38. from operator import itemgetter as _itemgetter
  39. from collections import OrderedDict
  40. class {typename}(tuple):
  41. __slots__ = ()
  42. _fields = {field_names!r}
  43. def __new__(_cls, {arg_list}):
  44. 'Create new instance of {typename}({arg_list})'
  45. return _tuple.__new__(_cls, ({arg_list}))
  46. @classmethod
  47. def _make(cls, iterable, new=tuple.__new__, len=len):
  48. 'Make a new {typename} object from a sequence or iterable'
  49. result = new(cls, iterable)
  50. if len(result) != {num_fields:d}:
  51. raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result))
  52. return result
  53. def _replace(_self, **kwds):
  54. 'Return a new {typename} object replacing specified fields with new values'
  55. result = _self._make(map(kwds.pop, {field_names!r}, _self))
  56. if kwds:
  57. raise ValueError('Got unexpected field names: %r' % list(kwds))
  58. return result
  59. def __repr__(self):
  60. 'Return a nicely formatted representation string'
  61. return self.__class__.__name__ + '({repr_fmt})' % self
  62. def _asdict(self):
  63. 'Return a new OrderedDict which maps field names to their values.'
  64. return OrderedDict(zip(self._fields, self))
  65. def __getnewargs__(self):
  66. 'Return self as a plain tuple. Used by copy and pickle.'
  67. return tuple(self)
  68. # These methods were added by Jedi.
  69. # __new__ doesn't really work with Jedi. So adding this to nametuples seems
  70. # like the easiest way.
  71. def __init__(self, {arg_list}):
  72. 'A helper function for namedtuple.'
  73. self.__iterable = ({arg_list})
  74. def __iter__(self):
  75. for i in self.__iterable:
  76. yield i
  77. def __getitem__(self, y):
  78. return self.__iterable[y]
  79. {field_defs}
  80. """
  81. _NAMEDTUPLE_FIELD_TEMPLATE = '''\
  82. {name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}')
  83. '''
  84. def execute(callback):
  85. def wrapper(value, arguments):
  86. def call():
  87. return callback(value, arguments=arguments)
  88. try:
  89. obj_name = value.name.string_name
  90. except AttributeError:
  91. pass
  92. else:
  93. p = value.parent_context
  94. if p is not None and p.is_builtins_module():
  95. module_name = 'builtins'
  96. elif p is not None and p.is_module():
  97. module_name = p.py__name__()
  98. else:
  99. return call()
  100. if value.is_bound_method() or value.is_instance():
  101. # value can be an instance for example if it is a partial
  102. # object.
  103. return call()
  104. # for now we just support builtin functions.
  105. try:
  106. func = _implemented[module_name][obj_name]
  107. except KeyError:
  108. pass
  109. else:
  110. return func(value, arguments=arguments, callback=call)
  111. return call()
  112. return wrapper
  113. def _follow_param(inference_state, arguments, index):
  114. try:
  115. key, lazy_value = list(arguments.unpack())[index]
  116. except IndexError:
  117. return NO_VALUES
  118. else:
  119. return lazy_value.infer()
  120. def argument_clinic(clinic_string, want_value=False, want_context=False,
  121. want_arguments=False, want_inference_state=False,
  122. want_callback=False):
  123. """
  124. Works like Argument Clinic (PEP 436), to validate function params.
  125. """
  126. def f(func):
  127. def wrapper(value, arguments, callback):
  128. try:
  129. args = tuple(iterate_argument_clinic(
  130. value.inference_state, arguments, clinic_string))
  131. except ParamIssue:
  132. return NO_VALUES
  133. debug.dbg('builtin start %s' % value, color='MAGENTA')
  134. kwargs = {}
  135. if want_context:
  136. kwargs['context'] = arguments.context
  137. if want_value:
  138. kwargs['value'] = value
  139. if want_inference_state:
  140. kwargs['inference_state'] = value.inference_state
  141. if want_arguments:
  142. kwargs['arguments'] = arguments
  143. if want_callback:
  144. kwargs['callback'] = callback
  145. result = func(*args, **kwargs)
  146. debug.dbg('builtin end: %s', result, color='MAGENTA')
  147. return result
  148. return wrapper
  149. return f
  150. @argument_clinic('iterator[, default], /', want_inference_state=True)
  151. def builtins_next(iterators, defaults, inference_state):
  152. # TODO theoretically we have to check here if something is an iterator.
  153. # That is probably done by checking if it's not a class.
  154. return defaults | iterators.py__getattribute__('__next__').execute_with_values()
  155. @argument_clinic('iterator[, default], /')
  156. def builtins_iter(iterators_or_callables, defaults):
  157. # TODO implement this if it's a callable.
  158. return iterators_or_callables.py__getattribute__('__iter__').execute_with_values()
  159. @argument_clinic('object, name[, default], /')
  160. def builtins_getattr(objects, names, defaults=None):
  161. # follow the first param
  162. for value in objects:
  163. for name in names:
  164. string = get_str_or_none(name)
  165. if string is None:
  166. debug.warning('getattr called without str')
  167. continue
  168. else:
  169. return value.py__getattribute__(string)
  170. return NO_VALUES
  171. @argument_clinic('object[, bases, dict], /')
  172. def builtins_type(objects, bases, dicts):
  173. if bases or dicts:
  174. # It's a type creation... maybe someday...
  175. return NO_VALUES
  176. else:
  177. return objects.py__class__()
  178. class SuperInstance(LazyValueWrapper):
  179. """To be used like the object ``super`` returns."""
  180. def __init__(self, inference_state, instance):
  181. self.inference_state = inference_state
  182. self._instance = instance # Corresponds to super().__self__
  183. def _get_bases(self):
  184. return self._instance.py__class__().py__bases__()
  185. def _get_wrapped_value(self):
  186. objs = self._get_bases()[0].infer().execute_with_values()
  187. if not objs:
  188. # This is just a fallback and will only be used, if it's not
  189. # possible to find a class
  190. return self._instance
  191. return next(iter(objs))
  192. def get_filters(self, origin_scope=None):
  193. for b in self._get_bases():
  194. for value in b.infer().execute_with_values():
  195. for f in value.get_filters():
  196. yield f
  197. @argument_clinic('[type[, value]], /', want_context=True)
  198. def builtins_super(types, objects, context):
  199. instance = None
  200. if isinstance(context, AnonymousMethodExecutionContext):
  201. instance = context.instance
  202. elif isinstance(context, MethodExecutionContext):
  203. instance = context.instance
  204. if instance is None:
  205. return NO_VALUES
  206. return ValueSet({SuperInstance(instance.inference_state, instance)})
  207. class ReversedObject(AttributeOverwrite):
  208. def __init__(self, reversed_obj, iter_list):
  209. super().__init__(reversed_obj)
  210. self._iter_list = iter_list
  211. def py__iter__(self, contextualized_node=None):
  212. return self._iter_list
  213. @publish_method('__next__')
  214. def _next(self, arguments):
  215. return ValueSet.from_sets(
  216. lazy_value.infer() for lazy_value in self._iter_list
  217. )
  218. @argument_clinic('sequence, /', want_value=True, want_arguments=True)
  219. def builtins_reversed(sequences, value, arguments):
  220. # While we could do without this variable (just by using sequences), we
  221. # want static analysis to work well. Therefore we need to generated the
  222. # values again.
  223. key, lazy_value = next(arguments.unpack())
  224. cn = None
  225. if isinstance(lazy_value, LazyTreeValue):
  226. cn = ContextualizedNode(lazy_value.context, lazy_value.data)
  227. ordered = list(sequences.iterate(cn))
  228. # Repack iterator values and then run it the normal way. This is
  229. # necessary, because `reversed` is a function and autocompletion
  230. # would fail in certain cases like `reversed(x).__iter__` if we
  231. # just returned the result directly.
  232. seq, = value.inference_state.typing_module.py__getattribute__('Iterator').execute_with_values()
  233. return ValueSet([ReversedObject(seq, list(reversed(ordered)))])
  234. @argument_clinic('value, type, /', want_arguments=True, want_inference_state=True)
  235. def builtins_isinstance(objects, types, arguments, inference_state):
  236. bool_results = set()
  237. for o in objects:
  238. cls = o.py__class__()
  239. try:
  240. cls.py__bases__
  241. except AttributeError:
  242. # This is temporary. Everything should have a class attribute in
  243. # Python?! Maybe we'll leave it here, because some numpy objects or
  244. # whatever might not.
  245. bool_results = set([True, False])
  246. break
  247. mro = list(cls.py__mro__())
  248. for cls_or_tup in types:
  249. if cls_or_tup.is_class():
  250. bool_results.add(cls_or_tup in mro)
  251. elif cls_or_tup.name.string_name == 'tuple' \
  252. and cls_or_tup.get_root_context().is_builtins_module():
  253. # Check for tuples.
  254. classes = ValueSet.from_sets(
  255. lazy_value.infer()
  256. for lazy_value in cls_or_tup.iterate()
  257. )
  258. bool_results.add(any(cls in mro for cls in classes))
  259. else:
  260. _, lazy_value = list(arguments.unpack())[1]
  261. if isinstance(lazy_value, LazyTreeValue):
  262. node = lazy_value.data
  263. message = 'TypeError: isinstance() arg 2 must be a ' \
  264. 'class, type, or tuple of classes and types, ' \
  265. 'not %s.' % cls_or_tup
  266. analysis.add(lazy_value.context, 'type-error-isinstance', node, message)
  267. return ValueSet(
  268. compiled.builtin_from_name(inference_state, str(b))
  269. for b in bool_results
  270. )
  271. class StaticMethodObject(ValueWrapper):
  272. def py__get__(self, instance, class_value):
  273. return ValueSet([self._wrapped_value])
  274. @argument_clinic('sequence, /')
  275. def builtins_staticmethod(functions):
  276. return ValueSet(StaticMethodObject(f) for f in functions)
  277. class ClassMethodObject(ValueWrapper):
  278. def __init__(self, class_method_obj, function):
  279. super().__init__(class_method_obj)
  280. self._function = function
  281. def py__get__(self, instance, class_value):
  282. return ValueSet([
  283. ClassMethodGet(__get__, class_value, self._function)
  284. for __get__ in self._wrapped_value.py__getattribute__('__get__')
  285. ])
  286. class ClassMethodGet(ValueWrapper):
  287. def __init__(self, get_method, klass, function):
  288. super().__init__(get_method)
  289. self._class = klass
  290. self._function = function
  291. def get_signatures(self):
  292. return [sig.bind(self._function) for sig in self._function.get_signatures()]
  293. def py__call__(self, arguments):
  294. return self._function.execute(ClassMethodArguments(self._class, arguments))
  295. class ClassMethodArguments(TreeArgumentsWrapper):
  296. def __init__(self, klass, arguments):
  297. super().__init__(arguments)
  298. self._class = klass
  299. def unpack(self, func=None):
  300. yield None, LazyKnownValue(self._class)
  301. for values in self._wrapped_arguments.unpack(func):
  302. yield values
  303. @argument_clinic('sequence, /', want_value=True, want_arguments=True)
  304. def builtins_classmethod(functions, value, arguments):
  305. return ValueSet(
  306. ClassMethodObject(class_method_object, function)
  307. for class_method_object in value.py__call__(arguments=arguments)
  308. for function in functions
  309. )
  310. class PropertyObject(AttributeOverwrite, ValueWrapper):
  311. api_type = 'property'
  312. def __init__(self, property_obj, function):
  313. super().__init__(property_obj)
  314. self._function = function
  315. def py__get__(self, instance, class_value):
  316. if instance is None:
  317. return ValueSet([self])
  318. return self._function.execute_with_values(instance)
  319. @publish_method('deleter')
  320. @publish_method('getter')
  321. @publish_method('setter')
  322. def _return_self(self, arguments):
  323. return ValueSet({self})
  324. @argument_clinic('func, /', want_callback=True)
  325. def builtins_property(functions, callback):
  326. return ValueSet(
  327. PropertyObject(property_value, function)
  328. for property_value in callback()
  329. for function in functions
  330. )
  331. def collections_namedtuple(value, arguments, callback):
  332. """
  333. Implementation of the namedtuple function.
  334. This has to be done by processing the namedtuple class template and
  335. inferring the result.
  336. """
  337. inference_state = value.inference_state
  338. # Process arguments
  339. name = 'jedi_unknown_namedtuple'
  340. for c in _follow_param(inference_state, arguments, 0):
  341. x = get_str_or_none(c)
  342. if x is not None:
  343. name = x
  344. break
  345. # TODO here we only use one of the types, we should use all.
  346. param_values = _follow_param(inference_state, arguments, 1)
  347. if not param_values:
  348. return NO_VALUES
  349. _fields = list(param_values)[0]
  350. string = get_str_or_none(_fields)
  351. if string is not None:
  352. fields = string.replace(',', ' ').split()
  353. elif isinstance(_fields, iterable.Sequence):
  354. fields = [
  355. get_str_or_none(v)
  356. for lazy_value in _fields.py__iter__()
  357. for v in lazy_value.infer()
  358. ]
  359. fields = [f for f in fields if f is not None]
  360. else:
  361. return NO_VALUES
  362. # Build source code
  363. code = _NAMEDTUPLE_CLASS_TEMPLATE.format(
  364. typename=name,
  365. field_names=tuple(fields),
  366. num_fields=len(fields),
  367. arg_list=repr(tuple(fields)).replace("'", "")[1:-1],
  368. repr_fmt='',
  369. field_defs='\n'.join(_NAMEDTUPLE_FIELD_TEMPLATE.format(index=index, name=name)
  370. for index, name in enumerate(fields))
  371. )
  372. # Parse source code
  373. module = inference_state.grammar.parse(code)
  374. generated_class = next(module.iter_classdefs())
  375. parent_context = ModuleValue(
  376. inference_state, module,
  377. code_lines=parso.split_lines(code, keepends=True),
  378. ).as_context()
  379. return ValueSet([ClassValue(inference_state, parent_context, generated_class)])
  380. class PartialObject(ValueWrapper):
  381. def __init__(self, actual_value, arguments, instance=None):
  382. super().__init__(actual_value)
  383. self._arguments = arguments
  384. self._instance = instance
  385. def _get_functions(self, unpacked_arguments):
  386. key, lazy_value = next(unpacked_arguments, (None, None))
  387. if key is not None or lazy_value is None:
  388. debug.warning("Partial should have a proper function %s", self._arguments)
  389. return None
  390. return lazy_value.infer()
  391. def get_signatures(self):
  392. unpacked_arguments = self._arguments.unpack()
  393. funcs = self._get_functions(unpacked_arguments)
  394. if funcs is None:
  395. return []
  396. arg_count = 0
  397. if self._instance is not None:
  398. arg_count = 1
  399. keys = set()
  400. for key, _ in unpacked_arguments:
  401. if key is None:
  402. arg_count += 1
  403. else:
  404. keys.add(key)
  405. return [PartialSignature(s, arg_count, keys) for s in funcs.get_signatures()]
  406. def py__call__(self, arguments):
  407. funcs = self._get_functions(self._arguments.unpack())
  408. if funcs is None:
  409. return NO_VALUES
  410. return funcs.execute(
  411. MergedPartialArguments(self._arguments, arguments, self._instance)
  412. )
  413. def py__doc__(self):
  414. """
  415. In CPython partial does not replace the docstring. However we are still
  416. imitating it here, because we want this docstring to be worth something
  417. for the user.
  418. """
  419. callables = self._get_functions(self._arguments.unpack())
  420. if callables is None:
  421. return ''
  422. for callable_ in callables:
  423. return callable_.py__doc__()
  424. return ''
  425. def py__get__(self, instance, class_value):
  426. return ValueSet([self])
  427. class PartialMethodObject(PartialObject):
  428. def py__get__(self, instance, class_value):
  429. if instance is None:
  430. return ValueSet([self])
  431. return ValueSet([PartialObject(self._wrapped_value, self._arguments, instance)])
  432. class PartialSignature(SignatureWrapper):
  433. def __init__(self, wrapped_signature, skipped_arg_count, skipped_arg_set):
  434. super().__init__(wrapped_signature)
  435. self._skipped_arg_count = skipped_arg_count
  436. self._skipped_arg_set = skipped_arg_set
  437. def get_param_names(self, resolve_stars=False):
  438. names = self._wrapped_signature.get_param_names()[self._skipped_arg_count:]
  439. return [n for n in names if n.string_name not in self._skipped_arg_set]
  440. class MergedPartialArguments(AbstractArguments):
  441. def __init__(self, partial_arguments, call_arguments, instance=None):
  442. self._partial_arguments = partial_arguments
  443. self._call_arguments = call_arguments
  444. self._instance = instance
  445. def unpack(self, funcdef=None):
  446. unpacked = self._partial_arguments.unpack(funcdef)
  447. # Ignore this one, it's the function. It was checked before that it's
  448. # there.
  449. next(unpacked, None)
  450. if self._instance is not None:
  451. yield None, LazyKnownValue(self._instance)
  452. for key_lazy_value in unpacked:
  453. yield key_lazy_value
  454. for key_lazy_value in self._call_arguments.unpack(funcdef):
  455. yield key_lazy_value
  456. def functools_partial(value, arguments, callback):
  457. return ValueSet(
  458. PartialObject(instance, arguments)
  459. for instance in value.py__call__(arguments)
  460. )
  461. def functools_partialmethod(value, arguments, callback):
  462. return ValueSet(
  463. PartialMethodObject(instance, arguments)
  464. for instance in value.py__call__(arguments)
  465. )
  466. @argument_clinic('first, /')
  467. def _return_first_param(firsts):
  468. return firsts
  469. @argument_clinic('seq')
  470. def _random_choice(sequences):
  471. return ValueSet.from_sets(
  472. lazy_value.infer()
  473. for sequence in sequences
  474. for lazy_value in sequence.py__iter__()
  475. )
  476. def _dataclass(value, arguments, callback):
  477. for c in _follow_param(value.inference_state, arguments, 0):
  478. if c.is_class():
  479. return ValueSet([DataclassWrapper(c)])
  480. else:
  481. return ValueSet([value])
  482. return NO_VALUES
  483. class DataclassWrapper(ValueWrapper, ClassMixin):
  484. def get_signatures(self):
  485. param_names = []
  486. for cls in reversed(list(self.py__mro__())):
  487. if isinstance(cls, DataclassWrapper):
  488. filter_ = cls.as_context().get_global_filter()
  489. # .values ordering is not guaranteed, at least not in
  490. # Python < 3.6, when dicts where not ordered, which is an
  491. # implementation detail anyway.
  492. for name in sorted(filter_.values(), key=lambda name: name.start_pos):
  493. d = name.tree_name.get_definition()
  494. annassign = d.children[1]
  495. if d.type == 'expr_stmt' and annassign.type == 'annassign':
  496. if len(annassign.children) < 4:
  497. default = None
  498. else:
  499. default = annassign.children[3]
  500. param_names.append(DataclassParamName(
  501. parent_context=cls.parent_context,
  502. tree_name=name.tree_name,
  503. annotation_node=annassign.children[1],
  504. default_node=default,
  505. ))
  506. return [DataclassSignature(cls, param_names)]
  507. class DataclassSignature(AbstractSignature):
  508. def __init__(self, value, param_names):
  509. super().__init__(value)
  510. self._param_names = param_names
  511. def get_param_names(self, resolve_stars=False):
  512. return self._param_names
  513. class DataclassParamName(BaseTreeParamName):
  514. def __init__(self, parent_context, tree_name, annotation_node, default_node):
  515. super().__init__(parent_context, tree_name)
  516. self.annotation_node = annotation_node
  517. self.default_node = default_node
  518. def get_kind(self):
  519. return Parameter.POSITIONAL_OR_KEYWORD
  520. def infer(self):
  521. if self.annotation_node is None:
  522. return NO_VALUES
  523. else:
  524. return self.parent_context.infer_node(self.annotation_node)
  525. class ItemGetterCallable(ValueWrapper):
  526. def __init__(self, instance, args_value_set):
  527. super().__init__(instance)
  528. self._args_value_set = args_value_set
  529. @repack_with_argument_clinic('item, /')
  530. def py__call__(self, item_value_set):
  531. value_set = NO_VALUES
  532. for args_value in self._args_value_set:
  533. lazy_values = list(args_value.py__iter__())
  534. if len(lazy_values) == 1:
  535. # TODO we need to add the contextualized value.
  536. value_set |= item_value_set.get_item(lazy_values[0].infer(), None)
  537. else:
  538. value_set |= ValueSet([iterable.FakeList(
  539. self._wrapped_value.inference_state,
  540. [
  541. LazyKnownValues(item_value_set.get_item(lazy_value.infer(), None))
  542. for lazy_value in lazy_values
  543. ],
  544. )])
  545. return value_set
  546. @argument_clinic('func, /')
  547. def _functools_wraps(funcs):
  548. return ValueSet(WrapsCallable(func) for func in funcs)
  549. class WrapsCallable(ValueWrapper):
  550. # XXX this is not the correct wrapped value, it should be a weird
  551. # partials object, but it doesn't matter, because it's always used as a
  552. # decorator anyway.
  553. @repack_with_argument_clinic('func, /')
  554. def py__call__(self, funcs):
  555. return ValueSet({Wrapped(func, self._wrapped_value) for func in funcs})
  556. class Wrapped(ValueWrapper, FunctionMixin):
  557. def __init__(self, func, original_function):
  558. super().__init__(func)
  559. self._original_function = original_function
  560. @property
  561. def name(self):
  562. return self._original_function.name
  563. def get_signature_functions(self):
  564. return [self]
  565. @argument_clinic('*args, /', want_value=True, want_arguments=True)
  566. def _operator_itemgetter(args_value_set, value, arguments):
  567. return ValueSet([
  568. ItemGetterCallable(instance, args_value_set)
  569. for instance in value.py__call__(arguments)
  570. ])
  571. def _create_string_input_function(func):
  572. @argument_clinic('string, /', want_value=True, want_arguments=True)
  573. def wrapper(strings, value, arguments):
  574. def iterate():
  575. for value in strings:
  576. s = get_str_or_none(value)
  577. if s is not None:
  578. s = func(s)
  579. yield compiled.create_simple_object(value.inference_state, s)
  580. values = ValueSet(iterate())
  581. if values:
  582. return values
  583. return value.py__call__(arguments)
  584. return wrapper
  585. @argument_clinic('*args, /', want_callback=True)
  586. def _os_path_join(args_set, callback):
  587. if len(args_set) == 1:
  588. string = ''
  589. sequence, = args_set
  590. is_first = True
  591. for lazy_value in sequence.py__iter__():
  592. string_values = lazy_value.infer()
  593. if len(string_values) != 1:
  594. break
  595. s = get_str_or_none(next(iter(string_values)))
  596. if s is None:
  597. break
  598. if not is_first:
  599. string += os.path.sep
  600. string += s
  601. is_first = False
  602. else:
  603. return ValueSet([compiled.create_simple_object(sequence.inference_state, string)])
  604. return callback()
  605. _implemented = {
  606. 'builtins': {
  607. 'getattr': builtins_getattr,
  608. 'type': builtins_type,
  609. 'super': builtins_super,
  610. 'reversed': builtins_reversed,
  611. 'isinstance': builtins_isinstance,
  612. 'next': builtins_next,
  613. 'iter': builtins_iter,
  614. 'staticmethod': builtins_staticmethod,
  615. 'classmethod': builtins_classmethod,
  616. 'property': builtins_property,
  617. },
  618. 'copy': {
  619. 'copy': _return_first_param,
  620. 'deepcopy': _return_first_param,
  621. },
  622. 'json': {
  623. 'load': lambda value, arguments, callback: NO_VALUES,
  624. 'loads': lambda value, arguments, callback: NO_VALUES,
  625. },
  626. 'collections': {
  627. 'namedtuple': collections_namedtuple,
  628. },
  629. 'functools': {
  630. 'partial': functools_partial,
  631. 'partialmethod': functools_partialmethod,
  632. 'wraps': _functools_wraps,
  633. },
  634. '_weakref': {
  635. 'proxy': _return_first_param,
  636. },
  637. 'random': {
  638. 'choice': _random_choice,
  639. },
  640. 'operator': {
  641. 'itemgetter': _operator_itemgetter,
  642. },
  643. 'abc': {
  644. # Not sure if this is necessary, but it's used a lot in typeshed and
  645. # it's for now easier to just pass the function.
  646. 'abstractmethod': _return_first_param,
  647. },
  648. 'typing': {
  649. # The _alias function just leads to some annoying type inference.
  650. # Therefore, just make it return nothing, which leads to the stubs
  651. # being used instead. This only matters for 3.7+.
  652. '_alias': lambda value, arguments, callback: NO_VALUES,
  653. # runtime_checkable doesn't really change anything and is just
  654. # adding logs for infering stuff, so we can safely ignore it.
  655. 'runtime_checkable': lambda value, arguments, callback: NO_VALUES,
  656. },
  657. 'dataclasses': {
  658. # For now this works at least better than Jedi trying to understand it.
  659. 'dataclass': _dataclass
  660. },
  661. # attrs exposes declaration interface roughly compatible with dataclasses
  662. # via attrs.define, attrs.frozen and attrs.mutable
  663. # https://www.attrs.org/en/stable/names.html
  664. 'attr': {
  665. 'define': _dataclass,
  666. 'frozen': _dataclass,
  667. },
  668. 'attrs': {
  669. 'define': _dataclass,
  670. 'frozen': _dataclass,
  671. },
  672. 'os.path': {
  673. 'dirname': _create_string_input_function(os.path.dirname),
  674. 'abspath': _create_string_input_function(os.path.abspath),
  675. 'relpath': _create_string_input_function(os.path.relpath),
  676. 'join': _os_path_join,
  677. }
  678. }
  679. def get_metaclass_filters(func):
  680. def wrapper(cls, metaclasses, is_instance):
  681. for metaclass in metaclasses:
  682. if metaclass.py__name__() == 'EnumMeta' \
  683. and metaclass.get_root_context().py__name__() == 'enum':
  684. filter_ = ParserTreeFilter(parent_context=cls.as_context())
  685. return [DictFilter({
  686. name.string_name: EnumInstance(cls, name).name
  687. for name in filter_.values()
  688. })]
  689. return func(cls, metaclasses, is_instance)
  690. return wrapper
  691. class EnumInstance(LazyValueWrapper):
  692. def __init__(self, cls, name):
  693. self.inference_state = cls.inference_state
  694. self._cls = cls # Corresponds to super().__self__
  695. self._name = name
  696. self.tree_node = self._name.tree_name
  697. @safe_property
  698. def name(self):
  699. return ValueName(self, self._name.tree_name)
  700. def _get_wrapped_value(self):
  701. n = self._name.string_name
  702. if n.startswith('__') and n.endswith('__') or self._name.api_type == 'function':
  703. inferred = self._name.infer()
  704. if inferred:
  705. return next(iter(inferred))
  706. o, = self.inference_state.builtins_module.py__getattribute__('object')
  707. return o
  708. value, = self._cls.execute_with_values()
  709. return value
  710. def get_filters(self, origin_scope=None):
  711. yield DictFilter(dict(
  712. name=compiled.create_simple_object(self.inference_state, self._name.string_name).name,
  713. value=self._name,
  714. ))
  715. for f in self._get_wrapped_value().get_filters():
  716. yield f
  717. def tree_name_to_values(func):
  718. def wrapper(inference_state, context, tree_name):
  719. if tree_name.value == 'sep' and context.is_module() and context.py__name__() == 'os.path':
  720. return ValueSet({
  721. compiled.create_simple_object(inference_state, os.path.sep),
  722. })
  723. return func(inference_state, context, tree_name)
  724. return wrapper