Debian Codegraph @

mypyc/irbuild/env_class.py

raw
1 """Generate classes representing function environments (+ related operations).
2
3 If we have a nested function that has non-local (free) variables, access to the
4 non-locals is via an instance of an environment class. Example:
5
6 def f() -> int:
7 x = 0 # Make 'x' an attribute of an environment class instance
8
9 def g() -> int:
10 # We have access to the environment class instance to
11 # allow accessing 'x'
12 return x + 2
13
14 x = x + 1 # Modify the attribute
15 return g()
16 """
17
18 from __future__ import annotations
19
20 from mypy.nodes import Argument, FuncDef, FuncItem, SymbolNode, Var
21 from mypyc.common import (
22 BITMAP_BITS,
23 ENV_ATTR_NAME,
24 GENERATOR_ATTRIBUTE_PREFIX,
25 SELF_NAME,
26 bitmap_name,
27 )
28 from mypyc.ir.class_ir import ClassIR
29 from mypyc.ir.ops import Call, GetAttr, SetAttr, Value
30 from mypyc.ir.rtypes import RInstance, bitmap_rprimitive, object_rprimitive
31 from mypyc.irbuild.builder import IRBuilder, SymbolTarget
32 from mypyc.irbuild.context import FuncInfo, GeneratorClass, ImplicitClass
33 from mypyc.irbuild.targets import AssignmentTargetAttr
34
35
36 def setup_env_class(builder: IRBuilder) -> ClassIR:
37 """Generate a class representing a function environment.
38
39 Note that the variables in the function environment are not
40 actually populated here. This is because when the environment
41 class is generated, the function environment has not yet been
42 visited. This behavior is allowed so that when the compiler visits
43 nested functions, it can use the returned ClassIR instance to
44 figure out free variables it needs to access. The remaining
45 attributes of the environment class are populated when the
46 environment registers are loaded.
47
48 Return a ClassIR representing an environment for a function
49 containing a nested function.
50 """
51 env_class = ClassIR(
52 f"{builder.fn_info.namespaced_name()}_env",
53 builder.module_name,
54 is_generated=True,
55 is_final_class=True,
56 )
57 env_class.reuse_freed_instance = True
58 env_class.attributes[SELF_NAME] = RInstance(env_class)
59 if builder.fn_info.is_nested and builder.fn_infos[-2]._env_class is not None:
60 # If the function is nested, its environment class must contain an environment
61 # attribute pointing to its encapsulating functions' environment class.
62 env_class.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_infos[-2].env_class)
63 if builder.fn_info.contains_nested:
64 env_class.attrs_to_keep_alive_on_completion.add(ENV_ATTR_NAME)
65 env_class.mro = [env_class]
66 builder.fn_info.env_class = env_class
67 builder.classes.append(env_class)
68 return env_class
69
70
71 def finalize_env_class(builder: IRBuilder, prefix: str = "") -> None:
72 """Generate, instantiate, and set up the environment of an environment class."""
73 if not builder.fn_info.can_merge_generator_and_env_classes():
74 instantiate_env_class(builder)
75
76 # Iterate through the function arguments and replace local definitions (using registers)
77 # that were previously added to the environment with references to the function's
78 # environment class. Comprehension scopes have no arguments to add.
79 if not builder.fn_info.is_comprehension_scope:
80 if builder.fn_info.is_nested:
81 add_args_to_env(
82 builder, local=False, base=builder.fn_info.callable_class, prefix=prefix
83 )
84 else:
85 add_args_to_env(builder, local=False, base=builder.fn_info, prefix=prefix)
86
87
88 def instantiate_env_class(builder: IRBuilder) -> Value:
89 """Assign an environment class to a register named after the given function definition."""
90 curr_env_reg = builder.add(
91 Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line)
92 )
93
94 if builder.fn_info.is_nested and not builder.fn_info.is_comprehension_scope:
95 builder.fn_info.callable_class._curr_env_reg = curr_env_reg
96 builder.add(
97 SetAttr(
98 curr_env_reg,
99 ENV_ATTR_NAME,
100 builder.fn_info.callable_class.prev_env_reg,
101 builder.fn_info.fitem.line,
102 )
103 )
104 else:
105 # Top-level functions and comprehension scopes store env reg directly.
106 builder.fn_info._curr_env_reg = curr_env_reg
107 # Comprehension scopes link to parent env if it exists.
108 if (
109 builder.fn_info.is_nested
110 and builder.fn_infos[-2]._env_class is not None
111 and builder.fn_infos[-2]._curr_env_reg is not None
112 ):
113 builder.add(
114 SetAttr(
115 curr_env_reg,
116 ENV_ATTR_NAME,
117 builder.fn_infos[-2].curr_env_reg,
118 builder.fn_info.fitem.line,
119 )
120 )
121
122 return curr_env_reg
123
124
125 def load_env_registers(builder: IRBuilder, prefix: str = "") -> None:
126 """Load the registers for the current FuncItem being visited.
127
128 Adds the arguments of the FuncItem to the environment. If the
129 FuncItem is nested inside of another function, then this also
130 loads all of the outer environments of the FuncItem into registers
131 so that they can be used when accessing free variables.
132 """
133 add_args_to_env(builder, local=True, prefix=prefix)
134
135 fn_info = builder.fn_info
136 fitem = fn_info.fitem
137 if fn_info.is_nested and builder.fn_infos[-2]._env_class is not None:
138 load_outer_envs(builder, fn_info.callable_class)
139 # If this is a FuncDef, then make sure to load the FuncDef into its own environment
140 # class so that the function can be called recursively.
141 if isinstance(fitem, FuncDef) and fn_info.add_nested_funcs_to_env:
142 setup_func_for_recursive_call(builder, fitem, fn_info.callable_class, prefix=prefix)
143
144
145 def load_outer_env(
146 builder: IRBuilder, base: Value, outer_env: dict[SymbolNode, SymbolTarget]
147 ) -> Value:
148 """Load the environment class for a given base into a register.
149
150 Additionally, iterates through all of the SymbolNode and
151 AssignmentTarget instances of the environment at the given index's
152 symtable, and adds those instances to the environment of the
153 current environment. This is done so that the current environment
154 can access outer environment variables without having to reload
155 all of the environment registers.
156
157 Returns the register where the environment class was loaded.
158 """
159 env = builder.add(GetAttr(base, ENV_ATTR_NAME, builder.fn_info.fitem.line))
160 assert isinstance(env.type, RInstance), f"{env} must be of type RInstance"
161
162 for symbol, target in outer_env.items():
163 attr_name = symbol.name
164 if isinstance(target, AssignmentTargetAttr):
165 attr_name = target.attr
166 env.type.class_ir.attributes[attr_name] = target.type
167 symbol_target = AssignmentTargetAttr(env, attr_name)
168 builder.add_target(symbol, symbol_target)
169
170 return env
171
172
173 def load_outer_envs(builder: IRBuilder, base: ImplicitClass) -> None:
174 index = len(builder.builders) - 2
175
176 # Load the first outer environment. This one is special because it gets saved in the
177 # FuncInfo instance's prev_env_reg field.
178 has_outer = index > 1 or (index == 1 and builder.fn_infos[1].contains_nested)
179 if has_outer and builder.fn_infos[index]._env_class is not None:
180 # outer_env = builder.fn_infos[index].environment
181 outer_env = builder.symtables[index]
182 if isinstance(base, GeneratorClass):
183 base.prev_env_reg = load_outer_env(builder, base.curr_env_reg, outer_env)
184 else:
185 base.prev_env_reg = load_outer_env(builder, base.self_reg, outer_env)
186 env_reg = base.prev_env_reg
187 index -= 1
188
189 # Load the remaining outer environments into registers.
190 while index > 1:
191 if builder.fn_infos[index]._env_class is None:
192 break
193 # outer_env = builder.fn_infos[index].environment
194 outer_env = builder.symtables[index]
195 env_reg = load_outer_env(builder, env_reg, outer_env)
196 index -= 1
197
198
199 def num_bitmap_args(builder: IRBuilder, args: list[Argument]) -> int:
200 n = 0
201 for arg in args:
202 t = builder.type_to_rtype(arg.variable.type)
203 if t.error_overlap and arg.kind.is_optional():
204 n += 1
205 return (n + (BITMAP_BITS - 1)) // BITMAP_BITS
206
207
208 def add_args_to_env(
209 builder: IRBuilder,
210 local: bool = True,
211 base: FuncInfo | ImplicitClass | None = None,
212 reassign: bool = True,
213 prefix: str = "",
214 ) -> None:
215 fn_info = builder.fn_info
216 args = fn_info.fitem.arguments
217 nb = num_bitmap_args(builder, args)
218 if local:
219 for arg in args:
220 rtype = builder.type_to_rtype(arg.variable.type)
221 builder.add_local_reg(arg.variable, rtype, is_arg=True)
222 for i in reversed(range(nb)):
223 builder.add_local_reg(Var(bitmap_name(i)), bitmap_rprimitive, is_arg=True)
224 else:
225 for arg in args:
226 if (
227 is_free_variable(builder, arg.variable)
228 or fn_info.is_generator
229 or fn_info.is_coroutine
230 ):
231 rtype = builder.type_to_rtype(arg.variable.type)
232 assert base is not None, "base cannot be None for adding nonlocal args"
233 builder.add_var_to_env_class(
234 arg.variable,
235 rtype,
236 base,
237 reassign=reassign,
238 keep_alive_on_completion=(
239 is_free_variable(builder, arg.variable)
240 or is_free_variable_in_nested_func(
241 builder, builder.fn_info.fitem, arg.variable
242 )
243 ),
244 prefix=prefix,
245 )
246
247
248 def add_vars_to_env(builder: IRBuilder, prefix: str = "") -> None:
249 """Add relevant local variables and nested functions to the environment class.
250
251 Add all variables and functions that are declared/defined within current
252 function and are referenced in functions nested within this one to this
253 function's environment class so the nested functions can reference
254 them even if they are declared after the nested function's definition.
255 Note that this is done before visiting the body of the function.
256 """
257 env_for_func: FuncInfo | ImplicitClass = builder.fn_info
258 if builder.fn_info.is_generator:
259 env_for_func = builder.fn_info.generator_class
260 elif (
261 builder.fn_info.is_nested or builder.fn_info.in_non_ext
262 ) and not builder.fn_info.is_comprehension_scope:
263 env_for_func = builder.fn_info.callable_class
264
265 if builder.fn_info.fitem in builder.free_variables:
266 # Sort the variables to keep things deterministic
267 for var in sorted(builder.free_variables[builder.fn_info.fitem], key=lambda x: x.name):
268 if isinstance(var, Var):
269 rtype = builder.type_to_rtype(var.type)
270 builder.add_var_to_env_class(
271 var,
272 rtype,
273 env_for_func,
274 reassign=False,
275 keep_alive_on_completion=True,
276 prefix=prefix,
277 )
278
279 if builder.fn_info.fitem in builder.encapsulating_funcs:
280 for nested_fn in builder.encapsulating_funcs[builder.fn_info.fitem]:
281 if isinstance(nested_fn, FuncDef):
282 # The return type is 'object' instead of an RInstance of the
283 # callable class because differently defined functions with
284 # the same name and signature across conditional blocks
285 # will generate different callable classes, so the callable
286 # class that gets instantiated must be generic.
287 nested_prefix = prefix
288 if nested_fn.is_generator or nested_fn.is_coroutine:
289 nested_prefix = GENERATOR_ATTRIBUTE_PREFIX
290 builder.add_var_to_env_class(
291 nested_fn,
292 object_rprimitive,
293 env_for_func,
294 reassign=False,
295 keep_alive_on_completion=is_free_variable(builder, nested_fn),
296 prefix=nested_prefix,
297 )
298
299
300 def setup_func_for_recursive_call(
301 builder: IRBuilder, fdef: FuncDef, base: ImplicitClass, prefix: str = ""
302 ) -> None:
303 """Enable calling a nested function (with a callable class) recursively.
304
305 Adds the instance of the callable class representing the given
306 FuncDef to a register in the environment so that the function can
307 be called recursively. Note that this needs to be done only for
308 nested functions.
309 """
310 # First, set the attribute of the environment class so that GetAttr can be called on it.
311 prev_env = builder.fn_infos[-2].env_class
312 attr_name = prefix + fdef.name
313 prev_env.attributes[attr_name] = builder.type_to_rtype(fdef.type)
314 line = fdef.line
315
316 if isinstance(base, GeneratorClass):
317 # If we are dealing with a generator class, then we need to first get the register
318 # holding the current environment class, and load the previous environment class from
319 # there.
320 prev_env_reg = builder.add(GetAttr(base.curr_env_reg, ENV_ATTR_NAME, line))
321 else:
322 prev_env_reg = base.prev_env_reg
323
324 # Obtain the instance of the callable class representing the FuncDef, and add it to the
325 # current environment.
326 val = builder.add(GetAttr(prev_env_reg, attr_name, line))
327 target = builder.add_local_reg(fdef, object_rprimitive)
328 builder.assign(target, val, line)
329
330
331 def is_free_variable(builder: IRBuilder, symbol: SymbolNode) -> bool:
332 fitem = builder.fn_info.fitem
333 return fitem in builder.free_variables and symbol in builder.free_variables[fitem]
334
335
336 def is_free_variable_in_nested_func(
337 builder: IRBuilder, fitem: FuncItem, symbol: SymbolNode
338 ) -> bool:
339 for nested in builder.encapsulating_funcs.get(fitem, []):
340 if symbol in builder.free_variables.get(nested, set()):
341 return True
342 if is_free_variable_in_nested_func(builder, nested, symbol):
343 return True
344 return False