arguments.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. from astroid import nodes
  6. from astroid.bases import Instance
  7. from astroid.context import CallContext, InferenceContext
  8. from astroid.exceptions import InferenceError, NoDefault
  9. from astroid.util import Uninferable, UninferableBase
  10. class CallSite:
  11. """Class for understanding arguments passed into a call site.
  12. It needs a call context, which contains the arguments and the
  13. keyword arguments that were passed into a given call site.
  14. In order to infer what an argument represents, call :meth:`infer_argument`
  15. with the corresponding function node and the argument name.
  16. :param callcontext:
  17. An instance of :class:`astroid.context.CallContext`, that holds
  18. the arguments for the call site.
  19. :param argument_context_map:
  20. Additional contexts per node, passed in from :attr:`astroid.context.Context.extra_context`
  21. :param context:
  22. An instance of :class:`astroid.context.Context`.
  23. """
  24. def __init__(
  25. self,
  26. callcontext: CallContext,
  27. argument_context_map=None,
  28. context: InferenceContext | None = None,
  29. ):
  30. if argument_context_map is None:
  31. argument_context_map = {}
  32. self.argument_context_map = argument_context_map
  33. args = callcontext.args
  34. keywords = callcontext.keywords
  35. self.duplicated_keywords: set[str] = set()
  36. self._unpacked_args = self._unpack_args(args, context=context)
  37. self._unpacked_kwargs = self._unpack_keywords(keywords, context=context)
  38. self.positional_arguments = [
  39. arg for arg in self._unpacked_args if not isinstance(arg, UninferableBase)
  40. ]
  41. self.keyword_arguments = {
  42. key: value
  43. for key, value in self._unpacked_kwargs.items()
  44. if not isinstance(value, UninferableBase)
  45. }
  46. @classmethod
  47. def from_call(cls, call_node, context: InferenceContext | None = None):
  48. """Get a CallSite object from the given Call node.
  49. context will be used to force a single inference path.
  50. """
  51. # Determine the callcontext from the given `context` object if any.
  52. context = context or InferenceContext()
  53. callcontext = CallContext(call_node.args, call_node.keywords)
  54. return cls(callcontext, context=context)
  55. def has_invalid_arguments(self):
  56. """Check if in the current CallSite were passed *invalid* arguments.
  57. This can mean multiple things. For instance, if an unpacking
  58. of an invalid object was passed, then this method will return True.
  59. Other cases can be when the arguments can't be inferred by astroid,
  60. for example, by passing objects which aren't known statically.
  61. """
  62. return len(self.positional_arguments) != len(self._unpacked_args)
  63. def has_invalid_keywords(self) -> bool:
  64. """Check if in the current CallSite were passed *invalid* keyword arguments.
  65. For instance, unpacking a dictionary with integer keys is invalid
  66. (**{1:2}), because the keys must be strings, which will make this
  67. method to return True. Other cases where this might return True if
  68. objects which can't be inferred were passed.
  69. """
  70. return len(self.keyword_arguments) != len(self._unpacked_kwargs)
  71. def _unpack_keywords(self, keywords, context: InferenceContext | None = None):
  72. values = {}
  73. context = context or InferenceContext()
  74. context.extra_context = self.argument_context_map
  75. for name, value in keywords:
  76. if name is None:
  77. # Then it's an unpacking operation (**)
  78. try:
  79. inferred = next(value.infer(context=context))
  80. except InferenceError:
  81. values[name] = Uninferable
  82. continue
  83. except StopIteration:
  84. continue
  85. if not isinstance(inferred, nodes.Dict):
  86. # Not something we can work with.
  87. values[name] = Uninferable
  88. continue
  89. for dict_key, dict_value in inferred.items:
  90. try:
  91. dict_key = next(dict_key.infer(context=context))
  92. except InferenceError:
  93. values[name] = Uninferable
  94. continue
  95. except StopIteration:
  96. continue
  97. if not isinstance(dict_key, nodes.Const):
  98. values[name] = Uninferable
  99. continue
  100. if not isinstance(dict_key.value, str):
  101. values[name] = Uninferable
  102. continue
  103. if dict_key.value in values:
  104. # The name is already in the dictionary
  105. values[dict_key.value] = Uninferable
  106. self.duplicated_keywords.add(dict_key.value)
  107. continue
  108. values[dict_key.value] = dict_value
  109. else:
  110. values[name] = value
  111. return values
  112. def _unpack_args(self, args, context: InferenceContext | None = None):
  113. values = []
  114. context = context or InferenceContext()
  115. context.extra_context = self.argument_context_map
  116. for arg in args:
  117. if isinstance(arg, nodes.Starred):
  118. try:
  119. inferred = next(arg.value.infer(context=context))
  120. except InferenceError:
  121. values.append(Uninferable)
  122. continue
  123. except StopIteration:
  124. continue
  125. if isinstance(inferred, UninferableBase):
  126. values.append(Uninferable)
  127. continue
  128. if not hasattr(inferred, "elts"):
  129. values.append(Uninferable)
  130. continue
  131. values.extend(inferred.elts)
  132. else:
  133. values.append(arg)
  134. return values
  135. def infer_argument(self, funcnode, name, context): # noqa: C901
  136. """Infer a function argument value according to the call context.
  137. Arguments:
  138. funcnode: The function being called.
  139. name: The name of the argument whose value is being inferred.
  140. context: Inference context object
  141. """
  142. if name in self.duplicated_keywords:
  143. raise InferenceError(
  144. "The arguments passed to {func!r} have duplicate keywords.",
  145. call_site=self,
  146. func=funcnode,
  147. arg=name,
  148. context=context,
  149. )
  150. # Look into the keywords first, maybe it's already there.
  151. try:
  152. return self.keyword_arguments[name].infer(context)
  153. except KeyError:
  154. pass
  155. # Too many arguments given and no variable arguments.
  156. if len(self.positional_arguments) > len(funcnode.args.args):
  157. if not funcnode.args.vararg and not funcnode.args.posonlyargs:
  158. raise InferenceError(
  159. "Too many positional arguments "
  160. "passed to {func!r} that does "
  161. "not have *args.",
  162. call_site=self,
  163. func=funcnode,
  164. arg=name,
  165. context=context,
  166. )
  167. positional = self.positional_arguments[: len(funcnode.args.args)]
  168. vararg = self.positional_arguments[len(funcnode.args.args) :]
  169. argindex = funcnode.args.find_argname(name)[0]
  170. kwonlyargs = {arg.name for arg in funcnode.args.kwonlyargs}
  171. kwargs = {
  172. key: value
  173. for key, value in self.keyword_arguments.items()
  174. if key not in kwonlyargs
  175. }
  176. # If there are too few positionals compared to
  177. # what the function expects to receive, check to see
  178. # if the missing positional arguments were passed
  179. # as keyword arguments and if so, place them into the
  180. # positional args list.
  181. if len(positional) < len(funcnode.args.args):
  182. for func_arg in funcnode.args.args:
  183. if func_arg.name in kwargs:
  184. arg = kwargs.pop(func_arg.name)
  185. positional.append(arg)
  186. if argindex is not None:
  187. boundnode = getattr(context, "boundnode", None)
  188. # 2. first argument of instance/class method
  189. if argindex == 0 and funcnode.type in {"method", "classmethod"}:
  190. # context.boundnode is None when an instance method is called with
  191. # the class, e.g. MyClass.method(obj, ...). In this case, self
  192. # is the first argument.
  193. if boundnode is None and funcnode.type == "method" and positional:
  194. return positional[0].infer(context=context)
  195. if boundnode is None:
  196. # XXX can do better ?
  197. boundnode = funcnode.parent.frame(future=True)
  198. if isinstance(boundnode, nodes.ClassDef):
  199. # Verify that we're accessing a method
  200. # of the metaclass through a class, as in
  201. # `cls.metaclass_method`. In this case, the
  202. # first argument is always the class.
  203. method_scope = funcnode.parent.scope()
  204. if method_scope is boundnode.metaclass():
  205. return iter((boundnode,))
  206. if funcnode.type == "method":
  207. if not isinstance(boundnode, Instance):
  208. boundnode = boundnode.instantiate_class()
  209. return iter((boundnode,))
  210. if funcnode.type == "classmethod":
  211. return iter((boundnode,))
  212. # if we have a method, extract one position
  213. # from the index, so we'll take in account
  214. # the extra parameter represented by `self` or `cls`
  215. if funcnode.type in {"method", "classmethod"} and boundnode:
  216. argindex -= 1
  217. # 2. search arg index
  218. try:
  219. return self.positional_arguments[argindex].infer(context)
  220. except IndexError:
  221. pass
  222. if funcnode.args.kwarg == name:
  223. # It wants all the keywords that were passed into
  224. # the call site.
  225. if self.has_invalid_keywords():
  226. raise InferenceError(
  227. "Inference failed to find values for all keyword arguments "
  228. "to {func!r}: {unpacked_kwargs!r} doesn't correspond to "
  229. "{keyword_arguments!r}.",
  230. keyword_arguments=self.keyword_arguments,
  231. unpacked_kwargs=self._unpacked_kwargs,
  232. call_site=self,
  233. func=funcnode,
  234. arg=name,
  235. context=context,
  236. )
  237. kwarg = nodes.Dict(
  238. lineno=funcnode.args.lineno,
  239. col_offset=funcnode.args.col_offset,
  240. parent=funcnode.args,
  241. )
  242. kwarg.postinit(
  243. [(nodes.const_factory(key), value) for key, value in kwargs.items()]
  244. )
  245. return iter((kwarg,))
  246. if funcnode.args.vararg == name:
  247. # It wants all the args that were passed into
  248. # the call site.
  249. if self.has_invalid_arguments():
  250. raise InferenceError(
  251. "Inference failed to find values for all positional "
  252. "arguments to {func!r}: {unpacked_args!r} doesn't "
  253. "correspond to {positional_arguments!r}.",
  254. positional_arguments=self.positional_arguments,
  255. unpacked_args=self._unpacked_args,
  256. call_site=self,
  257. func=funcnode,
  258. arg=name,
  259. context=context,
  260. )
  261. args = nodes.Tuple(
  262. lineno=funcnode.args.lineno,
  263. col_offset=funcnode.args.col_offset,
  264. parent=funcnode.args,
  265. )
  266. args.postinit(vararg)
  267. return iter((args,))
  268. # Check if it's a default parameter.
  269. try:
  270. return funcnode.args.default_value(name).infer(context)
  271. except NoDefault:
  272. pass
  273. raise InferenceError(
  274. "No value found for argument {arg} to {func!r}",
  275. call_site=self,
  276. func=funcnode,
  277. arg=name,
  278. context=context,
  279. )