mixin.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. """This module contains mixin classes for scoped nodes."""
  5. from __future__ import annotations
  6. import sys
  7. from typing import TYPE_CHECKING, overload
  8. from astroid.exceptions import ParentMissingError
  9. from astroid.filter_statements import _filter_stmts
  10. from astroid.nodes import _base_nodes, scoped_nodes
  11. from astroid.nodes.scoped_nodes.utils import builtin_lookup
  12. from astroid.typing import InferenceResult, SuccessfulInferenceResult
  13. if sys.version_info >= (3, 11):
  14. from typing import Self
  15. else:
  16. from typing_extensions import Self
  17. if TYPE_CHECKING:
  18. from astroid import nodes
  19. class LocalsDictNodeNG(_base_nodes.LookupMixIn):
  20. """this class provides locals handling common to Module, FunctionDef
  21. and ClassDef nodes, including a dict like interface for direct access
  22. to locals information
  23. """
  24. # attributes below are set by the builder module or by raw factories
  25. locals: dict[str, list[InferenceResult]]
  26. """A map of the name of a local variable to the node defining the local."""
  27. def qname(self) -> str:
  28. """Get the 'qualified' name of the node.
  29. For example: module.name, module.class.name ...
  30. :returns: The qualified name.
  31. :rtype: str
  32. """
  33. # pylint: disable=no-member; github.com/pylint-dev/astroid/issues/278
  34. if self.parent is None:
  35. return self.name
  36. try:
  37. return f"{self.parent.frame().qname()}.{self.name}"
  38. except ParentMissingError:
  39. return self.name
  40. def scope(self) -> Self:
  41. """The first parent node defining a new scope.
  42. :returns: The first parent scope node.
  43. :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr
  44. """
  45. return self
  46. def scope_lookup(
  47. self, node: _base_nodes.LookupMixIn, name: str, offset: int = 0
  48. ) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
  49. """Lookup where the given variable is assigned.
  50. :param node: The node to look for assignments up to.
  51. Any assignments after the given node are ignored.
  52. :param name: The name of the variable to find assignments for.
  53. :param offset: The line offset to filter statements up to.
  54. :returns: This scope node and the list of assignments associated to the
  55. given name according to the scope where it has been found (locals,
  56. globals or builtin).
  57. """
  58. raise NotImplementedError
  59. def _scope_lookup(
  60. self, node: _base_nodes.LookupMixIn, name: str, offset: int = 0
  61. ) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
  62. """XXX method for interfacing the scope lookup"""
  63. try:
  64. stmts = _filter_stmts(node, self.locals[name], self, offset)
  65. except KeyError:
  66. stmts = ()
  67. if stmts:
  68. return self, stmts
  69. # Handle nested scopes: since class names do not extend to nested
  70. # scopes (e.g., methods), we find the next enclosing non-class scope
  71. pscope = self.parent and self.parent.scope()
  72. while pscope is not None:
  73. if not isinstance(pscope, scoped_nodes.ClassDef):
  74. return pscope.scope_lookup(node, name)
  75. pscope = pscope.parent and pscope.parent.scope()
  76. # self is at the top level of a module, or is enclosed only by ClassDefs
  77. return builtin_lookup(name)
  78. def set_local(self, name: str, stmt: nodes.NodeNG) -> None:
  79. """Define that the given name is declared in the given statement node.
  80. .. seealso:: :meth:`scope`
  81. :param name: The name that is being defined.
  82. :param stmt: The statement that defines the given name.
  83. """
  84. # assert not stmt in self.locals.get(name, ()), (self, stmt)
  85. self.locals.setdefault(name, []).append(stmt)
  86. __setitem__ = set_local
  87. def _append_node(self, child: nodes.NodeNG) -> None:
  88. """append a child, linking it in the tree"""
  89. # pylint: disable=no-member; depending by the class
  90. # which uses the current class as a mixin or base class.
  91. # It's rewritten in 2.0, so it makes no sense for now
  92. # to spend development time on it.
  93. self.body.append(child) # type: ignore[attr-defined]
  94. child.parent = self
  95. @overload
  96. def add_local_node(
  97. self, child_node: nodes.ClassDef, name: str | None = ...
  98. ) -> None: ...
  99. @overload
  100. def add_local_node(self, child_node: nodes.NodeNG, name: str) -> None: ...
  101. def add_local_node(self, child_node: nodes.NodeNG, name: str | None = None) -> None:
  102. """Append a child that should alter the locals of this scope node.
  103. :param child_node: The child node that will alter locals.
  104. :param name: The name of the local that will be altered by
  105. the given child node.
  106. """
  107. if name != "__class__":
  108. # add __class__ node as a child will cause infinite recursion later!
  109. self._append_node(child_node)
  110. self.set_local(name or child_node.name, child_node) # type: ignore[attr-defined]
  111. def __getitem__(self, item: str) -> SuccessfulInferenceResult:
  112. """The first node the defines the given local.
  113. :param item: The name of the locally defined object.
  114. :raises KeyError: If the name is not defined.
  115. """
  116. return self.locals[item][0]
  117. def __iter__(self):
  118. """Iterate over the names of locals defined in this scoped node.
  119. :returns: The names of the defined locals.
  120. :rtype: iterable(str)
  121. """
  122. return iter(self.keys())
  123. def keys(self):
  124. """The names of locals defined in this scoped node.
  125. :returns: The names of the defined locals.
  126. :rtype: list(str)
  127. """
  128. return list(self.locals.keys())
  129. def values(self):
  130. """The nodes that define the locals in this scoped node.
  131. :returns: The nodes that define locals.
  132. :rtype: list(NodeNG)
  133. """
  134. # pylint: disable=consider-using-dict-items
  135. # It look like this class override items/keys/values,
  136. # probably not worth the headache
  137. return [self[key] for key in self.keys()]
  138. def items(self):
  139. """Get the names of the locals and the node that defines the local.
  140. :returns: The names of locals and their associated node.
  141. :rtype: list(tuple(str, NodeNG))
  142. """
  143. return list(zip(self.keys(), self.values()))
  144. def __contains__(self, name) -> bool:
  145. """Check if a local is defined in this scope.
  146. :param name: The name of the local to check for.
  147. :type name: str
  148. :returns: Whether this node has a local of the given name,
  149. """
  150. return name in self.locals
  151. class ComprehensionScope(LocalsDictNodeNG):
  152. """Scoping for different types of comprehensions."""
  153. scope_lookup = LocalsDictNodeNG._scope_lookup
  154. generators: list[nodes.Comprehension]
  155. """The generators that are looped through."""