context.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
  4. """Various context related utilities, including inference and call contexts."""
  5. from __future__ import annotations
  6. import contextlib
  7. import pprint
  8. from collections.abc import Iterator, Sequence
  9. from typing import TYPE_CHECKING
  10. from astroid.typing import InferenceResult, SuccessfulInferenceResult
  11. if TYPE_CHECKING:
  12. from astroid import constraint, nodes
  13. _InferenceCache = dict[
  14. tuple["nodes.NodeNG", str | None, str | None, str | None], Sequence["nodes.NodeNG"]
  15. ]
  16. _INFERENCE_CACHE: _InferenceCache = {}
  17. def _invalidate_cache() -> None:
  18. _INFERENCE_CACHE.clear()
  19. class InferenceContext:
  20. """Provide context for inference.
  21. Store already inferred nodes to save time
  22. Account for already visited nodes to stop infinite recursion
  23. """
  24. __slots__ = (
  25. "_nodes_inferred",
  26. "boundnode",
  27. "callcontext",
  28. "constraints",
  29. "extra_context",
  30. "lookupname",
  31. "path",
  32. )
  33. max_inferred = 100
  34. def __init__(
  35. self,
  36. path: set[tuple[nodes.NodeNG, str | None]] | None = None,
  37. nodes_inferred: list[int] | None = None,
  38. ) -> None:
  39. if nodes_inferred is None:
  40. self._nodes_inferred = [0]
  41. else:
  42. self._nodes_inferred = nodes_inferred
  43. self.path = path or set()
  44. """Path of visited nodes and their lookupname.
  45. Currently this key is ``(node, context.lookupname)``
  46. """
  47. self.lookupname: str | None = None
  48. """The original name of the node.
  49. e.g.
  50. foo = 1
  51. The inference of 'foo' is nodes.Const(1) but the lookup name is 'foo'
  52. """
  53. self.callcontext: CallContext | None = None
  54. """The call arguments and keywords for the given context."""
  55. self.boundnode: SuccessfulInferenceResult | None = None
  56. """The bound node of the given context.
  57. e.g. the bound node of object.__new__(cls) is the object node
  58. """
  59. self.extra_context: dict[SuccessfulInferenceResult, InferenceContext] = {}
  60. """Context that needs to be passed down through call stacks for call arguments."""
  61. self.constraints: dict[
  62. str, dict[nodes.If | nodes.IfExp, set[constraint.Constraint]]
  63. ] = {}
  64. """The constraints on nodes."""
  65. @property
  66. def nodes_inferred(self) -> int:
  67. """
  68. Number of nodes inferred in this context and all its clones/descendents.
  69. Wrap inner value in a mutable cell to allow for mutating a class
  70. variable in the presence of __slots__
  71. """
  72. return self._nodes_inferred[0]
  73. @nodes_inferred.setter
  74. def nodes_inferred(self, value: int) -> None:
  75. self._nodes_inferred[0] = value
  76. @property
  77. def inferred(self) -> _InferenceCache:
  78. """
  79. Inferred node contexts to their mapped results.
  80. Currently the key is ``(node, lookupname, callcontext, boundnode)``
  81. and the value is tuple of the inferred results
  82. """
  83. return _INFERENCE_CACHE
  84. def push(self, node: nodes.NodeNG) -> bool:
  85. """Push node into inference path.
  86. Allows one to see if the given node has already
  87. been looked at for this inference context
  88. """
  89. name = self.lookupname
  90. if (node, name) in self.path:
  91. return True
  92. self.path.add((node, name))
  93. return False
  94. def clone(self) -> InferenceContext:
  95. """Clone inference path.
  96. For example, each side of a binary operation (BinOp)
  97. starts with the same context but diverge as each side is inferred
  98. so the InferenceContext will need be cloned
  99. """
  100. # XXX copy lookupname/callcontext ?
  101. clone = InferenceContext(self.path.copy(), nodes_inferred=self._nodes_inferred)
  102. clone.callcontext = self.callcontext
  103. clone.boundnode = self.boundnode
  104. clone.extra_context = self.extra_context
  105. clone.constraints = self.constraints.copy()
  106. return clone
  107. @contextlib.contextmanager
  108. def restore_path(self) -> Iterator[None]:
  109. path = set(self.path)
  110. yield
  111. self.path = path
  112. def is_empty(self) -> bool:
  113. return (
  114. not self.path
  115. and not self.nodes_inferred
  116. and not self.callcontext
  117. and not self.boundnode
  118. and not self.lookupname
  119. and not self.callcontext
  120. and not self.extra_context
  121. and not self.constraints
  122. )
  123. def __str__(self) -> str:
  124. state = (
  125. f"{field}={pprint.pformat(getattr(self, field), width=80 - len(field))}"
  126. for field in self.__slots__
  127. )
  128. return "{}({})".format(type(self).__name__, ",\n ".join(state))
  129. class CallContext:
  130. """Holds information for a call site."""
  131. __slots__ = ("args", "callee", "keywords")
  132. def __init__(
  133. self,
  134. args: list[nodes.NodeNG],
  135. keywords: list[nodes.Keyword] | None = None,
  136. callee: InferenceResult | None = None,
  137. ):
  138. self.args = args # Call positional arguments
  139. if keywords:
  140. arg_value_pairs = [(arg.arg, arg.value) for arg in keywords]
  141. else:
  142. arg_value_pairs = []
  143. self.keywords = arg_value_pairs # Call keyword arguments
  144. self.callee = callee # Function being called
  145. def copy_context(context: InferenceContext | None) -> InferenceContext:
  146. """Clone a context if given, or return a fresh context."""
  147. if context is not None:
  148. return context.clone()
  149. return InferenceContext()
  150. def bind_context_to_node(
  151. context: InferenceContext | None, node: SuccessfulInferenceResult
  152. ) -> InferenceContext:
  153. """Give a context a boundnode
  154. to retrieve the correct function name or attribute value
  155. with from further inference.
  156. Do not use an existing context since the boundnode could then
  157. be incorrectly propagated higher up in the call stack.
  158. """
  159. context = copy_context(context)
  160. context.boundnode = node
  161. return context