Debian Codegraph @

mypyc/irbuild/statement.py

raw
1 """Transform mypy statement ASTs to mypyc IR (Intermediate Representation).
2
3 The top-level AST transformation logic is implemented in mypyc.irbuild.visitor
4 and mypyc.irbuild.builder.
5
6 A few statements are transformed in mypyc.irbuild.function (yield, for example).
7 """
8
9 from __future__ import annotations
10
11 import importlib.util
12 from collections.abc import Callable, Sequence
13 from typing import Final
14
15 import mypy.nodes
16 from mypy.nodes import (
17 ARG_NAMED,
18 ARG_POS,
19 AssertStmt,
20 AssignmentStmt,
21 AwaitExpr,
22 Block,
23 BreakStmt,
24 ContinueStmt,
25 DelStmt,
26 Expression,
27 ExpressionStmt,
28 ForStmt,
29 IfStmt,
30 Import,
31 ImportAll,
32 ImportFrom,
33 IndexExpr,
34 ListExpr,
35 Lvalue,
36 MatchStmt,
37 NameExpr,
38 OperatorAssignmentStmt,
39 RaiseStmt,
40 ReturnStmt,
41 StarExpr,
42 StrExpr,
43 TempNode,
44 TryStmt,
45 TupleExpr,
46 TypeAliasStmt,
47 WhileStmt,
48 WithStmt,
49 YieldExpr,
50 YieldFromExpr,
51 )
52 from mypyc.common import TEMP_ATTR_NAME
53 from mypyc.ir.ops import (
54 ERR_NEVER,
55 NAMESPACE_MODULE,
56 NO_TRACEBACK_LINE_NO,
57 Assign,
58 BasicBlock,
59 Branch,
60 Call,
61 InitStatic,
62 Integer,
63 LoadAddress,
64 LoadErrorValue,
65 LoadLiteral,
66 LoadStatic,
67 MethodCall,
68 PrimitiveDescription,
69 RaiseStandardError,
70 Register,
71 Return,
72 TupleGet,
73 Unborrow,
74 Unreachable,
75 Value,
76 )
77 from mypyc.ir.rtypes import (
78 RInstance,
79 RTuple,
80 c_pyssize_t_rprimitive,
81 exc_rtuple,
82 is_tagged,
83 none_rprimitive,
84 object_pointer_rprimitive,
85 object_rprimitive,
86 )
87 from mypyc.irbuild.ast_helpers import is_borrow_friendly_expr, process_conditional
88 from mypyc.irbuild.builder import IRBuilder, create_type_params, int_borrow_friendly_op
89 from mypyc.irbuild.for_helpers import for_loop_helper
90 from mypyc.irbuild.generator import add_raise_exception_blocks_to_generator_class
91 from mypyc.irbuild.nonlocalcontrol import (
92 ExceptNonlocalControl,
93 FinallyNonlocalControl,
94 TryFinallyNonlocalControl,
95 )
96 from mypyc.irbuild.prepare import GENERATOR_HELPER_NAME
97 from mypyc.irbuild.specialize import apply_dunder_specialization
98 from mypyc.irbuild.targets import (
99 AssignmentTarget,
100 AssignmentTargetAttr,
101 AssignmentTargetIndex,
102 AssignmentTargetRegister,
103 AssignmentTargetTuple,
104 )
105 from mypyc.primitives.exc_ops import (
106 error_catch_op,
107 exc_matches_op,
108 get_exc_info_op,
109 get_exc_value_op,
110 keep_propagating_op,
111 no_err_occurred_op,
112 propagate_if_error_op,
113 raise_exception_op,
114 reraise_exception_op,
115 restore_exc_info_op,
116 )
117 from mypyc.primitives.generic_ops import iter_op, next_raw_op, py_delattr_op
118 from mypyc.primitives.misc_ops import (
119 check_stop_op,
120 coro_op,
121 get_native_attrs_op,
122 import_from_many_op,
123 import_many_op,
124 import_op,
125 send_op,
126 set_type_alias_compute_function_op,
127 type_op,
128 yield_from_except_op,
129 )
130
131 from .match import MatchVisitor
132
133 GenFunc = Callable[[], None]
134 ValueGenFunc = Callable[[], Value]
135
136
137 def transform_block(builder: IRBuilder, block: Block) -> None:
138 if not block.is_unreachable:
139 builder.block_reachable_stack.append(True)
140 for stmt in block.body:
141 builder.accept(stmt)
142 if not builder.block_reachable_stack[-1]:
143 # The rest of the block is unreachable, so skip it
144 break
145 builder.block_reachable_stack.pop()
146 # Raise a RuntimeError if we hit a non-empty unreachable block.
147 # Don't complain about empty unreachable blocks, since mypy inserts
148 # those after `if MYPY`.
149 elif block.body:
150 builder.add(
151 RaiseStandardError(
152 RaiseStandardError.RUNTIME_ERROR, "Reached allegedly unreachable code!", block.line
153 )
154 )
155 builder.add(Unreachable())
156
157
158 def transform_expression_stmt(builder: IRBuilder, stmt: ExpressionStmt) -> None:
159 if isinstance(stmt.expr, StrExpr):
160 # Docstring. Ignore
161 return
162 # ExpressionStmts do not need to be coerced like other Expressions, so we shouldn't
163 # call builder.accept here.
164 stmt.expr.accept(builder.visitor)
165 builder.flush_keep_alives(stmt.line)
166
167
168 def transform_return_stmt(builder: IRBuilder, stmt: ReturnStmt) -> None:
169 if stmt.expr:
170 retval = builder.accept(stmt.expr)
171 else:
172 retval = builder.builder.none()
173 retval = builder.coerce(retval, builder.ret_types[-1], stmt.line)
174 builder.nonlocal_control[-1].gen_return(builder, retval, stmt.line)
175
176
177 def check_unsupported_cls_assignment(builder: IRBuilder, stmt: AssignmentStmt) -> None:
178 fn = builder.fn_info
179 method_args = fn.fitem.arg_names
180 if fn.name != "__new__" or len(method_args) == 0:
181 return
182
183 ir = builder.get_current_class_ir()
184 if ir is None or ir.inherits_python or not ir.is_ext_class:
185 return
186
187 cls_arg = method_args[0]
188
189 def flatten(lvalues: list[Expression]) -> list[Expression]:
190 flat = []
191 for lvalue in lvalues:
192 if isinstance(lvalue, (TupleExpr, ListExpr)):
193 flat += flatten(lvalue.items)
194 else:
195 flat.append(lvalue)
196 return flat
197
198 lvalues = flatten(stmt.lvalues)
199
200 for lvalue in lvalues:
201 if isinstance(lvalue, NameExpr) and lvalue.name == cls_arg:
202 # Disallowed because it could break the transformation of object.__new__ calls
203 # inside __new__ methods.
204 builder.error(
205 f'Assignment to argument "{cls_arg}" in "__new__" method unsupported', stmt.line
206 )
207
208
209 def transform_assignment_stmt(builder: IRBuilder, stmt: AssignmentStmt) -> None:
210 lvalues = stmt.lvalues
211 assert lvalues
212 builder.disallow_class_assignments(lvalues, stmt.line)
213 check_unsupported_cls_assignment(builder, stmt)
214 first_lvalue = lvalues[0]
215 if stmt.type and isinstance(stmt.rvalue, TempNode):
216 # This is actually a variable annotation without initializer. Don't generate
217 # an assignment but we need to call get_assignment_target since it adds a
218 # name binding as a side effect.
219 builder.get_assignment_target(first_lvalue, stmt.line)
220 return
221
222 # Special case multiple assignments like 'x, y = e1, e2'.
223 if (
224 isinstance(first_lvalue, (TupleExpr, ListExpr))
225 and isinstance(stmt.rvalue, (TupleExpr, ListExpr))
226 and len(first_lvalue.items) == len(stmt.rvalue.items)
227 and all(is_simple_lvalue(item) for item in first_lvalue.items)
228 and len(lvalues) == 1
229 ):
230 temps = []
231 for right in stmt.rvalue.items:
232 rvalue_reg = builder.accept(right)
233 temp = Register(rvalue_reg.type)
234 builder.assign(temp, rvalue_reg, stmt.line)
235 temps.append(temp)
236 for left, temp in zip(first_lvalue.items, temps):
237 assignment_target = builder.get_assignment_target(left)
238 builder.assign(assignment_target, temp, stmt.line)
239 builder.flush_keep_alives(stmt.line)
240 return
241
242 line = stmt.rvalue.line
243 rvalue_reg = builder.accept(stmt.rvalue)
244
245 if builder.non_function_scope() and stmt.is_final_def:
246 builder.init_final_static(first_lvalue, rvalue_reg)
247
248 # Special-case multiple assignments like 'x, y = expr' to reduce refcount ops.
249 if (
250 isinstance(first_lvalue, (TupleExpr, ListExpr))
251 and isinstance(rvalue_reg.type, RTuple)
252 and len(rvalue_reg.type.types) == len(first_lvalue.items)
253 and len(lvalues) == 1
254 and all(is_simple_lvalue(item) for item in first_lvalue.items)
255 and any(t.is_refcounted for t in rvalue_reg.type.types)
256 ):
257 n = len(first_lvalue.items)
258 borrows = [builder.add(TupleGet(rvalue_reg, i, borrow=True)) for i in range(n)]
259 builder.builder.keep_alive([rvalue_reg], line, steal=True)
260 for lvalue_item, rvalue_item in zip(first_lvalue.items, borrows):
261 rvalue_item = builder.add(Unborrow(rvalue_item))
262 builder.assign(builder.get_assignment_target(lvalue_item), rvalue_item, line)
263 builder.flush_keep_alives(line)
264 return
265
266 for lvalue in lvalues:
267 # Check for __setitem__ dunder specialization before converting to assignment target
268 if isinstance(lvalue, IndexExpr):
269 specialized = apply_dunder_specialization(
270 builder, lvalue.base, [lvalue.index, stmt.rvalue], "__setitem__", lvalue
271 )
272 if specialized is not None:
273 builder.flush_keep_alives(lvalue.line)
274 continue
275
276 target = builder.get_assignment_target(lvalue)
277 builder.assign(target, rvalue_reg, line)
278 builder.flush_keep_alives(line)
279
280
281 def is_simple_lvalue(expr: Expression) -> bool:
282 return not isinstance(expr, (StarExpr, ListExpr, TupleExpr))
283
284
285 def transform_operator_assignment_stmt(builder: IRBuilder, stmt: OperatorAssignmentStmt) -> None:
286 """Operator assignment statement such as x += 1"""
287 builder.disallow_class_assignments([stmt.lvalue], stmt.line)
288 if (
289 is_tagged(builder.node_type(stmt.lvalue))
290 and is_tagged(builder.node_type(stmt.rvalue))
291 and stmt.op in int_borrow_friendly_op
292 ):
293 can_borrow = is_borrow_friendly_expr(builder, stmt.rvalue) and is_borrow_friendly_expr(
294 builder, stmt.lvalue
295 )
296 else:
297 can_borrow = False
298 target = builder.get_assignment_target(stmt.lvalue)
299 target_value = builder.read(target, stmt.line, can_borrow=can_borrow)
300 rreg = builder.accept(stmt.rvalue, can_borrow=can_borrow)
301 # the Python parser strips the '=' from operator assignment statements, so re-add it
302 op = stmt.op + "="
303 res = builder.binary_op(target_value, rreg, op, stmt.line)
304 # usually operator assignments are done in-place
305 # but when target doesn't support that we need to manually assign
306 builder.assign(target, res, res.line)
307 builder.flush_keep_alives(res.line)
308
309
310 def import_globals_id_and_name(module_id: str, as_name: str | None) -> tuple[str, str]:
311 """Compute names for updating the globals dict with the appropriate module.
312
313 * For 'import foo.bar as baz' we add 'foo.bar' with the name 'baz'
314 * For 'import foo.bar' we add 'foo' with the name 'foo'
315
316 Typically we then ignore these entries and access things directly
317 via the module static, but we will use the globals version for
318 modules that mypy couldn't find, since it doesn't analyze module
319 references from those properly."""
320 if as_name:
321 globals_id = module_id
322 globals_name = as_name
323 else:
324 globals_id = globals_name = module_id.split(".")[0]
325
326 return globals_id, globals_name
327
328
329 def transform_import(builder: IRBuilder, node: Import) -> None:
330 if node.is_mypy_only:
331 return
332
333 # Imports (not from imports!) are processed in an odd way so they can be
334 # table-driven and compact. Here's how it works:
335 #
336 # Import nodes are divided in groups (in the prebuild visitor). Each group
337 # consists of consecutive Import nodes:
338 #
339 # import mod <| group #1
340 # import mod2 |
341 #
342 # def foo() -> None:
343 # import mod3 <- group #2 (*)
344 #
345 # import mod4 <| group #3
346 # import mod5 |
347 #
348 # Every time we encounter the first import of a group, build IR to import
349 # all modules in the group. Native same-group imports are handled individually,
350 # while non-native imports use a table-driven helper for compactness.
351
352 if not node.is_top_level:
353 # (*) Unless the import is within a function. In that case, prioritize
354 # speed over codesize when generating IR.
355 group = [(mod_id, as_id, node.line) for mod_id, as_id in node.ids]
356 transform_imports_without_grouping(builder, group)
357 return
358
359 if node not in builder.module_import_groups:
360 return
361
362 group_nodes = builder.module_import_groups[node]
363 subgroups = split_import_group_to_python_and_native(builder, group_nodes)
364 for subgroup, is_native in subgroups:
365 if is_native:
366 transform_imports_without_grouping(builder, subgroup)
367 else:
368 transform_non_native_import_group(builder, subgroup)
369
370
371 def split_import_group_to_python_and_native(
372 builder: IRBuilder, group: list[Import]
373 ) -> list[tuple[list[tuple[str, str | None, int]], bool]]:
374 """Split imports into consecutive runs of native same-group and non-native imports."""
375 flat_list = []
376 for imp in group:
377 for mod_id, as_name in imp.ids:
378 flat_list.append(
379 (
380 mod_id,
381 as_name,
382 imp.line,
383 builder.is_native_module(mod_id) and builder.is_same_group_module(mod_id),
384 )
385 )
386 result = []
387 i = 0
388 while i < len(flat_list):
389 i0 = i
390 is_native = flat_list[i][3]
391 i += 1
392 while i < len(flat_list) and flat_list[i][3] == is_native:
393 i += 1
394 result.append(([t[:3] for t in flat_list[i0:i]], is_native))
395 return result
396
397
398 def transform_imports_without_grouping(
399 builder: IRBuilder, group: list[tuple[str, str | None, int]]
400 ) -> None:
401 globals = builder.load_globals_dict()
402 for mod_id, as_name, line in group:
403 builder.gen_import(mod_id, line)
404 globals_id, globals_name = import_globals_id_and_name(mod_id, as_name)
405 builder.gen_method_call(
406 globals,
407 "__setitem__",
408 [builder.load_str(globals_name), builder.get_module(globals_id, line)],
409 result_type=None,
410 line=line,
411 )
412
413
414 def transform_non_native_import_group(
415 builder: IRBuilder, group: list[tuple[str, str | None, int]]
416 ) -> None:
417 """Transform a group of import statements that target non-native modules."""
418 modules = []
419 static_ptrs = []
420 # To show the right line number on failure, we have to add the traceback
421 # entry within the helper function (which is admittedly ugly). To drive
422 # this, we need the line number corresponding to each module.
423 mod_lines = []
424 first_line = group[0][2] if group else NO_TRACEBACK_LINE_NO
425 for mod_id, as_name, line in group:
426 builder.imports[mod_id] = None
427 modules.append((mod_id, *import_globals_id_and_name(mod_id, as_name)))
428 mod_static = LoadStatic(object_rprimitive, mod_id, namespace=NAMESPACE_MODULE)
429 static_ptrs.append(builder.add(LoadAddress(object_pointer_rprimitive, mod_static)))
430 mod_lines.append(Integer(line, c_pyssize_t_rprimitive))
431
432 static_array_ptr = builder.builder.setup_rarray(
433 object_pointer_rprimitive, static_ptrs, first_line
434 )
435 import_line_ptr = builder.builder.setup_rarray(c_pyssize_t_rprimitive, mod_lines, first_line)
436 builder.call_c(
437 import_many_op,
438 [
439 builder.add(LoadLiteral(tuple(modules), object_rprimitive)),
440 static_array_ptr,
441 builder.load_globals_dict(),
442 builder.load_str(builder.module_path),
443 builder.load_str(builder.fn_info.name),
444 import_line_ptr,
445 ],
446 NO_TRACEBACK_LINE_NO,
447 )
448
449
450 def transform_import_from(builder: IRBuilder, node: ImportFrom) -> None:
451 if node.is_mypy_only:
452 return
453
454 module_state = builder.graph[builder.module_name]
455 if builder.module_path.endswith("__init__.py"):
456 module_package = builder.module_name
457 elif module_state.ancestors is not None and module_state.ancestors:
458 module_package = module_state.ancestors[0]
459 else:
460 module_package = ""
461
462 id = importlib.util.resolve_name("." * node.relative + node.id, module_package)
463 builder.imports[id] = None
464
465 names = [name for name, _ in node.names]
466 as_names = [as_name or name for name, as_name in node.names]
467
468 parent_is_native = builder.is_native_module(id) and builder.is_same_group_module(id)
469 transform_import_from_buckets(builder, id, names, as_names, node.line, parent_is_native)
470
471
472 # Import kind constants for classify_import_from.
473 IMPORT_NATIVE_SUBMODULE: Final = 0 # native same-group submodule (import directly)
474 IMPORT_NATIVE_ATTR: Final = 1 # attribute of a native module (getattr)
475 IMPORT_NON_NATIVE: Final = 2 # non-native or cross-group (use Python import system)
476
477
478 class ImportFromBucket:
479 def __init__(self, kind: int, names: list[str], as_names: list[str]) -> None:
480 self.kind = kind
481 self.names = names
482 self.as_names = as_names
483
484
485 def group_consecutive(items: list[tuple[int, str, str]]) -> list[ImportFromBucket]:
486 """Group consecutive items by kind (first element) into ImportFromBuckets.
487
488 Each item is a (kind, name, as_name) tuple.
489 """
490 result: list[ImportFromBucket] = []
491 i = 0
492 while i < len(items):
493 kind = items[i][0]
494 i0 = i
495 i += 1
496 while i < len(items) and items[i][0] == kind:
497 i += 1
498 result.append(
499 ImportFromBucket(kind, [t[1] for t in items[i0:i]], [t[2] for t in items[i0:i]])
500 )
501 return result
502
503
504 def classify_import_from(
505 builder: IRBuilder,
506 module_id: str,
507 names: list[str],
508 as_names: list[str],
509 parent_is_native: bool,
510 ) -> list[ImportFromBucket]:
511 """Classify each imported name and group consecutive same-kind names into buckets."""
512 flat_list = []
513 for name, as_name in zip(names, as_names):
514 submodule_id = f"{module_id}.{name}"
515 if builder.is_native_module(submodule_id) and builder.is_same_group_module(submodule_id):
516 kind = IMPORT_NATIVE_SUBMODULE
517 elif parent_is_native and submodule_id not in builder.graph:
518 kind = IMPORT_NATIVE_ATTR
519 else:
520 kind = IMPORT_NON_NATIVE
521 flat_list.append((kind, name, as_name))
522 return group_consecutive(flat_list)
523
524
525 def transform_import_from_buckets(
526 builder: IRBuilder,
527 module_id: str,
528 names: list[str],
529 as_names: list[str],
530 line: int,
531 parent_is_native: bool,
532 ) -> None:
533 """Handle 'from module_id import names' by dispatching each bucket to the right strategy."""
534 buckets = classify_import_from(builder, module_id, names, as_names, parent_is_native)
535 module = None
536 for bucket in buckets:
537 if bucket.kind == IMPORT_NATIVE_SUBMODULE:
538 group: list[tuple[str, str | None, int]] = [
539 (f"{module_id}.{name}", as_name, line)
540 for name, as_name in zip(bucket.names, bucket.as_names)
541 ]
542 transform_imports_without_grouping(builder, group)
543 elif bucket.kind == IMPORT_NATIVE_ATTR:
544 builder.gen_import(module_id, line)
545 names_literal = builder.add(LoadLiteral(tuple(bucket.names), object_rprimitive))
546 if bucket.as_names == bucket.names:
547 as_names_literal = names_literal
548 else:
549 as_names_literal = builder.add(
550 LoadLiteral(tuple(bucket.as_names), object_rprimitive)
551 )
552 builder.call_c(
553 get_native_attrs_op,
554 [
555 builder.load_str(module_id),
556 names_literal,
557 as_names_literal,
558 builder.load_globals_dict(),
559 ],
560 line,
561 )
562 else:
563 assert bucket.kind == IMPORT_NON_NATIVE
564 # Note that we miscompile import from inside of functions here,
565 # since that case *shouldn't* load everything into the globals dict.
566 # This probably doesn't matter much and the code runs basically right.
567 names_literal = builder.add(LoadLiteral(tuple(bucket.names), object_rprimitive))
568 if bucket.as_names == bucket.names:
569 as_names_literal = names_literal
570 else:
571 as_names_literal = builder.add(
572 LoadLiteral(tuple(bucket.as_names), object_rprimitive)
573 )
574 module = builder.call_c(
575 import_from_many_op,
576 [
577 builder.load_str(module_id),
578 names_literal,
579 as_names_literal,
580 builder.load_globals_dict(),
581 ],
582 line,
583 )
584 if module is not None:
585 builder.add(InitStatic(module, module_id, namespace=NAMESPACE_MODULE))
586
587
588 def transform_import_all(builder: IRBuilder, node: ImportAll) -> None:
589 if node.is_mypy_only:
590 return
591 builder.gen_import(node.id, node.line)
592
593
594 def transform_if_stmt(builder: IRBuilder, stmt: IfStmt) -> None:
595 if_body, next = BasicBlock(), BasicBlock()
596 else_body = BasicBlock() if stmt.else_body else next
597
598 # If statements are normalized
599 assert len(stmt.expr) == 1
600
601 process_conditional(builder, stmt.expr[0], if_body, else_body)
602 builder.activate_block(if_body)
603 builder.accept(stmt.body[0])
604 builder.goto(next)
605 if stmt.else_body:
606 builder.activate_block(else_body)
607 builder.accept(stmt.else_body)
608 builder.goto(next)
609 builder.activate_block(next)
610
611
612 def transform_while_stmt(builder: IRBuilder, s: WhileStmt) -> None:
613 body, next, top, else_block = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
614 normal_loop_exit = else_block if s.else_body is not None else next
615
616 builder.push_loop_stack(top, next)
617
618 # Split block so that we get a handle to the top of the loop.
619 builder.goto_and_activate(top)
620 process_conditional(builder, s.expr, body, normal_loop_exit)
621
622 builder.activate_block(body)
623 builder.accept(s.body)
624 # Add branch to the top at the end of the body.
625 builder.goto(top)
626
627 builder.pop_loop_stack()
628
629 if s.else_body is not None:
630 builder.activate_block(else_block)
631 builder.accept(s.else_body)
632 builder.goto(next)
633
634 builder.activate_block(next)
635
636
637 def transform_for_stmt(builder: IRBuilder, s: ForStmt) -> None:
638 def body() -> None:
639 builder.accept(s.body)
640
641 def else_block() -> None:
642 assert s.else_body is not None
643 builder.accept(s.else_body)
644
645 for_loop_helper(
646 builder, s.index, s.expr, body, else_block if s.else_body else None, s.is_async, s.line
647 )
648
649
650 def transform_break_stmt(builder: IRBuilder, node: BreakStmt) -> None:
651 builder.nonlocal_control[-1].gen_break(builder, node.line)
652
653
654 def transform_continue_stmt(builder: IRBuilder, node: ContinueStmt) -> None:
655 builder.nonlocal_control[-1].gen_continue(builder, node.line)
656
657
658 def transform_raise_stmt(builder: IRBuilder, s: RaiseStmt) -> None:
659 if s.expr is None:
660 builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
661 builder.add(Unreachable())
662 return
663
664 exc = builder.accept(s.expr)
665 builder.call_c(raise_exception_op, [exc], s.line)
666 builder.add(Unreachable())
667
668
669 def transform_try_except(
670 builder: IRBuilder,
671 body: GenFunc,
672 handlers: Sequence[tuple[tuple[ValueGenFunc, int] | None, Expression | None, GenFunc]],
673 else_body: GenFunc | None,
674 line: int,
675 ) -> None:
676 """Generalized try/except/else handling that takes functions to gen the bodies.
677
678 The point of this is to also be able to support with."""
679 assert handlers, "try needs except"
680
681 except_entry, exit_block, cleanup_block = BasicBlock(), BasicBlock(), BasicBlock()
682 double_except_block = BasicBlock()
683 # If there is an else block, jump there after the try, otherwise just leave
684 else_block = BasicBlock() if else_body else exit_block
685
686 # Compile the try block with an error handler
687 builder.builder.push_error_handler(except_entry)
688 builder.goto_and_activate(BasicBlock())
689 body()
690 builder.goto(else_block)
691 builder.builder.pop_error_handler()
692
693 # The error handler catches the error and then checks it
694 # against the except clauses. We compile the error handler
695 # itself with an error handler so that it can properly restore
696 # the *old* exc_info if an exception occurs.
697 # The exception chaining will be done automatically when the
698 # exception is raised, based on the exception in exc_info.
699 builder.builder.push_error_handler(double_except_block)
700 builder.activate_block(except_entry)
701 old_exc = builder.maybe_spill(builder.call_c(error_catch_op, [], line))
702 # Compile the except blocks with the nonlocal control flow overridden to clear exc_info
703 builder.nonlocal_control.append(ExceptNonlocalControl(builder.nonlocal_control[-1], old_exc))
704
705 # Process the bodies
706 for type, var, handler_body in handlers:
707 next_block = None
708 if type:
709 type_f, type_line = type
710 next_block, body_block = BasicBlock(), BasicBlock()
711 matches = builder.call_c(exc_matches_op, [type_f()], type_line)
712 builder.add(Branch(matches, body_block, next_block, Branch.BOOL, type_line))
713 builder.activate_block(body_block)
714 if var:
715 target = builder.get_assignment_target(var)
716 builder.assign(target, builder.call_c(get_exc_value_op, [], var.line), var.line)
717 handler_body()
718 builder.goto(cleanup_block)
719 if next_block:
720 builder.activate_block(next_block)
721
722 # Reraise the exception if needed
723 if next_block:
724 builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
725 builder.add(Unreachable())
726
727 builder.nonlocal_control.pop()
728 builder.builder.pop_error_handler()
729
730 # Cleanup for if we leave except through normal control flow:
731 # restore the saved exc_info information and continue propagating
732 # the exception if it exists.
733 builder.activate_block(cleanup_block)
734 builder.call_c(restore_exc_info_op, [builder.read(old_exc, line)], line)
735 builder.goto(exit_block)
736
737 # Cleanup for if we leave except through a raised exception:
738 # restore the saved exc_info information and continue propagating
739 # the exception.
740 builder.activate_block(double_except_block)
741 builder.call_c(restore_exc_info_op, [builder.read(old_exc, line)], line)
742 builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)
743 builder.add(Unreachable())
744
745 # If present, compile the else body in the obvious way
746 if else_body:
747 builder.activate_block(else_block)
748 else_body()
749 builder.goto(exit_block)
750
751 builder.activate_block(exit_block)
752
753
754 def transform_try_except_stmt(builder: IRBuilder, t: TryStmt) -> None:
755 def body() -> None:
756 builder.accept(t.body)
757
758 # Work around scoping woes
759 def make_handler(body: Block) -> GenFunc:
760 return lambda: builder.accept(body)
761
762 def make_entry(type: Expression) -> tuple[ValueGenFunc, int]:
763 return (lambda: builder.accept(type), type.line)
764
765 handlers = [
766 (make_entry(type) if type else None, var, make_handler(body))
767 for type, var, body in zip(t.types, t.vars, t.handlers)
768 ]
769
770 _else_body = t.else_body
771 else_body = (lambda: builder.accept(_else_body)) if _else_body else None
772 transform_try_except(builder, body, handlers, else_body, t.line)
773
774
775 def try_finally_try(
776 builder: IRBuilder,
777 err_handler: BasicBlock,
778 return_entry: BasicBlock,
779 main_entry: BasicBlock,
780 try_body: GenFunc,
781 ) -> Register | AssignmentTarget | None:
782 # Compile the try block with an error handler
783 control = TryFinallyNonlocalControl(return_entry)
784 builder.builder.push_error_handler(err_handler)
785
786 builder.nonlocal_control.append(control)
787 builder.goto_and_activate(BasicBlock())
788 try_body()
789 builder.goto(main_entry)
790 builder.nonlocal_control.pop()
791 builder.builder.pop_error_handler()
792
793 return control.ret_reg
794
795
796 def try_finally_entry_blocks(
797 builder: IRBuilder,
798 err_handler: BasicBlock,
799 return_entry: BasicBlock,
800 main_entry: BasicBlock,
801 finally_block: BasicBlock,
802 ret_reg: Register | AssignmentTarget | None,
803 ) -> Value:
804 line = builder.fn_info.fitem.line
805 old_exc = Register(exc_rtuple, line=line)
806
807 # Entry block for non-exceptional flow
808 builder.activate_block(main_entry)
809 if ret_reg:
810 builder.assign(ret_reg, builder.add(LoadErrorValue(builder.ret_types[-1], line)), line)
811 builder.goto(return_entry)
812
813 builder.activate_block(return_entry)
814 builder.add(Assign(old_exc, builder.add(LoadErrorValue(exc_rtuple, line)), line))
815 builder.goto(finally_block)
816
817 # Entry block for errors
818 builder.activate_block(err_handler)
819 if ret_reg:
820 builder.assign(ret_reg, builder.add(LoadErrorValue(builder.ret_types[-1], line)), line)
821 builder.add(Assign(old_exc, builder.call_c(error_catch_op, [], line), line))
822 builder.goto(finally_block)
823
824 return old_exc
825
826
827 def try_finally_body(
828 builder: IRBuilder, finally_block: BasicBlock, finally_body: GenFunc, old_exc: Value
829 ) -> tuple[BasicBlock, FinallyNonlocalControl]:
830 cleanup_block = BasicBlock()
831 # Compile the finally block with the nonlocal control flow overridden to restore exc_info
832 builder.builder.push_error_handler(cleanup_block)
833 finally_control = FinallyNonlocalControl(builder.nonlocal_control[-1], old_exc)
834 builder.nonlocal_control.append(finally_control)
835 builder.activate_block(finally_block)
836 finally_body()
837 builder.nonlocal_control.pop()
838
839 return cleanup_block, finally_control
840
841
842 def try_finally_resolve_control(
843 builder: IRBuilder,
844 cleanup_block: BasicBlock,
845 finally_control: FinallyNonlocalControl,
846 old_exc: Value,
847 ret_reg: Register | AssignmentTarget | None,
848 ) -> BasicBlock:
849 """Resolve the control flow out of a finally block.
850
851 This means returning if there was a return, propagating
852 exceptions, break/continue (soon), or just continuing on.
853 """
854 line = builder.fn_info.fitem.line
855 reraise, rest = BasicBlock(), BasicBlock()
856 builder.add(Branch(old_exc, rest, reraise, Branch.IS_ERROR, line))
857
858 # Reraise the exception if there was one
859 builder.activate_block(reraise)
860 builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
861 builder.add(Unreachable(line))
862 builder.builder.pop_error_handler()
863
864 # If there was a return, keep returning
865 if ret_reg:
866 builder.activate_block(rest)
867 return_block, rest = BasicBlock(), BasicBlock()
868 # For spill targets in try/finally, use nullable read to avoid AttributeError
869 if isinstance(ret_reg, AssignmentTargetAttr) and ret_reg.attr.startswith(TEMP_ATTR_NAME):
870 ret_val = builder.read_nullable_attr(ret_reg.obj, ret_reg.attr, line)
871 else:
872 ret_val = builder.read(ret_reg, line)
873 builder.add(Branch(ret_val, rest, return_block, Branch.IS_ERROR, line))
874
875 builder.activate_block(return_block)
876 builder.nonlocal_control[-1].gen_return(builder, ret_val, line)
877
878 # TODO: handle break/continue
879 builder.activate_block(rest)
880 out_block = BasicBlock()
881 builder.goto(out_block)
882
883 # If there was an exception, restore again
884 builder.activate_block(cleanup_block)
885 finally_control.gen_cleanup(builder, line)
886 builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)
887 builder.add(Unreachable())
888
889 return out_block
890
891
892 def transform_try_finally_stmt(
893 builder: IRBuilder, try_body: GenFunc, finally_body: GenFunc, line: int = -1
894 ) -> None:
895 """Generalized try/finally handling that takes functions to gen the bodies.
896
897 The point of this is to also be able to support with."""
898 # Finally is a big pain, because there are so many ways that
899 # exits can occur. We emit 10+ basic blocks for every finally!
900
901 err_handler, main_entry, return_entry, finally_block = (
902 BasicBlock(),
903 BasicBlock(),
904 BasicBlock(),
905 BasicBlock(),
906 )
907
908 # Compile the body of the try
909 ret_reg = try_finally_try(builder, err_handler, return_entry, main_entry, try_body)
910
911 # Set up the entry blocks for the finally statement
912 old_exc = try_finally_entry_blocks(
913 builder, err_handler, return_entry, main_entry, finally_block, ret_reg
914 )
915
916 # Compile the body of the finally
917 cleanup_block, finally_control = try_finally_body(
918 builder, finally_block, finally_body, old_exc
919 )
920
921 # Resolve the control flow out of the finally block
922 out_block = try_finally_resolve_control(
923 builder, cleanup_block, finally_control, old_exc, ret_reg
924 )
925
926 builder.activate_block(out_block)
927
928
929 def transform_try_finally_stmt_async(
930 builder: IRBuilder, try_body: GenFunc, finally_body: GenFunc, line: int = -1
931 ) -> None:
932 """Async-aware try/finally handling for when finally contains await.
933
934 This version uses a modified approach that preserves exceptions across await."""
935
936 # We need to handle returns properly, so we'll use TryFinallyNonlocalControl
937 # to track return values, similar to the regular try/finally implementation
938
939 err_handler, main_entry, return_entry, finally_entry = (
940 BasicBlock(),
941 BasicBlock(),
942 BasicBlock(),
943 BasicBlock(),
944 )
945
946 # Track if we're returning from the try block
947 control = TryFinallyNonlocalControl(return_entry)
948 builder.builder.push_error_handler(err_handler)
949 builder.nonlocal_control.append(control)
950 builder.goto_and_activate(BasicBlock())
951 try_body()
952 builder.goto(main_entry)
953 builder.nonlocal_control.pop()
954 builder.builder.pop_error_handler()
955 ret_reg = control.ret_reg
956
957 # Normal case - no exception or return
958 builder.activate_block(main_entry)
959 builder.goto(finally_entry)
960
961 # Return case
962 builder.activate_block(return_entry)
963 builder.goto(finally_entry)
964
965 # Exception case - need to catch to clear the error indicator
966 builder.activate_block(err_handler)
967 # Catch the error to clear Python's error indicator
968 builder.call_c(error_catch_op, [], line)
969 # We're not going to use old_exc since it won't survive await
970 # The exception is now in sys.exc_info()
971 builder.goto(finally_entry)
972
973 # Finally block
974 builder.activate_block(finally_entry)
975
976 # Execute finally body
977 finally_body()
978
979 # After finally, we need to handle exceptions carefully:
980 # 1. If finally raised a new exception, it's in the error indicator - let it propagate
981 # 2. If finally didn't raise, check if we need to reraise the original from sys.exc_info()
982 # 3. If there was a return, return that value
983 # 4. Otherwise, normal exit
984
985 # First, check if there's a current exception in the error indicator
986 # (this would be from the finally block)
987 no_current_exc = builder.call_c(no_err_occurred_op, [], line)
988 finally_raised = BasicBlock()
989 check_original = BasicBlock()
990 builder.add(Branch(no_current_exc, check_original, finally_raised, Branch.BOOL))
991
992 # Finally raised an exception - let it propagate naturally
993 builder.activate_block(finally_raised)
994 builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)
995 builder.add(Unreachable())
996
997 # No exception from finally, check if we need to handle return or original exception
998 builder.activate_block(check_original)
999
1000 # Check if we have a return value
1001 if ret_reg:
1002 return_block, check_old_exc = BasicBlock(), BasicBlock()
1003 builder.add(
1004 Branch(
1005 builder.read(ret_reg, line, allow_error_value=True),
1006 check_old_exc,
1007 return_block,
1008 Branch.IS_ERROR,
1009 )
1010 )
1011
1012 builder.activate_block(return_block)
1013 builder.nonlocal_control[-1].gen_return(builder, builder.read(ret_reg, line), line)
1014
1015 builder.activate_block(check_old_exc)
1016
1017 # Check if we need to reraise the original exception from sys.exc_info
1018 exc_info = builder.call_c(get_exc_info_op, [], line)
1019 exc_type = builder.add(TupleGet(exc_info, 0, line))
1020
1021 # Check if exc_type is None
1022 none_obj = builder.none_object()
1023 has_exc = builder.binary_op(exc_type, none_obj, "is not", line)
1024
1025 reraise_block, exit_block = BasicBlock(), BasicBlock()
1026 builder.add(Branch(has_exc, reraise_block, exit_block, Branch.BOOL))
1027
1028 # Reraise the original exception
1029 builder.activate_block(reraise_block)
1030 builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
1031 builder.add(Unreachable())
1032
1033 # Normal exit
1034 builder.activate_block(exit_block)
1035
1036
1037 # A simple visitor to detect await expressions
1038 class AwaitDetector(mypy.traverser.TraverserVisitor):
1039 def __init__(self) -> None:
1040 super().__init__()
1041 self.has_await = False
1042
1043 def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> None:
1044 self.has_await = True
1045 super().visit_await_expr(o)
1046
1047
1048 def transform_try_stmt(builder: IRBuilder, t: TryStmt) -> None:
1049 # Our compilation strategy for try/except/else/finally is to
1050 # treat try/except/else and try/finally as separate language
1051 # constructs that we compile separately. When we have a
1052 # try/except/else/finally, we treat the try/except/else as the
1053 # body of a try/finally block.
1054 if t.is_star:
1055 builder.error("Exception groups and except* cannot be compiled yet", t.line)
1056
1057 # Check if we're in an async function with a finally block that contains await
1058 use_async_version = False
1059 if t.finally_body and builder.fn_info.is_coroutine:
1060 detector = AwaitDetector()
1061 t.finally_body.accept(detector)
1062
1063 if detector.has_await:
1064 # Use the async version that handles exceptions correctly
1065 use_async_version = True
1066
1067 if t.finally_body:
1068
1069 def transform_try_body() -> None:
1070 if t.handlers:
1071 transform_try_except_stmt(builder, t)
1072 else:
1073 builder.accept(t.body)
1074
1075 body = t.finally_body
1076
1077 if use_async_version:
1078 transform_try_finally_stmt_async(
1079 builder, transform_try_body, lambda: builder.accept(body), t.line
1080 )
1081 else:
1082 transform_try_finally_stmt(
1083 builder, transform_try_body, lambda: builder.accept(body), t.line
1084 )
1085 else:
1086 transform_try_except_stmt(builder, t)
1087
1088
1089 def get_sys_exc_info(builder: IRBuilder) -> list[Value]:
1090 line = builder.fn_info.fitem.line
1091 exc_info = builder.call_c(get_exc_info_op, [], line)
1092 return [builder.add(TupleGet(exc_info, i, line)) for i in range(3)]
1093
1094
1095 def transform_with(
1096 builder: IRBuilder,
1097 expr: Expression,
1098 target: Lvalue | None,
1099 body: GenFunc,
1100 is_async: bool,
1101 line: int,
1102 ) -> None:
1103 # This is basically a straight transcription of the Python code in PEP 343.
1104 # I don't actually understand why a bunch of it is the way it is.
1105 # We could probably optimize the case where the manager is compiled by us,
1106 # but that is not our common case at all, so.
1107
1108 al = "a" if is_async else ""
1109
1110 mgr_v = builder.accept(expr)
1111 is_native = isinstance(mgr_v.type, RInstance)
1112 if is_native:
1113 value = builder.add(MethodCall(mgr_v, f"__{al}enter__", args=[], line=line))
1114 exit_ = None
1115 else:
1116 typ = builder.primitive_op(type_op, [mgr_v], line)
1117 exit_ = builder.maybe_spill(builder.py_get_attr(typ, f"__{al}exit__", line))
1118 value = builder.py_call(builder.py_get_attr(typ, f"__{al}enter__", line), [mgr_v], line)
1119
1120 mgr = builder.maybe_spill(mgr_v)
1121 exc = builder.maybe_spill_assignable(builder.true())
1122 if is_async:
1123 value = emit_await(builder, value, line)
1124
1125 def maybe_natively_call_exit(exc_info: bool) -> Value:
1126 if exc_info:
1127 args = get_sys_exc_info(builder)
1128 else:
1129 none = builder.none_object()
1130 args = [none, none, none]
1131
1132 if is_native:
1133 assert isinstance(mgr_v.type, RInstance), mgr_v.type
1134 exit_val = builder.gen_method_call(
1135 builder.read(mgr, line),
1136 f"__{al}exit__",
1137 arg_values=args,
1138 line=line,
1139 result_type=none_rprimitive,
1140 )
1141 else:
1142 assert exit_ is not None
1143 exit_val = builder.py_call(
1144 builder.read(exit_, line), [builder.read(mgr, line)] + args, line
1145 )
1146
1147 if is_async:
1148 return emit_await(builder, exit_val, line)
1149 else:
1150 return exit_val
1151
1152 def try_body() -> None:
1153 if target:
1154 builder.assign(builder.get_assignment_target(target), value, line)
1155 body()
1156
1157 def except_body() -> None:
1158 builder.assign(exc, builder.false(), line)
1159 out_block, reraise_block = BasicBlock(), BasicBlock()
1160 builder.add_bool_branch(maybe_natively_call_exit(exc_info=True), out_block, reraise_block)
1161 builder.activate_block(reraise_block)
1162 builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
1163 builder.add(Unreachable())
1164 builder.activate_block(out_block)
1165
1166 def finally_body() -> None:
1167 out_block, exit_block = BasicBlock(), BasicBlock()
1168 builder.add(Branch(builder.read(exc, line), exit_block, out_block, Branch.BOOL))
1169 builder.activate_block(exit_block)
1170
1171 maybe_natively_call_exit(exc_info=False)
1172 builder.goto_and_activate(out_block)
1173
1174 transform_try_finally_stmt(
1175 builder,
1176 lambda: transform_try_except(builder, try_body, [(None, None, except_body)], None, line),
1177 finally_body,
1178 line,
1179 )
1180
1181
1182 def transform_with_stmt(builder: IRBuilder, o: WithStmt) -> None:
1183 # Generate separate logic for each expr in it, left to right
1184 def generate(i: int) -> None:
1185 if i >= len(o.expr):
1186 builder.accept(o.body)
1187 else:
1188 transform_with(
1189 builder, o.expr[i], o.target[i], lambda: generate(i + 1), o.is_async, o.line
1190 )
1191
1192 generate(0)
1193
1194
1195 def transform_assert_stmt(builder: IRBuilder, a: AssertStmt) -> None:
1196 if builder.options.strip_asserts:
1197 return
1198 cond = builder.accept(a.expr)
1199 ok_block, error_block = BasicBlock(), BasicBlock()
1200 builder.add_bool_branch(cond, ok_block, error_block)
1201 builder.activate_block(error_block)
1202 if a.msg is None:
1203 # Special case (for simpler generated code)
1204 builder.add(RaiseStandardError(RaiseStandardError.ASSERTION_ERROR, None, a.line))
1205 elif isinstance(a.msg, StrExpr):
1206 # Another special case
1207 builder.add(RaiseStandardError(RaiseStandardError.ASSERTION_ERROR, a.msg.value, a.line))
1208 else:
1209 # The general case -- explicitly construct an exception instance
1210 message = builder.accept(a.msg)
1211 exc_type = builder.load_module_attr_by_fullname("builtins.AssertionError", a.line)
1212 exc = builder.py_call(exc_type, [message], a.line)
1213 builder.call_c(raise_exception_op, [exc], a.line)
1214 builder.add(Unreachable())
1215 builder.activate_block(ok_block)
1216
1217
1218 def transform_del_stmt(builder: IRBuilder, o: DelStmt) -> None:
1219 transform_del_item(builder, builder.get_assignment_target(o.expr), o.line)
1220
1221
1222 def transform_del_item(builder: IRBuilder, target: AssignmentTarget, line: int) -> None:
1223 if isinstance(target, AssignmentTargetIndex):
1224 builder.gen_method_call(
1225 target.base, "__delitem__", [target.index], result_type=None, line=line
1226 )
1227 elif isinstance(target, AssignmentTargetAttr):
1228 if isinstance(target.obj_type, RInstance):
1229 cl = target.obj_type.class_ir
1230 if not cl.is_deletable(target.attr):
1231 builder.error(f'"{target.attr}" cannot be deleted', line)
1232 builder.note(
1233 'Using "__deletable__ = '
1234 + '[\'<attr>\']" in the class body enables "del obj.<attr>"',
1235 line,
1236 )
1237 key = builder.load_str(target.attr)
1238 builder.primitive_op(py_delattr_op, [target.obj, key], line)
1239 elif isinstance(target, AssignmentTargetRegister):
1240 # Delete a local by assigning an error value to it, which will
1241 # prompt the insertion of uninit checks.
1242 builder.add(
1243 Assign(target.register, builder.add(LoadErrorValue(target.type, undefines=True)))
1244 )
1245 elif isinstance(target, AssignmentTargetTuple):
1246 for subtarget in target.items:
1247 transform_del_item(builder, subtarget, line)
1248
1249
1250 # yield/yield from/await
1251
1252 # These are really expressions, not statements... but they depend on try/except/finally
1253
1254
1255 def emit_yield(builder: IRBuilder, val: Value, line: int) -> Value:
1256 retval = builder.coerce(val, builder.ret_types[-1], line)
1257
1258 cls = builder.fn_info.generator_class
1259 # Create a new block for the instructions immediately following the yield expression, and
1260 # set the next label so that the next time '__next__' is called on the generator object,
1261 # the function continues at the new block.
1262 next_block = BasicBlock()
1263 next_label = len(cls.continuation_blocks)
1264 cls.continuation_blocks.append(next_block)
1265 builder.assign(cls.next_label_target, Integer(next_label), line)
1266 builder.add(Return(retval, yield_target=next_block))
1267 builder.activate_block(next_block)
1268
1269 add_raise_exception_blocks_to_generator_class(builder, line)
1270
1271 assert cls.send_arg_reg is not None
1272 return cls.send_arg_reg
1273
1274
1275 def emit_yield_from_or_await(
1276 builder: IRBuilder, val: Value, line: int, *, is_await: bool
1277 ) -> Value:
1278 # This is basically an implementation of the code in PEP 380.
1279
1280 # TODO: do we want to use the right types here?
1281 result = Register(object_rprimitive, line=line)
1282 to_yield_reg = Register(object_rprimitive, line=line)
1283 received_reg = Register(object_rprimitive, line=line)
1284
1285 helper_method = GENERATOR_HELPER_NAME
1286 if (
1287 isinstance(val, (Call, MethodCall))
1288 and isinstance(val.type, RInstance)
1289 and val.type.class_ir.has_method(helper_method)
1290 ):
1291 # This is a generated native generator class, and we can use a fast path.
1292 # This allows two optimizations:
1293 # 1) No need to call CPy_GetCoro() or iter() since for native generators
1294 # it just returns the generator object (implemented here).
1295 # 2) Instead of calling next(), call generator helper method directly,
1296 # since next() just calls __next__ which calls the helper method.
1297 iter_val: Value = val
1298 else:
1299 get_op = coro_op if is_await else iter_op
1300 if isinstance(get_op, PrimitiveDescription):
1301 iter_val = builder.primitive_op(get_op, [val], line)
1302 else:
1303 iter_val = builder.call_c(get_op, [val], line)
1304
1305 iter_reg = builder.maybe_spill_assignable(iter_val)
1306
1307 stop_block, main_block, done_block = BasicBlock(), BasicBlock(), BasicBlock()
1308
1309 if isinstance(iter_reg.type, RInstance) and iter_reg.type.class_ir.has_method(helper_method):
1310 # Second fast path optimization: call helper directly (see also comment above).
1311 #
1312 # Calling a generated generator, so avoid raising StopIteration by passing
1313 # an extra PyObject ** argument to helper where the stop iteration value is stored.
1314 fast_path = True
1315 obj = builder.read(iter_reg, line)
1316 nn = builder.none_object()
1317 stop_iter_val = Register(object_rprimitive)
1318 err = builder.add(LoadErrorValue(object_rprimitive, undefines=True))
1319 builder.assign(stop_iter_val, err, line)
1320 ptr = builder.add(LoadAddress(object_pointer_rprimitive, stop_iter_val))
1321 m = MethodCall(obj, helper_method, [nn, nn, nn, nn, ptr], line)
1322 # Generators have custom error handling, so disable normal error handling.
1323 m.error_kind = ERR_NEVER
1324 _y_init = builder.add(m)
1325 else:
1326 fast_path = False
1327 _y_init = builder.call_c(next_raw_op, [builder.read(iter_reg, line)], line)
1328
1329 builder.add(Branch(_y_init, stop_block, main_block, Branch.IS_ERROR))
1330
1331 builder.activate_block(stop_block)
1332 if fast_path:
1333 builder.primitive_op(propagate_if_error_op, [stop_iter_val], line)
1334 builder.assign(result, stop_iter_val, line)
1335 else:
1336 # Try extracting a return value from a StopIteration and return it.
1337 # If it wasn't, this reraises the exception.
1338 builder.assign(result, builder.call_c(check_stop_op, [], line), line)
1339 # Clear the spilled iterator/coroutine so that it will be freed.
1340 # Otherwise, the freeing of the spilled register would likely be delayed.
1341 err = builder.add(LoadErrorValue(iter_reg.type))
1342 builder.assign(iter_reg, err, line)
1343 builder.goto(done_block)
1344
1345 builder.activate_block(main_block)
1346 builder.assign(to_yield_reg, _y_init, line)
1347
1348 # OK Now the main loop!
1349 loop_block = BasicBlock()
1350 builder.goto_and_activate(loop_block)
1351
1352 def try_body() -> None:
1353 builder.assign(
1354 received_reg, emit_yield(builder, builder.read(to_yield_reg, line), line), line
1355 )
1356
1357 def except_body() -> None:
1358 # The body of the except is all implemented in a C function to
1359 # reduce how much code we need to generate. It returns a value
1360 # indicating whether to break or yield (or raise an exception).
1361 val = Register(object_rprimitive)
1362 val_address = builder.add(LoadAddress(object_pointer_rprimitive, val))
1363 to_stop = builder.call_c(
1364 yield_from_except_op, [builder.read(iter_reg, line), val_address], line
1365 )
1366
1367 ok, stop = BasicBlock(), BasicBlock()
1368 builder.add(Branch(to_stop, stop, ok, Branch.BOOL))
1369
1370 # The exception got swallowed. Continue, yielding the returned value
1371 builder.activate_block(ok)
1372 builder.assign(to_yield_reg, val, line)
1373 builder.nonlocal_control[-1].gen_continue(builder, line)
1374
1375 # The exception was a StopIteration. Stop iterating.
1376 builder.activate_block(stop)
1377 builder.assign(result, val, line)
1378 builder.nonlocal_control[-1].gen_break(builder, line)
1379
1380 def else_body() -> None:
1381 # Do a next() or a .send(). It will return NULL on exception
1382 # but it won't automatically propagate.
1383 _y = builder.call_c(
1384 send_op, [builder.read(iter_reg, line), builder.read(received_reg, line)], line
1385 )
1386 ok, stop = BasicBlock(), BasicBlock()
1387 builder.add(Branch(_y, stop, ok, Branch.IS_ERROR))
1388
1389 # Everything's fine. Yield it.
1390 builder.activate_block(ok)
1391 builder.assign(to_yield_reg, _y, line)
1392 builder.nonlocal_control[-1].gen_continue(builder, line)
1393
1394 # Try extracting a return value from a StopIteration and return it.
1395 # If it wasn't, this rereaises the exception.
1396 builder.activate_block(stop)
1397 builder.assign(result, builder.call_c(check_stop_op, [], line), line)
1398 builder.nonlocal_control[-1].gen_break(builder, line)
1399
1400 builder.push_loop_stack(loop_block, done_block)
1401 transform_try_except(builder, try_body, [(None, None, except_body)], else_body, line)
1402 builder.pop_loop_stack()
1403
1404 builder.goto_and_activate(done_block)
1405 return builder.read(result, line)
1406
1407
1408 def emit_await(builder: IRBuilder, val: Value, line: int) -> Value:
1409 return emit_yield_from_or_await(builder, val, line, is_await=True)
1410
1411
1412 def transform_yield_expr(builder: IRBuilder, expr: YieldExpr) -> Value:
1413 if builder.fn_info.is_coroutine:
1414 builder.error("async generators are unimplemented", expr.line)
1415
1416 if expr.expr:
1417 retval = builder.accept(expr.expr)
1418 else:
1419 retval = builder.builder.none()
1420 return emit_yield(builder, retval, expr.line)
1421
1422
1423 def transform_yield_from_expr(builder: IRBuilder, o: YieldFromExpr) -> Value:
1424 return emit_yield_from_or_await(builder, builder.accept(o.expr), o.line, is_await=False)
1425
1426
1427 def transform_await_expr(builder: IRBuilder, o: AwaitExpr) -> Value:
1428 return emit_yield_from_or_await(builder, builder.accept(o.expr), o.line, is_await=True)
1429
1430
1431 def transform_match_stmt(builder: IRBuilder, m: MatchStmt) -> None:
1432 m.accept(MatchVisitor(builder, m))
1433
1434
1435 def transform_type_alias_stmt(builder: IRBuilder, s: TypeAliasStmt) -> None:
1436 line = s.line
1437 # Use "_typing" to avoid importing "typing", as the latter can be expensive.
1438 # "_typing" includes everything we need here.
1439 mod = builder.call_c(import_op, [builder.load_str("_typing")], line)
1440 type_params = create_type_params(builder, mod, s.type_args, s.line)
1441
1442 type_alias_type = builder.py_get_attr(mod, "TypeAliasType", line)
1443 args = [builder.load_str(s.name.name), builder.none()]
1444 arg_names: list[str | None] = [None, None]
1445 arg_kinds = [ARG_POS, ARG_POS]
1446 if s.type_args:
1447 args.append(builder.new_tuple(type_params, line))
1448 arg_names.append("type_params")
1449 arg_kinds.append(ARG_NAMED)
1450 alias = builder.py_call(type_alias_type, args, line, arg_names=arg_names, arg_kinds=arg_kinds)
1451
1452 # Use primitive to set function used to lazily compute type alias type value.
1453 # The value needs to be lazily computed to match Python runtime behavior, but
1454 # Python public APIs don't support this, so we use a C primitive.
1455 compute_fn = s.value.accept(builder.visitor)
1456 builder.builder.primitive_op(set_type_alias_compute_function_op, [alias, compute_fn], line)
1457
1458 target = builder.get_assignment_target(s.name)
1459 builder.assign(target, alias, line)