helpers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. """Various helper utilities."""
  5. from __future__ import annotations
  6. from collections.abc import Generator
  7. from astroid import bases, manager, nodes, objects, raw_building, util
  8. from astroid.context import CallContext, InferenceContext
  9. from astroid.exceptions import (
  10. AstroidTypeError,
  11. AttributeInferenceError,
  12. InferenceError,
  13. MroError,
  14. _NonDeducibleTypeHierarchy,
  15. )
  16. from astroid.nodes import scoped_nodes
  17. from astroid.typing import InferenceResult, SuccessfulInferenceResult
  18. def _build_proxy_class(cls_name: str, builtins: nodes.Module) -> nodes.ClassDef:
  19. proxy = raw_building.build_class(cls_name)
  20. proxy.parent = builtins
  21. return proxy
  22. def _function_type(
  23. function: nodes.Lambda | bases.UnboundMethod, builtins: nodes.Module
  24. ) -> nodes.ClassDef:
  25. if isinstance(function, scoped_nodes.Lambda):
  26. if function.root().name == "builtins":
  27. cls_name = "builtin_function_or_method"
  28. else:
  29. cls_name = "function"
  30. elif isinstance(function, bases.BoundMethod):
  31. cls_name = "method"
  32. else:
  33. cls_name = "function"
  34. return _build_proxy_class(cls_name, builtins)
  35. def _object_type(
  36. node: SuccessfulInferenceResult, context: InferenceContext | None = None
  37. ) -> Generator[InferenceResult | None, None, None]:
  38. astroid_manager = manager.AstroidManager()
  39. builtins = astroid_manager.builtins_module
  40. context = context or InferenceContext()
  41. for inferred in node.infer(context=context):
  42. if isinstance(inferred, scoped_nodes.ClassDef):
  43. if inferred.newstyle:
  44. metaclass = inferred.metaclass(context=context)
  45. if metaclass:
  46. yield metaclass
  47. continue
  48. yield builtins.getattr("type")[0]
  49. elif isinstance(inferred, (scoped_nodes.Lambda, bases.UnboundMethod)):
  50. yield _function_type(inferred, builtins)
  51. elif isinstance(inferred, scoped_nodes.Module):
  52. yield _build_proxy_class("module", builtins)
  53. elif isinstance(inferred, nodes.Unknown):
  54. raise InferenceError
  55. elif isinstance(inferred, util.UninferableBase):
  56. yield inferred
  57. elif isinstance(inferred, (bases.Proxy, nodes.Slice, objects.Super)):
  58. yield inferred._proxied
  59. else: # pragma: no cover
  60. raise AssertionError(f"We don't handle {type(inferred)} currently")
  61. def object_type(
  62. node: SuccessfulInferenceResult, context: InferenceContext | None = None
  63. ) -> InferenceResult | None:
  64. """Obtain the type of the given node.
  65. This is used to implement the ``type`` builtin, which means that it's
  66. used for inferring type calls, as well as used in a couple of other places
  67. in the inference.
  68. The node will be inferred first, so this function can support all
  69. sorts of objects, as long as they support inference.
  70. """
  71. try:
  72. types = set(_object_type(node, context))
  73. except InferenceError:
  74. return util.Uninferable
  75. if len(types) > 1 or not types:
  76. return util.Uninferable
  77. return list(types)[0]
  78. def _object_type_is_subclass(
  79. obj_type, class_or_seq, context: InferenceContext | None = None
  80. ):
  81. if not isinstance(class_or_seq, (tuple, list)):
  82. class_seq = (class_or_seq,)
  83. else:
  84. class_seq = class_or_seq
  85. if isinstance(obj_type, util.UninferableBase):
  86. return util.Uninferable
  87. # Instances are not types
  88. class_seq = [
  89. item if not isinstance(item, bases.Instance) else util.Uninferable
  90. for item in class_seq
  91. ]
  92. # strict compatibility with issubclass
  93. # issubclass(type, (object, 1)) evaluates to true
  94. # issubclass(object, (1, type)) raises TypeError
  95. for klass in class_seq:
  96. if isinstance(klass, util.UninferableBase):
  97. raise AstroidTypeError("arg 2 must be a type or tuple of types")
  98. for obj_subclass in obj_type.mro():
  99. if obj_subclass == klass:
  100. return True
  101. return False
  102. def object_isinstance(node, class_or_seq, context: InferenceContext | None = None):
  103. """Check if a node 'isinstance' any node in class_or_seq.
  104. :param node: A given node
  105. :param class_or_seq: Union[nodes.NodeNG, Sequence[nodes.NodeNG]]
  106. :rtype: bool
  107. :raises AstroidTypeError: if the given ``classes_or_seq`` are not types
  108. """
  109. obj_type = object_type(node, context)
  110. if isinstance(obj_type, util.UninferableBase):
  111. return util.Uninferable
  112. return _object_type_is_subclass(obj_type, class_or_seq, context=context)
  113. def object_issubclass(node, class_or_seq, context: InferenceContext | None = None):
  114. """Check if a type is a subclass of any node in class_or_seq.
  115. :param node: A given node
  116. :param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]]
  117. :rtype: bool
  118. :raises AstroidTypeError: if the given ``classes_or_seq`` are not types
  119. :raises AstroidError: if the type of the given node cannot be inferred
  120. or its type's mro doesn't work
  121. """
  122. if not isinstance(node, nodes.ClassDef):
  123. raise TypeError(f"{node} needs to be a ClassDef node")
  124. return _object_type_is_subclass(node, class_or_seq, context=context)
  125. def safe_infer(
  126. node: nodes.NodeNG | bases.Proxy, context: InferenceContext | None = None
  127. ) -> InferenceResult | None:
  128. """Return the inferred value for the given node.
  129. Return None if inference failed or if there is some ambiguity (more than
  130. one node has been inferred).
  131. """
  132. try:
  133. inferit = node.infer(context=context)
  134. value = next(inferit)
  135. except (InferenceError, StopIteration):
  136. return None
  137. try:
  138. next(inferit)
  139. return None # None if there is ambiguity on the inferred node
  140. except InferenceError:
  141. return None # there is some kind of ambiguity
  142. except StopIteration:
  143. return value
  144. def has_known_bases(klass, context: InferenceContext | None = None) -> bool:
  145. """Return whether all base classes of a class could be inferred."""
  146. try:
  147. return klass._all_bases_known
  148. except AttributeError:
  149. pass
  150. for base in klass.bases:
  151. result = safe_infer(base, context=context)
  152. # TODO: check for A->B->A->B pattern in class structure too?
  153. if (
  154. not isinstance(result, scoped_nodes.ClassDef)
  155. or result is klass
  156. or not has_known_bases(result, context=context)
  157. ):
  158. klass._all_bases_known = False
  159. return False
  160. klass._all_bases_known = True
  161. return True
  162. def _type_check(type1, type2) -> bool:
  163. if not all(map(has_known_bases, (type1, type2))):
  164. raise _NonDeducibleTypeHierarchy
  165. if not all([type1.newstyle, type2.newstyle]):
  166. return False
  167. try:
  168. return type1 in type2.mro()[:-1]
  169. except MroError as e:
  170. # The MRO is invalid.
  171. raise _NonDeducibleTypeHierarchy from e
  172. def is_subtype(type1, type2) -> bool:
  173. """Check if *type1* is a subtype of *type2*."""
  174. return _type_check(type1=type2, type2=type1)
  175. def is_supertype(type1, type2) -> bool:
  176. """Check if *type2* is a supertype of *type1*."""
  177. return _type_check(type1, type2)
  178. def class_instance_as_index(node: SuccessfulInferenceResult) -> nodes.Const | None:
  179. """Get the value as an index for the given instance.
  180. If an instance provides an __index__ method, then it can
  181. be used in some scenarios where an integer is expected,
  182. for instance when multiplying or subscripting a list.
  183. """
  184. context = InferenceContext()
  185. try:
  186. for inferred in node.igetattr("__index__", context=context):
  187. if not isinstance(inferred, bases.BoundMethod):
  188. continue
  189. context.boundnode = node
  190. context.callcontext = CallContext(args=[], callee=inferred)
  191. for result in inferred.infer_call_result(node, context=context):
  192. if isinstance(result, nodes.Const) and isinstance(result.value, int):
  193. return result
  194. except InferenceError:
  195. pass
  196. return None
  197. def object_len(node, context: InferenceContext | None = None):
  198. """Infer length of given node object.
  199. :param Union[nodes.ClassDef, nodes.Instance] node:
  200. :param node: Node to infer length of
  201. :raises AstroidTypeError: If an invalid node is returned
  202. from __len__ method or no __len__ method exists
  203. :raises InferenceError: If the given node cannot be inferred
  204. or if multiple nodes are inferred or if the code executed in python
  205. would result in a infinite recursive check for length
  206. :rtype int: Integer length of node
  207. """
  208. # pylint: disable=import-outside-toplevel; circular import
  209. from astroid.objects import FrozenSet
  210. inferred_node = safe_infer(node, context=context)
  211. # prevent self referential length calls from causing a recursion error
  212. # see https://github.com/PyCQA/astroid/issues/777
  213. node_frame = node.frame(future=True)
  214. if (
  215. isinstance(node_frame, scoped_nodes.FunctionDef)
  216. and node_frame.name == "__len__"
  217. and hasattr(inferred_node, "_proxied")
  218. and inferred_node._proxied == node_frame.parent
  219. ):
  220. message = (
  221. "Self referential __len__ function will "
  222. "cause a RecursionError on line {} of {}".format(
  223. node.lineno, node.root().file
  224. )
  225. )
  226. raise InferenceError(message)
  227. if inferred_node is None or isinstance(inferred_node, util.UninferableBase):
  228. raise InferenceError(node=node)
  229. if isinstance(inferred_node, nodes.Const) and isinstance(
  230. inferred_node.value, (bytes, str)
  231. ):
  232. return len(inferred_node.value)
  233. if isinstance(inferred_node, (nodes.List, nodes.Set, nodes.Tuple, FrozenSet)):
  234. return len(inferred_node.elts)
  235. if isinstance(inferred_node, nodes.Dict):
  236. return len(inferred_node.items)
  237. node_type = object_type(inferred_node, context=context)
  238. if not node_type:
  239. raise InferenceError(node=node)
  240. try:
  241. len_call = next(node_type.igetattr("__len__", context=context))
  242. except StopIteration as e:
  243. raise AstroidTypeError(str(e)) from e
  244. except AttributeInferenceError as e:
  245. raise AstroidTypeError(
  246. f"object of type '{node_type.pytype()}' has no len()"
  247. ) from e
  248. inferred = len_call.infer_call_result(node, context)
  249. if isinstance(inferred, util.UninferableBase):
  250. raise InferenceError(node=node, context=context)
  251. result_of_len = next(inferred, None)
  252. if (
  253. isinstance(result_of_len, nodes.Const)
  254. and result_of_len.pytype() == "builtins.int"
  255. ):
  256. return result_of_len.value
  257. if (
  258. result_of_len is None
  259. or isinstance(result_of_len, bases.Instance)
  260. and result_of_len.is_subtype_of("builtins.int")
  261. ):
  262. # Fake a result as we don't know the arguments of the instance call.
  263. return 0
  264. raise AstroidTypeError(
  265. f"'{result_of_len}' object cannot be interpreted as an integer"
  266. )