Debian Codegraph @

mypyc/irbuild/prebuildvisitor.py

raw
1 from __future__ import annotations
2
3 from mypy.nodes import (
4 AssignmentStmt,
5 Block,
6 Decorator,
7 DictionaryComprehension,
8 Expression,
9 FuncDef,
10 FuncItem,
11 GeneratorExpr,
12 Import,
13 LambdaExpr,
14 MemberExpr,
15 MypyFile,
16 NameExpr,
17 Node,
18 SymbolNode,
19 Var,
20 )
21 from mypy.traverser import ExtendedTraverserVisitor, TraverserVisitor
22 from mypy.types import Type
23 from mypyc.errors import Errors
24 from mypyc.irbuild.missingtypevisitor import MissingTypesVisitor
25
26
27 class _LambdaChecker(TraverserVisitor):
28 """Check whether an AST subtree contains a lambda expression."""
29
30 found = False
31
32 def visit_lambda_expr(self, _o: LambdaExpr) -> None:
33 self.found = True
34
35
36 def _comprehension_has_lambda(node: GeneratorExpr | DictionaryComprehension) -> bool:
37 """Return True if a comprehension body contains a lambda.
38
39 Only checks body expressions (left_expr/key/value and conditions),
40 not the sequences, since sequences are evaluated in the enclosing scope.
41 """
42 checker = _LambdaChecker()
43 if isinstance(node, GeneratorExpr):
44 node.left_expr.accept(checker)
45 else:
46 node.key.accept(checker)
47 node.value.accept(checker)
48 for conds in node.condlists:
49 for cond in conds:
50 cond.accept(checker)
51 return checker.found
52
53
54 class PreBuildVisitor(ExtendedTraverserVisitor):
55 """Mypy file AST visitor run before building the IR.
56
57 This collects various things, including:
58
59 * Determine relationships between nested functions and functions that
60 contain nested functions
61 * Find non-local variables (free variables)
62 * Find property setters
63 * Find decorators of functions
64 * Find module import groups
65
66 The main IR build pass uses this information.
67 """
68
69 def __init__(
70 self,
71 errors: Errors,
72 current_file: MypyFile,
73 decorators_to_remove: dict[FuncDef, list[int]],
74 types: dict[Expression, Type],
75 ) -> None:
76 super().__init__()
77 # Dict from a function to symbols defined directly in the
78 # function that are used as non-local (free) variables within a
79 # nested function.
80 self.free_variables: dict[FuncItem, set[SymbolNode]] = {}
81
82 # Intermediate data structure used to find the function where
83 # a SymbolNode is declared. Initially this may point to a
84 # function nested inside the function with the declaration,
85 # but we'll eventually update this to refer to the function
86 # with the declaration.
87 self.symbols_to_funcs: dict[SymbolNode, FuncItem] = {}
88
89 # Stack representing current function nesting.
90 self.funcs: list[FuncItem] = []
91
92 # All property setters encountered so far.
93 self.prop_setters: set[FuncDef] = set()
94
95 # A map from any function that contains nested functions to
96 # a set of all the functions that are nested within it.
97 self.encapsulating_funcs: dict[FuncItem, list[FuncItem]] = {}
98
99 # Map nested function to its parent/encapsulating function.
100 self.nested_funcs: dict[FuncItem, FuncItem] = {}
101
102 # Map function to its non-special decorators.
103 self.funcs_to_decorators: dict[FuncDef, list[Expression]] = {}
104
105 # Map function to indices of decorators to remove
106 self.decorators_to_remove: dict[FuncDef, list[int]] = decorators_to_remove
107
108 # A mapping of import groups (a series of Import nodes with
109 # nothing in between) where each group is keyed by its first
110 # import node.
111 self.module_import_groups: dict[Import, list[Import]] = {}
112 self._current_import_group: Import | None = None
113
114 self.errors: Errors = errors
115
116 self.current_file: MypyFile = current_file
117
118 self.missing_types_visitor = MissingTypesVisitor(types)
119
120 # Synthetic FuncDef representing the module scope, created on demand
121 # when a comprehension at module/class level contains a lambda.
122 self._module_fitem: FuncDef | None = None
123
124 # Counter for generating unique synthetic comprehension scope names.
125 self._comprehension_counter = 0
126
127 # Map comprehension AST nodes to synthetic FuncDefs representing
128 # their scope (only for comprehensions that contain lambdas).
129 self.comprehension_to_fitem: dict[GeneratorExpr | DictionaryComprehension, FuncDef] = {}
130
131 def visit(self, o: Node) -> bool:
132 if not isinstance(o, Import):
133 self._current_import_group = None
134 return True
135
136 def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None:
137 # These are cases where mypy may not have types for certain expressions,
138 # but mypyc needs some form type to exist.
139 if stmt.is_alias_def:
140 stmt.rvalue.accept(self.missing_types_visitor)
141 return super().visit_assignment_stmt(stmt)
142
143 def visit_block(self, block: Block) -> None:
144 self._current_import_group = None
145 super().visit_block(block)
146 self._current_import_group = None
147
148 def visit_decorator(self, dec: Decorator) -> None:
149 if dec.decorators:
150 # Only add the function being decorated if there exist
151 # (ordinary) decorators in the decorator list. Certain
152 # decorators (such as @property, @abstractmethod) are
153 # special cased and removed from this list by
154 # mypy. Functions decorated only by special decorators
155 # (and property setters) are not treated as decorated
156 # functions by the IR builder.
157 if isinstance(dec.decorators[0], MemberExpr) and dec.decorators[0].name == "setter":
158 # Property setters are not treated as decorated methods.
159 self.prop_setters.add(dec.func)
160 else:
161 decorators_to_store = dec.decorators.copy()
162 if dec.func in self.decorators_to_remove:
163 to_remove = self.decorators_to_remove[dec.func]
164
165 for i in reversed(to_remove):
166 del decorators_to_store[i]
167 # if all of the decorators are removed, we shouldn't treat this as a decorated
168 # function because there aren't any decorators to apply
169 if not decorators_to_store:
170 return
171
172 self.funcs_to_decorators[dec.func] = decorators_to_store
173 super().visit_decorator(dec)
174
175 def visit_func_def(self, fdef: FuncDef) -> None:
176 # TODO: What about overloaded functions?
177 self.visit_func(fdef)
178 self.visit_symbol_node(fdef)
179
180 def visit_lambda_expr(self, expr: LambdaExpr) -> None:
181 self.visit_func(expr)
182
183 def visit_func(self, func: FuncItem) -> None:
184 # If there were already functions or lambda expressions
185 # defined in the function stack, then note the previous
186 # FuncItem as containing a nested function and the current
187 # FuncItem as being a nested function.
188 if self.funcs:
189 # Add the new func to the set of nested funcs within the
190 # func at top of the func stack.
191 self.encapsulating_funcs.setdefault(self.funcs[-1], []).append(func)
192 # Add the func at top of the func stack as the parent of
193 # new func.
194 self.nested_funcs[func] = self.funcs[-1]
195
196 self.funcs.append(func)
197 super().visit_func(func)
198 self.funcs.pop()
199
200 def _visit_comprehension_with_scope(self, o: GeneratorExpr | DictionaryComprehension) -> None:
201 """Visit a comprehension that contains lambdas.
202
203 Creates a synthetic FuncDef to represent the comprehension's scope,
204 registers it in the function nesting hierarchy, and traverses the
205 comprehension body with it on the stack.
206 """
207 pushed_module = False
208 if not self.funcs:
209 # At module level: push synthetic module FuncDef.
210 if self._module_fitem is None:
211 self._module_fitem = FuncDef("__mypyc_module__")
212 self._module_fitem.line = 1
213 self.funcs.append(self._module_fitem)
214 pushed_module = True
215
216 # Create synthetic FuncDef for the comprehension scope.
217 comprehension_fdef = FuncDef(f"__comprehension_{self._comprehension_counter}__")
218 self._comprehension_counter += 1
219 comprehension_fdef.line = o.line
220 self.comprehension_to_fitem[o] = comprehension_fdef
221
222 # Register as nested within enclosing function.
223 self.encapsulating_funcs.setdefault(self.funcs[-1], []).append(comprehension_fdef)
224 self.nested_funcs[comprehension_fdef] = self.funcs[-1]
225
226 # Push and traverse.
227 self.funcs.append(comprehension_fdef)
228 if isinstance(o, GeneratorExpr):
229 super().visit_generator_expr(o)
230 else:
231 super().visit_dictionary_comprehension(o)
232 self.funcs.pop()
233
234 if pushed_module:
235 self.funcs.pop()
236
237 def visit_generator_expr(self, o: GeneratorExpr) -> None:
238 if _comprehension_has_lambda(o):
239 self._visit_comprehension_with_scope(o)
240 else:
241 super().visit_generator_expr(o)
242
243 def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None:
244 if _comprehension_has_lambda(o):
245 self._visit_comprehension_with_scope(o)
246 else:
247 super().visit_dictionary_comprehension(o)
248
249 def visit_import(self, imp: Import) -> None:
250 if self._current_import_group is not None:
251 self.module_import_groups[self._current_import_group].append(imp)
252 else:
253 self.module_import_groups[imp] = [imp]
254 self._current_import_group = imp
255 super().visit_import(imp)
256
257 def visit_name_expr(self, expr: NameExpr) -> None:
258 if isinstance(expr.node, (Var, FuncDef)):
259 self.visit_symbol_node(expr.node)
260
261 def visit_var(self, var: Var) -> None:
262 self.visit_symbol_node(var)
263
264 def visit_symbol_node(self, symbol: SymbolNode) -> None:
265 if not self.funcs:
266 # We are not inside a function and hence do not need to do
267 # anything regarding free variables.
268 return
269
270 if symbol in self.symbols_to_funcs:
271 orig_func = self.symbols_to_funcs[symbol]
272 if self.is_parent(self.funcs[-1], orig_func):
273 # The function in which the symbol was previously seen is
274 # nested within the function currently being visited. Thus
275 # the current function is a better candidate to contain the
276 # declaration.
277 self.symbols_to_funcs[symbol] = self.funcs[-1]
278 # TODO: Remove from the orig_func free_variables set?
279 self.free_variables.setdefault(self.funcs[-1], set()).add(symbol)
280
281 elif self.is_parent(orig_func, self.funcs[-1]):
282 # The SymbolNode instance has already been visited
283 # before in a parent function, thus it's a non-local
284 # symbol.
285 self.add_free_variable(symbol)
286
287 else:
288 # This is the first time the SymbolNode is being
289 # visited. We map the SymbolNode to the current FuncDef
290 # being visited to note where it was first visited.
291 self.symbols_to_funcs[symbol] = self.funcs[-1]
292
293 def is_parent(self, fitem: FuncItem, child: FuncItem) -> bool:
294 # Check if child is nested within fdef (possibly indirectly
295 # within multiple nested functions).
296 if child not in self.nested_funcs:
297 return False
298 parent = self.nested_funcs[child]
299 return parent == fitem or self.is_parent(fitem, parent)
300
301 def add_free_variable(self, symbol: SymbolNode) -> None:
302 # Find the function where the symbol was (likely) first declared,
303 # and mark is as a non-local symbol within that function.
304 func = self.symbols_to_funcs[symbol]
305 self.free_variables.setdefault(func, set()).add(symbol)