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