Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

arguments.py 11KB

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