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, 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 env_class.mro = [env_class]
64 builder.fn_info.env_class = env_class
65 builder.classes.append(env_class)
66 return env_class
67
68
69 def finalize_env_class(builder: IRBuilder, prefix: str = "") -> None:
70 """Generate, instantiate, and set up the environment of an environment class."""
71 if not builder.fn_info.can_merge_generator_and_env_classes():
72 instantiate_env_class(builder)
73
74 # Iterate through the function arguments and replace local definitions (using registers)
75 # that were previously added to the environment with references to the function's
76 # environment class. Comprehension scopes have no arguments to add.
77 if not builder.fn_info.is_comprehension_scope:
78 if builder.fn_info.is_nested:
79 add_args_to_env(
80 builder, local=False, base=builder.fn_info.callable_class, prefix=prefix
81 )
82 else:
83 add_args_to_env(builder, local=False, base=builder.fn_info, prefix=prefix)
84
85
86 def instantiate_env_class(builder: IRBuilder) -> Value:
87 """Assign an environment class to a register named after the given function definition."""
88 curr_env_reg = builder.add(
89 Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line)
90 )
91
92 if builder.fn_info.is_nested and not builder.fn_info.is_comprehension_scope:
93 builder.fn_info.callable_class._curr_env_reg = curr_env_reg
94 builder.add(
95 SetAttr(
96 curr_env_reg,
97 ENV_ATTR_NAME,
98 builder.fn_info.callable_class.prev_env_reg,
99 builder.fn_info.fitem.line,
100 )
101 )
102 else:
103 # Top-level functions and comprehension scopes store env reg directly.
104 builder.fn_info._curr_env_reg = curr_env_reg
105 # Comprehension scopes link to parent env if it exists.
106 if (
107 builder.fn_info.is_nested
108 and builder.fn_infos[-2]._env_class is not None
109 and builder.fn_infos[-2]._curr_env_reg is not None
110 ):
111 builder.add(
112 SetAttr(
113 curr_env_reg,
114 ENV_ATTR_NAME,
115 builder.fn_infos[-2].curr_env_reg,
116 builder.fn_info.fitem.line,
117 )
118 )
119
120 return curr_env_reg
121
122
123 def load_env_registers(builder: IRBuilder, prefix: str = "") -> None:
124 """Load the registers for the current FuncItem being visited.
125
126 Adds the arguments of the FuncItem to the environment. If the
127 FuncItem is nested inside of another function, then this also
128 loads all of the outer environments of the FuncItem into registers
129 so that they can be used when accessing free variables.
130 """
131 add_args_to_env(builder, local=True, prefix=prefix)
132
133 fn_info = builder.fn_info
134 fitem = fn_info.fitem
135 if fn_info.is_nested and builder.fn_infos[-2]._env_class is not None:
136 load_outer_envs(builder, fn_info.callable_class)
137 # If this is a FuncDef, then make sure to load the FuncDef into its own environment
138 # class so that the function can be called recursively.
139 if isinstance(fitem, FuncDef) and fn_info.add_nested_funcs_to_env:
140 setup_func_for_recursive_call(builder, fitem, fn_info.callable_class, prefix=prefix)
141
142
143 def load_outer_env(
144 builder: IRBuilder, base: Value, outer_env: dict[SymbolNode, SymbolTarget]
145 ) -> Value:
146 """Load the environment class for a given base into a register.
147
148 Additionally, iterates through all of the SymbolNode and
149 AssignmentTarget instances of the environment at the given index's
150 symtable, and adds those instances to the environment of the
151 current environment. This is done so that the current environment
152 can access outer environment variables without having to reload
153 all of the environment registers.
154
155 Returns the register where the environment class was loaded.
156 """
157 env = builder.add(GetAttr(base, ENV_ATTR_NAME, builder.fn_info.fitem.line))
158 assert isinstance(env.type, RInstance), f"{env} must be of type RInstance"
159
160 for symbol, target in outer_env.items():
161 attr_name = symbol.name
162 if isinstance(target, AssignmentTargetAttr):
163 attr_name = target.attr
164 env.type.class_ir.attributes[attr_name] = target.type
165 symbol_target = AssignmentTargetAttr(env, attr_name)
166 builder.add_target(symbol, symbol_target)
167
168 return env
169
170
171 def load_outer_envs(builder: IRBuilder, base: ImplicitClass) -> None:
172 index = len(builder.builders) - 2
173
174 # Load the first outer environment. This one is special because it gets saved in the
175 # FuncInfo instance's prev_env_reg field.
176 has_outer = index > 1 or (index == 1 and builder.fn_infos[1].contains_nested)
177 if has_outer and builder.fn_infos[index]._env_class is not None:
178 # outer_env = builder.fn_infos[index].environment
179 outer_env = builder.symtables[index]
180 if isinstance(base, GeneratorClass):
181 base.prev_env_reg = load_outer_env(builder, base.curr_env_reg, outer_env)
182 else:
183 base.prev_env_reg = load_outer_env(builder, base.self_reg, outer_env)
184 env_reg = base.prev_env_reg
185 index -= 1
186
187 # Load the remaining outer environments into registers.
188 while index > 1:
189 if builder.fn_infos[index]._env_class is None:
190 break
191 # outer_env = builder.fn_infos[index].environment
192 outer_env = builder.symtables[index]
193 env_reg = load_outer_env(builder, env_reg, outer_env)
194 index -= 1
195
196
197 def num_bitmap_args(builder: IRBuilder, args: list[Argument]) -> int:
198 n = 0
199 for arg in args:
200 t = builder.type_to_rtype(arg.variable.type)
201 if t.error_overlap and arg.kind.is_optional():
202 n += 1
203 return (n + (BITMAP_BITS - 1)) // BITMAP_BITS
204
205
206 def add_args_to_env(
207 builder: IRBuilder,
208 local: bool = True,
209 base: FuncInfo | ImplicitClass | None = None,
210 reassign: bool = True,
211 prefix: str = "",
212 ) -> None:
213 fn_info = builder.fn_info
214 args = fn_info.fitem.arguments
215 nb = num_bitmap_args(builder, args)
216 if local:
217 for arg in args:
218 rtype = builder.type_to_rtype(arg.variable.type)
219 builder.add_local_reg(arg.variable, rtype, is_arg=True)
220 for i in reversed(range(nb)):
221 builder.add_local_reg(Var(bitmap_name(i)), bitmap_rprimitive, is_arg=True)
222 else:
223 for arg in args:
224 if (
225 is_free_variable(builder, arg.variable)
226 or fn_info.is_generator
227 or fn_info.is_coroutine
228 ):
229 rtype = builder.type_to_rtype(arg.variable.type)
230 assert base is not None, "base cannot be None for adding nonlocal args"
231 builder.add_var_to_env_class(
232 arg.variable, rtype, base, reassign=reassign, prefix=prefix
233 )
234
235
236 def add_vars_to_env(builder: IRBuilder, prefix: str = "") -> None:
237 """Add relevant local variables and nested functions to the environment class.
238
239 Add all variables and functions that are declared/defined within current
240 function and are referenced in functions nested within this one to this
241 function's environment class so the nested functions can reference
242 them even if they are declared after the nested function's definition.
243 Note that this is done before visiting the body of the function.
244 """
245 env_for_func: FuncInfo | ImplicitClass = builder.fn_info
246 if builder.fn_info.is_generator:
247 env_for_func = builder.fn_info.generator_class
248 elif (
249 builder.fn_info.is_nested or builder.fn_info.in_non_ext
250 ) and not builder.fn_info.is_comprehension_scope:
251 env_for_func = builder.fn_info.callable_class
252
253 if builder.fn_info.fitem in builder.free_variables:
254 # Sort the variables to keep things deterministic
255 for var in sorted(builder.free_variables[builder.fn_info.fitem], key=lambda x: x.name):
256 if isinstance(var, Var):
257 rtype = builder.type_to_rtype(var.type)
258 builder.add_var_to_env_class(
259 var, rtype, env_for_func, reassign=False, prefix=prefix
260 )
261
262 if builder.fn_info.fitem in builder.encapsulating_funcs:
263 for nested_fn in builder.encapsulating_funcs[builder.fn_info.fitem]:
264 if isinstance(nested_fn, FuncDef):
265 # The return type is 'object' instead of an RInstance of the
266 # callable class because differently defined functions with
267 # the same name and signature across conditional blocks
268 # will generate different callable classes, so the callable
269 # class that gets instantiated must be generic.
270 if nested_fn.is_generator or nested_fn.is_coroutine:
271 prefix = GENERATOR_ATTRIBUTE_PREFIX
272 builder.add_var_to_env_class(
273 nested_fn, object_rprimitive, env_for_func, reassign=False, prefix=prefix
274 )
275
276
277 def setup_func_for_recursive_call(
278 builder: IRBuilder, fdef: FuncDef, base: ImplicitClass, prefix: str = ""
279 ) -> None:
280 """Enable calling a nested function (with a callable class) recursively.
281
282 Adds the instance of the callable class representing the given
283 FuncDef to a register in the environment so that the function can
284 be called recursively. Note that this needs to be done only for
285 nested functions.
286 """
287 # First, set the attribute of the environment class so that GetAttr can be called on it.
288 prev_env = builder.fn_infos[-2].env_class
289 attr_name = prefix + fdef.name
290 prev_env.attributes[attr_name] = builder.type_to_rtype(fdef.type)
291 line = fdef.line
292
293 if isinstance(base, GeneratorClass):
294 # If we are dealing with a generator class, then we need to first get the register
295 # holding the current environment class, and load the previous environment class from
296 # there.
297 prev_env_reg = builder.add(GetAttr(base.curr_env_reg, ENV_ATTR_NAME, line))
298 else:
299 prev_env_reg = base.prev_env_reg
300
301 # Obtain the instance of the callable class representing the FuncDef, and add it to the
302 # current environment.
303 val = builder.add(GetAttr(prev_env_reg, attr_name, line))
304 target = builder.add_local_reg(fdef, object_rprimitive)
305 builder.assign(target, val, line)
306
307
308 def is_free_variable(builder: IRBuilder, symbol: SymbolNode) -> bool:
309 fitem = builder.fn_info.fitem
310 return fitem in builder.free_variables and symbol in builder.free_variables[fitem]