_base_nodes.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. """This module contains some base nodes that can be inherited for the different nodes.
  5. Previously these were called Mixin nodes.
  6. """
  7. from __future__ import annotations
  8. import itertools
  9. import sys
  10. from collections.abc import Iterator
  11. from typing import TYPE_CHECKING, ClassVar
  12. from astroid import decorators
  13. from astroid.exceptions import AttributeInferenceError
  14. from astroid.nodes.node_ng import NodeNG
  15. if TYPE_CHECKING:
  16. from astroid import nodes
  17. if sys.version_info >= (3, 8):
  18. from functools import cached_property
  19. else:
  20. from astroid.decorators import cachedproperty as cached_property
  21. class Statement(NodeNG):
  22. """Statement node adding a few attributes.
  23. NOTE: This class is part of the public API of 'astroid.nodes'.
  24. """
  25. is_statement = True
  26. """Whether this node indicates a statement."""
  27. def next_sibling(self):
  28. """The next sibling statement node.
  29. :returns: The next sibling statement node.
  30. :rtype: NodeNG or None
  31. """
  32. stmts = self.parent.child_sequence(self)
  33. index = stmts.index(self)
  34. try:
  35. return stmts[index + 1]
  36. except IndexError:
  37. return None
  38. def previous_sibling(self):
  39. """The previous sibling statement.
  40. :returns: The previous sibling statement node.
  41. :rtype: NodeNG or None
  42. """
  43. stmts = self.parent.child_sequence(self)
  44. index = stmts.index(self)
  45. if index >= 1:
  46. return stmts[index - 1]
  47. return None
  48. class NoChildrenNode(NodeNG):
  49. """Base nodes for nodes with no children, e.g. Pass."""
  50. def get_children(self) -> Iterator[NodeNG]:
  51. yield from ()
  52. class FilterStmtsBaseNode(NodeNG):
  53. """Base node for statement filtering and assignment type."""
  54. def _get_filtered_stmts(self, _, node, _stmts, mystmt: Statement | None):
  55. """Method used in _filter_stmts to get statements and trigger break."""
  56. if self.statement(future=True) is mystmt:
  57. # original node's statement is the assignment, only keep
  58. # current node (gen exp, list comp)
  59. return [node], True
  60. return _stmts, False
  61. def assign_type(self):
  62. return self
  63. class AssignTypeNode(NodeNG):
  64. """Base node for nodes that can 'assign' such as AnnAssign."""
  65. def assign_type(self):
  66. return self
  67. def _get_filtered_stmts(self, lookup_node, node, _stmts, mystmt: Statement | None):
  68. """Method used in filter_stmts."""
  69. if self is mystmt:
  70. return _stmts, True
  71. if self.statement(future=True) is mystmt:
  72. # original node's statement is the assignment, only keep
  73. # current node (gen exp, list comp)
  74. return [node], True
  75. return _stmts, False
  76. class ParentAssignNode(AssignTypeNode):
  77. """Base node for nodes whose assign_type is determined by the parent node."""
  78. def assign_type(self):
  79. return self.parent.assign_type()
  80. class ImportNode(FilterStmtsBaseNode, NoChildrenNode, Statement):
  81. """Base node for From and Import Nodes."""
  82. modname: str | None
  83. """The module that is being imported from.
  84. This is ``None`` for relative imports.
  85. """
  86. names: list[tuple[str, str | None]]
  87. """What is being imported from the module.
  88. Each entry is a :class:`tuple` of the name being imported,
  89. and the alias that the name is assigned to (if any).
  90. """
  91. def _infer_name(self, frame, name):
  92. return name
  93. def do_import_module(self, modname: str | None = None) -> nodes.Module:
  94. """Return the ast for a module whose name is <modname> imported by <self>."""
  95. mymodule = self.root()
  96. level: int | None = getattr(self, "level", None) # Import has no level
  97. if modname is None:
  98. modname = self.modname
  99. # If the module ImportNode is importing is a module with the same name
  100. # as the file that contains the ImportNode we don't want to use the cache
  101. # to make sure we use the import system to get the correct module.
  102. # pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
  103. if mymodule.relative_to_absolute_name(modname, level) == mymodule.name:
  104. use_cache = False
  105. else:
  106. use_cache = True
  107. # pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
  108. return mymodule.import_module(
  109. modname,
  110. level=level,
  111. relative_only=bool(level and level >= 1),
  112. use_cache=use_cache,
  113. )
  114. def real_name(self, asname: str) -> str:
  115. """Get name from 'as' name."""
  116. for name, _asname in self.names:
  117. if name == "*":
  118. return asname
  119. if not _asname:
  120. name = name.split(".", 1)[0]
  121. _asname = name
  122. if asname == _asname:
  123. return name
  124. raise AttributeInferenceError(
  125. "Could not find original name for {attribute} in {target!r}",
  126. target=self,
  127. attribute=asname,
  128. )
  129. class MultiLineBlockNode(NodeNG):
  130. """Base node for multi-line blocks, e.g. For and FunctionDef.
  131. Note that this does not apply to every node with a `body` field.
  132. For instance, an If node has a multi-line body, but the body of an
  133. IfExpr is not multi-line, and hence cannot contain Return nodes,
  134. Assign nodes, etc.
  135. """
  136. _multi_line_block_fields: ClassVar[tuple[str, ...]] = ()
  137. @cached_property
  138. def _multi_line_blocks(self):
  139. return tuple(getattr(self, field) for field in self._multi_line_block_fields)
  140. def _get_return_nodes_skip_functions(self):
  141. for block in self._multi_line_blocks:
  142. for child_node in block:
  143. if child_node.is_function:
  144. continue
  145. yield from child_node._get_return_nodes_skip_functions()
  146. def _get_yield_nodes_skip_lambdas(self):
  147. for block in self._multi_line_blocks:
  148. for child_node in block:
  149. if child_node.is_lambda:
  150. continue
  151. yield from child_node._get_yield_nodes_skip_lambdas()
  152. @decorators.cached
  153. def _get_assign_nodes(self):
  154. children_assign_nodes = (
  155. child_node._get_assign_nodes()
  156. for block in self._multi_line_blocks
  157. for child_node in block
  158. )
  159. return list(itertools.chain.from_iterable(children_assign_nodes))
  160. class MultiLineWithElseBlockNode(MultiLineBlockNode):
  161. """Base node for multi-line blocks that can have else statements."""
  162. @cached_property
  163. def blockstart_tolineno(self):
  164. return self.lineno
  165. def _elsed_block_range(self, lineno, orelse, last=None):
  166. """Handle block line numbers range for try/finally, for, if and while
  167. statements.
  168. """
  169. if lineno == self.fromlineno:
  170. return lineno, lineno
  171. if orelse:
  172. if lineno >= orelse[0].fromlineno:
  173. return lineno, orelse[-1].tolineno
  174. return lineno, orelse[0].fromlineno - 1
  175. return lineno, last or self.tolineno