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