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