Debian Codegraph @

mypyc/irbuild/generator.py

raw
1 """Generate IR for generator functions.
2
3 A generator function is represented by a class that implements the
4 generator protocol and keeps track of the generator state, including
5 local variables.
6
7 The top-level logic for dealing with generator functions is in
8 mypyc.irbuild.function.
9 """
10
11 from __future__ import annotations
12
13 from collections.abc import Callable
14
15 from mypy.nodes import ARG_OPT, FuncDef, Var
16 from mypyc.common import ENV_ATTR_NAME, GENERATOR_ATTRIBUTE_PREFIX, NEXT_LABEL_ATTR_NAME
17 from mypyc.ir.class_ir import ClassIR
18 from mypyc.ir.func_ir import FuncDecl, FuncIR
19 from mypyc.ir.ops import (
20 NO_TRACEBACK_LINE_NO,
21 BasicBlock,
22 Branch,
23 Call,
24 Goto,
25 Integer,
26 MethodCall,
27 RaiseStandardError,
28 Register,
29 Return,
30 SetAttr,
31 TupleSet,
32 Unreachable,
33 Value,
34 )
35 from mypyc.ir.rtypes import (
36 RInstance,
37 int32_rprimitive,
38 object_pointer_rprimitive,
39 object_rprimitive,
40 )
41 from mypyc.irbuild.builder import IRBuilder, calculate_arg_defaults, gen_arg_defaults
42 from mypyc.irbuild.context import FuncInfo
43 from mypyc.irbuild.env_class import (
44 add_args_to_env,
45 add_vars_to_env,
46 finalize_env_class,
47 load_env_registers,
48 load_outer_env,
49 load_outer_envs,
50 setup_func_for_recursive_call,
51 )
52 from mypyc.irbuild.nonlocalcontrol import ExceptNonlocalControl
53 from mypyc.irbuild.prepare import GENERATOR_HELPER_NAME
54 from mypyc.primitives.exc_ops import (
55 error_catch_op,
56 exc_matches_op,
57 raise_exception_with_tb_op,
58 reraise_exception_op,
59 restore_exc_info_op,
60 )
61
62
63 def gen_generator_func(
64 builder: IRBuilder,
65 gen_func_ir: Callable[
66 [list[Register], list[BasicBlock], FuncInfo], tuple[FuncIR, Value | None]
67 ],
68 ) -> tuple[FuncIR, Value | None]:
69 """Generate IR for generator function that returns generator object."""
70 setup_generator_class(builder)
71 load_env_registers(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)
72 gen_arg_defaults(builder)
73 if builder.fn_info.can_merge_generator_and_env_classes():
74 gen = instantiate_generator_class(builder)
75 builder.fn_info._curr_env_reg = gen
76 finalize_env_class(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)
77 else:
78 finalize_env_class(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)
79 gen = instantiate_generator_class(builder)
80 builder.add(Return(gen))
81
82 args, _, blocks, ret_type, fn_info = builder.leave()
83 func_ir, func_reg = gen_func_ir(args, blocks, fn_info)
84 return func_ir, func_reg
85
86
87 def gen_generator_func_body(builder: IRBuilder, fn_info: FuncInfo, func_reg: Value | None) -> None:
88 """Generate IR based on the body of a generator function.
89
90 Add "__next__", "__iter__" and other generator methods to the generator
91 class that implements the function (each function gets a separate class).
92
93 Return the symbol table for the body.
94 """
95 builder.enter(fn_info, ret_type=object_rprimitive)
96 setup_env_for_generator_class(builder)
97
98 load_outer_envs(builder, builder.fn_info.generator_class)
99 top_level = builder.top_level_fn_info()
100 fitem = fn_info.fitem
101 if (
102 builder.fn_info.is_nested
103 and isinstance(fitem, FuncDef)
104 and top_level
105 and top_level.add_nested_funcs_to_env
106 ):
107 setup_func_for_recursive_call(
108 builder, fitem, builder.fn_info.generator_class, prefix=GENERATOR_ATTRIBUTE_PREFIX
109 )
110 create_switch_for_generator_class(builder)
111 add_raise_exception_blocks_to_generator_class(builder, fitem.line)
112
113 add_vars_to_env(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)
114
115 builder.accept(fitem.body)
116 builder.maybe_add_implicit_return()
117
118 populate_switch_for_generator_class(builder)
119
120 # Hang on to the local symbol table, since the caller will use it
121 # to calculate argument defaults.
122 symtable = builder.symtables[-1]
123
124 args, _, blocks, ret_type, fn_info = builder.leave()
125
126 add_methods_to_generator_class(builder, fn_info, args, blocks, fitem.is_coroutine)
127
128 # Evaluate argument defaults in the surrounding scope, since we
129 # calculate them *once* when the function definition is evaluated.
130 calculate_arg_defaults(builder, fn_info, func_reg, symtable)
131
132
133 def instantiate_generator_class(builder: IRBuilder) -> Value:
134 fitem = builder.fn_info.fitem
135 generator_reg = builder.add(Call(builder.fn_info.generator_class.ir.ctor, [], fitem.line))
136
137 if builder.fn_info.can_merge_generator_and_env_classes():
138 # Set the generator instance to the initial state (zero).
139 zero = Integer(0)
140 builder.add(SetAttr(generator_reg, NEXT_LABEL_ATTR_NAME, zero, fitem.line))
141 else:
142 # Get the current environment register. If the current function is nested, then the
143 # generator class gets instantiated from the callable class' '__call__' method, and hence
144 # we use the callable class' environment register. Otherwise, we use the original
145 # function's environment register.
146 if builder.fn_info.is_nested:
147 curr_env_reg = builder.fn_info.callable_class.curr_env_reg
148 else:
149 curr_env_reg = builder.fn_info.curr_env_reg
150
151 # Set the generator class' environment attribute to point at the environment class
152 # defined in the current scope.
153 builder.add(SetAttr(generator_reg, ENV_ATTR_NAME, curr_env_reg, fitem.line))
154
155 # Set the generator instance's environment to the initial state (zero).
156 zero = Integer(0)
157 builder.add(SetAttr(curr_env_reg, NEXT_LABEL_ATTR_NAME, zero, fitem.line))
158 return generator_reg
159
160
161 def setup_generator_class(builder: IRBuilder) -> ClassIR:
162 mapper = builder.mapper
163 assert isinstance(builder.fn_info.fitem, FuncDef), builder.fn_info.fitem
164 generator_class_ir = mapper.fdef_to_generator[builder.fn_info.fitem]
165 if builder.fn_info.can_merge_generator_and_env_classes():
166 builder.fn_info.env_class = generator_class_ir
167 else:
168 generator_class_ir.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_info.env_class)
169
170 builder.classes.append(generator_class_ir)
171 return generator_class_ir
172
173
174 def create_switch_for_generator_class(builder: IRBuilder) -> None:
175 builder.add(Goto(builder.fn_info.generator_class.switch_block))
176 block = BasicBlock()
177 builder.fn_info.generator_class.continuation_blocks.append(block)
178 builder.activate_block(block)
179
180
181 def populate_switch_for_generator_class(builder: IRBuilder) -> None:
182 cls = builder.fn_info.generator_class
183 line = builder.fn_info.fitem.line
184
185 builder.activate_block(cls.switch_block)
186 for label, true_block in enumerate(cls.continuation_blocks):
187 false_block = BasicBlock()
188 comparison = builder.binary_op(cls.next_label_reg, Integer(label), "==", line)
189 builder.add_bool_branch(comparison, true_block, false_block)
190 builder.activate_block(false_block)
191
192 builder.add(RaiseStandardError(RaiseStandardError.STOP_ITERATION, None, line))
193 builder.add(Unreachable())
194
195
196 def add_raise_exception_blocks_to_generator_class(builder: IRBuilder, line: int) -> None:
197 """Add error handling blocks to a generator class.
198
199 Generates blocks to check if error flags are set while calling the
200 helper method for generator functions, and raises an exception if
201 those flags are set.
202 """
203 cls = builder.fn_info.generator_class
204 assert cls.exc_regs is not None
205 exc_type, exc_val, exc_tb = cls.exc_regs
206
207 # Check to see if an exception was raised.
208 error_block = BasicBlock()
209 ok_block = BasicBlock()
210 comparison = builder.translate_is_op(exc_type, builder.none_object(), "is not", line)
211 builder.add_bool_branch(comparison, error_block, ok_block)
212
213 builder.activate_block(error_block)
214 builder.call_c(raise_exception_with_tb_op, [exc_type, exc_val, exc_tb], line)
215 builder.add(Unreachable())
216 builder.goto_and_activate(ok_block)
217
218
219 def add_methods_to_generator_class(
220 builder: IRBuilder,
221 fn_info: FuncInfo,
222 arg_regs: list[Register],
223 blocks: list[BasicBlock],
224 is_coroutine: bool,
225 ) -> None:
226 helper_fn_decl = add_helper_to_generator_class(builder, arg_regs, blocks, fn_info)
227 add_next_to_generator_class(builder, fn_info, helper_fn_decl)
228 add_send_to_generator_class(builder, fn_info, helper_fn_decl)
229 add_iter_to_generator_class(builder, fn_info)
230 add_throw_to_generator_class(builder, fn_info, helper_fn_decl)
231 add_close_to_generator_class(builder, fn_info)
232 if is_coroutine:
233 add_await_to_generator_class(builder, fn_info)
234
235
236 def add_helper_to_generator_class(
237 builder: IRBuilder, arg_regs: list[Register], blocks: list[BasicBlock], fn_info: FuncInfo
238 ) -> FuncDecl:
239 """Generates a helper method for a generator class, called by '__next__' and 'throw'."""
240 helper_fn_decl = fn_info.generator_class.ir.method_decls[GENERATOR_HELPER_NAME]
241 helper_fn_ir = FuncIR(
242 helper_fn_decl, arg_regs, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name
243 )
244 fn_info.generator_class.ir.methods[GENERATOR_HELPER_NAME] = helper_fn_ir
245 builder.functions.append(helper_fn_ir)
246 fn_info.env_class.env_user_function = helper_fn_ir
247
248 return helper_fn_decl
249
250
251 def add_iter_to_generator_class(builder: IRBuilder, fn_info: FuncInfo) -> None:
252 """Generates the '__iter__' method for a generator class."""
253 with builder.enter_method(fn_info.generator_class.ir, "__iter__", object_rprimitive, fn_info):
254 builder.add(Return(builder.self()))
255
256
257 def add_next_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl) -> None:
258 """Generates the '__next__' method for a generator class."""
259 with builder.enter_method(fn_info.generator_class.ir, "__next__", object_rprimitive, fn_info):
260 none_reg = builder.none_object()
261 # Call the helper function with error flags set to Py_None, and return that result.
262 result = builder.add(
263 Call(
264 fn_decl,
265 [
266 builder.self(),
267 none_reg,
268 none_reg,
269 none_reg,
270 none_reg,
271 Integer(0, object_pointer_rprimitive),
272 ],
273 fn_info.fitem.line,
274 )
275 )
276 builder.add(Return(result))
277
278
279 def add_send_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl) -> None:
280 """Generates the 'send' method for a generator class."""
281 with builder.enter_method(fn_info.generator_class.ir, "send", object_rprimitive, fn_info):
282 arg = builder.add_argument("arg", object_rprimitive)
283 none_reg = builder.none_object()
284 # Call the helper function with error flags set to Py_None, and return that result.
285 result = builder.add(
286 Call(
287 fn_decl,
288 [
289 builder.self(),
290 none_reg,
291 none_reg,
292 none_reg,
293 builder.read(arg),
294 Integer(0, object_pointer_rprimitive),
295 ],
296 fn_info.fitem.line,
297 )
298 )
299 builder.add(Return(result))
300
301
302 def add_throw_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl) -> None:
303 """Generates the 'throw' method for a generator class."""
304 with builder.enter_method(fn_info.generator_class.ir, "throw", object_rprimitive, fn_info):
305 typ = builder.add_argument("type", object_rprimitive)
306 val = builder.add_argument("value", object_rprimitive, ARG_OPT)
307 tb = builder.add_argument("traceback", object_rprimitive, ARG_OPT)
308
309 # Because the value and traceback arguments are optional and hence
310 # can be NULL if not passed in, we have to assign them Py_None if
311 # they are not passed in.
312 none_reg = builder.none_object()
313 builder.assign_if_null(val, lambda: none_reg, fn_info.fitem.line)
314 builder.assign_if_null(tb, lambda: none_reg, fn_info.fitem.line)
315
316 # Call the helper function using the arguments passed in, and return that result.
317 result = builder.add(
318 Call(
319 fn_decl,
320 [
321 builder.self(),
322 builder.read(typ),
323 builder.read(val),
324 builder.read(tb),
325 none_reg,
326 Integer(0, object_pointer_rprimitive),
327 ],
328 fn_info.fitem.line,
329 )
330 )
331 builder.add(Return(result))
332
333
334 def add_close_to_generator_class(builder: IRBuilder, fn_info: FuncInfo) -> None:
335 """Generates the '__close__' method for a generator class."""
336 with builder.enter_method(fn_info.generator_class.ir, "close", object_rprimitive, fn_info):
337 except_block, else_block = BasicBlock(), BasicBlock()
338 builder.builder.push_error_handler(except_block)
339 builder.goto_and_activate(BasicBlock())
340 generator_exit = builder.load_module_attr_by_fullname(
341 "builtins.GeneratorExit", fn_info.fitem.line
342 )
343 builder.add(
344 MethodCall(
345 builder.self(),
346 "throw",
347 [generator_exit, builder.none_object(), builder.none_object()],
348 fn_info.fitem.line,
349 )
350 )
351 builder.goto(else_block)
352 builder.builder.pop_error_handler()
353
354 builder.activate_block(except_block)
355 old_exc = builder.call_c(error_catch_op, [], fn_info.fitem.line)
356 builder.nonlocal_control.append(
357 ExceptNonlocalControl(builder.nonlocal_control[-1], old_exc)
358 )
359 stop_iteration = builder.load_module_attr_by_fullname(
360 "builtins.StopIteration", fn_info.fitem.line
361 )
362 exceptions = builder.add(TupleSet([generator_exit, stop_iteration], fn_info.fitem.line))
363 matches = builder.call_c(exc_matches_op, [exceptions], fn_info.fitem.line)
364
365 match_block, non_match_block = BasicBlock(), BasicBlock()
366 builder.add(Branch(matches, match_block, non_match_block, Branch.BOOL))
367
368 builder.activate_block(match_block)
369 builder.call_c(restore_exc_info_op, [builder.read(old_exc)], fn_info.fitem.line)
370 builder.add(Return(builder.none_object()))
371
372 builder.activate_block(non_match_block)
373 builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
374 builder.add(Unreachable())
375
376 builder.nonlocal_control.pop()
377
378 builder.activate_block(else_block)
379 builder.add(
380 RaiseStandardError(
381 RaiseStandardError.RUNTIME_ERROR,
382 "generator ignored GeneratorExit",
383 fn_info.fitem.line,
384 )
385 )
386 builder.add(Unreachable())
387
388
389 def add_await_to_generator_class(builder: IRBuilder, fn_info: FuncInfo) -> None:
390 """Generates the '__await__' method for a generator class."""
391 with builder.enter_method(fn_info.generator_class.ir, "__await__", object_rprimitive, fn_info):
392 builder.add(Return(builder.self()))
393
394
395 def setup_env_for_generator_class(builder: IRBuilder) -> None:
396 """Populates the environment for a generator class."""
397 fitem = builder.fn_info.fitem
398 cls = builder.fn_info.generator_class
399 self_target = builder.add_self_to_env(cls.ir)
400
401 # Add the type, value, and traceback variables to the environment.
402 exc_type = builder.add_local(Var("type"), object_rprimitive, is_arg=True)
403 exc_val = builder.add_local(Var("value"), object_rprimitive, is_arg=True)
404 exc_tb = builder.add_local(Var("traceback"), object_rprimitive, is_arg=True)
405 # TODO: Use the right type here instead of object?
406 exc_arg = builder.add_local(Var("arg"), object_rprimitive, is_arg=True)
407
408 # Parameter that can used to pass a pointer which can used instead of
409 # raising StopIteration(value). If the value is NULL, this won't be used.
410 stop_iter_value_arg = builder.add_local(
411 Var("stop_iter_ptr"), object_pointer_rprimitive, is_arg=True
412 )
413
414 cls.exc_regs = (exc_type, exc_val, exc_tb)
415 cls.send_arg_reg = exc_arg
416 cls.stop_iter_value_reg = stop_iter_value_arg
417
418 cls.self_reg = builder.read(self_target, fitem.line)
419 if builder.fn_info.can_merge_generator_and_env_classes():
420 cls.curr_env_reg = cls.self_reg
421 else:
422 cls.curr_env_reg = load_outer_env(builder, cls.self_reg, builder.symtables[-1])
423
424 # Define a variable representing the label to go to the next time
425 # the '__next__' function of the generator is called, and add it
426 # as an attribute to the environment class.
427 cls.next_label_target = builder.add_var_to_env_class(
428 Var(NEXT_LABEL_ATTR_NAME), int32_rprimitive, cls, reassign=False, always_defined=True
429 )
430
431 # Add arguments from the original generator function to the
432 # environment of the generator class.
433 add_args_to_env(
434 builder, local=False, base=cls, reassign=False, prefix=GENERATOR_ATTRIBUTE_PREFIX
435 )
436
437 # Set the next label register for the generator class.
438 cls.next_label_reg = builder.read(cls.next_label_target, fitem.line)