arguments.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import re
  2. from itertools import zip_longest
  3. from parso.python import tree
  4. from jedi import debug
  5. from jedi.inference.utils import PushBackIterator
  6. from jedi.inference import analysis
  7. from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \
  8. LazyTreeValue, get_merged_lazy_value
  9. from jedi.inference.names import ParamName, TreeNameDefinition, AnonymousParamName
  10. from jedi.inference.base_value import NO_VALUES, ValueSet, ContextualizedNode
  11. from jedi.inference.value import iterable
  12. from jedi.inference.cache import inference_state_as_method_param_cache
  13. def try_iter_content(types, depth=0):
  14. """Helper method for static analysis."""
  15. if depth > 10:
  16. # It's possible that a loop has references on itself (especially with
  17. # CompiledValue). Therefore don't loop infinitely.
  18. return
  19. for typ in types:
  20. try:
  21. f = typ.py__iter__
  22. except AttributeError:
  23. pass
  24. else:
  25. for lazy_value in f():
  26. try_iter_content(lazy_value.infer(), depth + 1)
  27. class ParamIssue(Exception):
  28. pass
  29. def repack_with_argument_clinic(clinic_string):
  30. """
  31. Transforms a function or method with arguments to the signature that is
  32. given as an argument clinic notation.
  33. Argument clinic is part of CPython and used for all the functions that are
  34. implemented in C (Python 3.7):
  35. str.split.__text_signature__
  36. # Results in: '($self, /, sep=None, maxsplit=-1)'
  37. """
  38. def decorator(func):
  39. def wrapper(value, arguments):
  40. try:
  41. args = tuple(iterate_argument_clinic(
  42. value.inference_state,
  43. arguments,
  44. clinic_string,
  45. ))
  46. except ParamIssue:
  47. return NO_VALUES
  48. else:
  49. return func(value, *args)
  50. return wrapper
  51. return decorator
  52. def iterate_argument_clinic(inference_state, arguments, clinic_string):
  53. """Uses a list with argument clinic information (see PEP 436)."""
  54. clinic_args = list(_parse_argument_clinic(clinic_string))
  55. iterator = PushBackIterator(arguments.unpack())
  56. for i, (name, optional, allow_kwargs, stars) in enumerate(clinic_args):
  57. if stars == 1:
  58. lazy_values = []
  59. for key, argument in iterator:
  60. if key is not None:
  61. iterator.push_back((key, argument))
  62. break
  63. lazy_values.append(argument)
  64. yield ValueSet([iterable.FakeTuple(inference_state, lazy_values)])
  65. lazy_values
  66. continue
  67. elif stars == 2:
  68. raise NotImplementedError()
  69. key, argument = next(iterator, (None, None))
  70. if key is not None:
  71. debug.warning('Keyword arguments in argument clinic are currently not supported.')
  72. raise ParamIssue
  73. if argument is None and not optional:
  74. debug.warning('TypeError: %s expected at least %s arguments, got %s',
  75. name, len(clinic_args), i)
  76. raise ParamIssue
  77. value_set = NO_VALUES if argument is None else argument.infer()
  78. if not value_set and not optional:
  79. # For the stdlib we always want values. If we don't get them,
  80. # that's ok, maybe something is too hard to resolve, however,
  81. # we will not proceed with the type inference of that function.
  82. debug.warning('argument_clinic "%s" not resolvable.', name)
  83. raise ParamIssue
  84. yield value_set
  85. def _parse_argument_clinic(string):
  86. allow_kwargs = False
  87. optional = False
  88. while string:
  89. # Optional arguments have to begin with a bracket. And should always be
  90. # at the end of the arguments. This is therefore not a proper argument
  91. # clinic implementation. `range()` for exmple allows an optional start
  92. # value at the beginning.
  93. match = re.match(r'(?:(?:(\[),? ?|, ?|)(\**\w+)|, ?/)\]*', string)
  94. string = string[len(match.group(0)):]
  95. if not match.group(2): # A slash -> allow named arguments
  96. allow_kwargs = True
  97. continue
  98. optional = optional or bool(match.group(1))
  99. word = match.group(2)
  100. stars = word.count('*')
  101. word = word[stars:]
  102. yield (word, optional, allow_kwargs, stars)
  103. if stars:
  104. allow_kwargs = True
  105. class _AbstractArgumentsMixin:
  106. def unpack(self, funcdef=None):
  107. raise NotImplementedError
  108. def get_calling_nodes(self):
  109. return []
  110. class AbstractArguments(_AbstractArgumentsMixin):
  111. context = None
  112. argument_node = None
  113. trailer = None
  114. def unpack_arglist(arglist):
  115. if arglist is None:
  116. return
  117. if arglist.type != 'arglist' and not (
  118. arglist.type == 'argument' and arglist.children[0] in ('*', '**')):
  119. yield 0, arglist
  120. return
  121. iterator = iter(arglist.children)
  122. for child in iterator:
  123. if child == ',':
  124. continue
  125. elif child in ('*', '**'):
  126. c = next(iterator, None)
  127. assert c is not None
  128. yield len(child.value), c
  129. elif child.type == 'argument' and \
  130. child.children[0] in ('*', '**'):
  131. assert len(child.children) == 2
  132. yield len(child.children[0].value), child.children[1]
  133. else:
  134. yield 0, child
  135. class TreeArguments(AbstractArguments):
  136. def __init__(self, inference_state, context, argument_node, trailer=None):
  137. """
  138. :param argument_node: May be an argument_node or a list of nodes.
  139. """
  140. self.argument_node = argument_node
  141. self.context = context
  142. self._inference_state = inference_state
  143. self.trailer = trailer # Can be None, e.g. in a class definition.
  144. @classmethod
  145. @inference_state_as_method_param_cache()
  146. def create_cached(cls, *args, **kwargs):
  147. return cls(*args, **kwargs)
  148. def unpack(self, funcdef=None):
  149. named_args = []
  150. for star_count, el in unpack_arglist(self.argument_node):
  151. if star_count == 1:
  152. arrays = self.context.infer_node(el)
  153. iterators = [_iterate_star_args(self.context, a, el, funcdef)
  154. for a in arrays]
  155. for values in list(zip_longest(*iterators)):
  156. yield None, get_merged_lazy_value(
  157. [v for v in values if v is not None]
  158. )
  159. elif star_count == 2:
  160. arrays = self.context.infer_node(el)
  161. for dct in arrays:
  162. yield from _star_star_dict(self.context, dct, el, funcdef)
  163. else:
  164. if el.type == 'argument':
  165. c = el.children
  166. if len(c) == 3: # Keyword argument.
  167. named_args.append((c[0].value, LazyTreeValue(self.context, c[2]),))
  168. else: # Generator comprehension.
  169. # Include the brackets with the parent.
  170. sync_comp_for = el.children[1]
  171. if sync_comp_for.type == 'comp_for':
  172. sync_comp_for = sync_comp_for.children[1]
  173. comp = iterable.GeneratorComprehension(
  174. self._inference_state,
  175. defining_context=self.context,
  176. sync_comp_for_node=sync_comp_for,
  177. entry_node=el.children[0],
  178. )
  179. yield None, LazyKnownValue(comp)
  180. else:
  181. yield None, LazyTreeValue(self.context, el)
  182. # Reordering arguments is necessary, because star args sometimes appear
  183. # after named argument, but in the actual order it's prepended.
  184. yield from named_args
  185. def _as_tree_tuple_objects(self):
  186. for star_count, argument in unpack_arglist(self.argument_node):
  187. default = None
  188. if argument.type == 'argument':
  189. if len(argument.children) == 3: # Keyword argument.
  190. argument, default = argument.children[::2]
  191. yield argument, default, star_count
  192. def iter_calling_names_with_star(self):
  193. for name, default, star_count in self._as_tree_tuple_objects():
  194. # TODO this function is a bit strange. probably refactor?
  195. if not star_count or not isinstance(name, tree.Name):
  196. continue
  197. yield TreeNameDefinition(self.context, name)
  198. def __repr__(self):
  199. return '<%s: %s>' % (self.__class__.__name__, self.argument_node)
  200. def get_calling_nodes(self):
  201. old_arguments_list = []
  202. arguments = self
  203. while arguments not in old_arguments_list:
  204. if not isinstance(arguments, TreeArguments):
  205. break
  206. old_arguments_list.append(arguments)
  207. for calling_name in reversed(list(arguments.iter_calling_names_with_star())):
  208. names = calling_name.goto()
  209. if len(names) != 1:
  210. break
  211. if isinstance(names[0], AnonymousParamName):
  212. # Dynamic parameters should not have calling nodes, because
  213. # they are dynamic and extremely random.
  214. return []
  215. if not isinstance(names[0], ParamName):
  216. break
  217. executed_param_name = names[0].get_executed_param_name()
  218. arguments = executed_param_name.arguments
  219. break
  220. if arguments.argument_node is not None:
  221. return [ContextualizedNode(arguments.context, arguments.argument_node)]
  222. if arguments.trailer is not None:
  223. return [ContextualizedNode(arguments.context, arguments.trailer)]
  224. return []
  225. class ValuesArguments(AbstractArguments):
  226. def __init__(self, values_list):
  227. self._values_list = values_list
  228. def unpack(self, funcdef=None):
  229. for values in self._values_list:
  230. yield None, LazyKnownValues(values)
  231. def __repr__(self):
  232. return '<%s: %s>' % (self.__class__.__name__, self._values_list)
  233. class TreeArgumentsWrapper(_AbstractArgumentsMixin):
  234. def __init__(self, arguments):
  235. self._wrapped_arguments = arguments
  236. @property
  237. def context(self):
  238. return self._wrapped_arguments.context
  239. @property
  240. def argument_node(self):
  241. return self._wrapped_arguments.argument_node
  242. @property
  243. def trailer(self):
  244. return self._wrapped_arguments.trailer
  245. def unpack(self, func=None):
  246. raise NotImplementedError
  247. def get_calling_nodes(self):
  248. return self._wrapped_arguments.get_calling_nodes()
  249. def __repr__(self):
  250. return '<%s: %s>' % (self.__class__.__name__, self._wrapped_arguments)
  251. def _iterate_star_args(context, array, input_node, funcdef=None):
  252. if not array.py__getattribute__('__iter__'):
  253. if funcdef is not None:
  254. # TODO this funcdef should not be needed.
  255. m = "TypeError: %s() argument after * must be a sequence, not %s" \
  256. % (funcdef.name.value, array)
  257. analysis.add(context, 'type-error-star', input_node, message=m)
  258. try:
  259. iter_ = array.py__iter__
  260. except AttributeError:
  261. pass
  262. else:
  263. yield from iter_()
  264. def _star_star_dict(context, array, input_node, funcdef):
  265. from jedi.inference.value.instance import CompiledInstance
  266. if isinstance(array, CompiledInstance) and array.name.string_name == 'dict':
  267. # For now ignore this case. In the future add proper iterators and just
  268. # make one call without crazy isinstance checks.
  269. return {}
  270. elif isinstance(array, iterable.Sequence) and array.array_type == 'dict':
  271. return array.exact_key_items()
  272. else:
  273. if funcdef is not None:
  274. m = "TypeError: %s argument after ** must be a mapping, not %s" \
  275. % (funcdef.name.value, array)
  276. analysis.add(context, 'type-error-star-star', input_node, message=m)
  277. return {}