-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathstatement.py
More file actions
1588 lines (1312 loc) · 57.9 KB
/
statement.py
File metadata and controls
1588 lines (1312 loc) · 57.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Transform mypy statement ASTs to mypyc IR (Intermediate Representation).
The top-level AST transformation logic is implemented in mypyc.irbuild.visitor
and mypyc.irbuild.builder.
A few statements are transformed in mypyc.irbuild.function (yield, for example).
"""
from __future__ import annotations
import importlib.util
from collections.abc import Callable, Sequence
import mypy.nodes
from mypy.nodes import (
ARG_NAMED,
ARG_POS,
AssertStmt,
AssignmentStmt,
AwaitExpr,
Block,
BreakStmt,
ContinueStmt,
DelStmt,
Expression,
ExpressionStmt,
ForStmt,
IfStmt,
Import,
ImportAll,
ImportFrom,
IndexExpr,
ListExpr,
Lvalue,
MatchStmt,
NameExpr,
OperatorAssignmentStmt,
RaiseStmt,
ReturnStmt,
StarExpr,
StrExpr,
TempNode,
TryStmt,
TupleExpr,
TypeAliasStmt,
WhileStmt,
WithStmt,
YieldExpr,
YieldFromExpr,
)
from mypyc.common import TEMP_ATTR_NAME
from mypyc.ir.ops import (
ERR_NEVER,
NAMESPACE_MODULE,
NO_TRACEBACK_LINE_NO,
Assign,
BasicBlock,
Branch,
Call,
ComparisonOp,
InitStatic,
Integer,
LoadAddress,
LoadErrorValue,
LoadLiteral,
LoadStatic,
MethodCall,
PrimitiveDescription,
RaiseStandardError,
Register,
Return,
TupleGet,
Unborrow,
Unreachable,
Value,
)
from mypyc.ir.rtypes import (
RInstance,
RTuple,
c_pyssize_t_rprimitive,
exc_rtuple,
is_tagged,
none_rprimitive,
object_pointer_rprimitive,
object_rprimitive,
pointer_rprimitive,
)
from mypyc.irbuild.ast_helpers import is_borrow_friendly_expr, process_conditional
from mypyc.irbuild.builder import IRBuilder, create_type_params, int_borrow_friendly_op
from mypyc.irbuild.for_helpers import for_loop_helper
from mypyc.irbuild.generator import add_raise_exception_blocks_to_generator_class
from mypyc.irbuild.nonlocalcontrol import (
ExceptNonlocalControl,
FinallyNonlocalControl,
TryFinallyNonlocalControl,
)
from mypyc.irbuild.prepare import GENERATOR_HELPER_NAME
from mypyc.irbuild.specialize import apply_dunder_specialization
from mypyc.irbuild.targets import (
AssignmentTarget,
AssignmentTargetAttr,
AssignmentTargetIndex,
AssignmentTargetRegister,
AssignmentTargetTuple,
)
from mypyc.primitives.exc_ops import (
err_occurred_op,
error_catch_op,
error_clear_op,
exc_matches_op,
get_exc_info_op,
get_exc_value_op,
keep_propagating_op,
no_err_occurred_op,
propagate_if_error_op,
raise_exception_op,
raise_exception_with_tb_op,
reraise_exception_op,
restore_exc_info_op,
)
from mypyc.primitives.generic_ops import iter_op, next_raw_op, py_delattr_op, py_setattr_op
from mypyc.primitives.misc_ops import (
check_stop_op,
coro_op,
import_from_many_op,
import_many_op,
import_op,
send_op,
set_type_alias_compute_function_op,
type_op,
yield_from_except_op,
)
from .match import MatchVisitor
GenFunc = Callable[[], None]
ValueGenFunc = Callable[[], Value]
def transform_block(builder: IRBuilder, block: Block) -> None:
if not block.is_unreachable:
builder.block_reachable_stack.append(True)
for stmt in block.body:
builder.accept(stmt)
if not builder.block_reachable_stack[-1]:
# The rest of the block is unreachable, so skip it
break
builder.block_reachable_stack.pop()
# Raise a RuntimeError if we hit a non-empty unreachable block.
# Don't complain about empty unreachable blocks, since mypy inserts
# those after `if MYPY`.
elif block.body:
builder.add(
RaiseStandardError(
RaiseStandardError.RUNTIME_ERROR, "Reached allegedly unreachable code!", block.line
)
)
builder.add(Unreachable())
def transform_expression_stmt(builder: IRBuilder, stmt: ExpressionStmt) -> None:
if isinstance(stmt.expr, StrExpr):
# Docstring. Ignore
return
# ExpressionStmts do not need to be coerced like other Expressions, so we shouldn't
# call builder.accept here.
stmt.expr.accept(builder.visitor)
builder.flush_keep_alives()
def transform_return_stmt(builder: IRBuilder, stmt: ReturnStmt) -> None:
if stmt.expr:
retval = builder.accept(stmt.expr)
else:
retval = builder.builder.none()
retval = builder.coerce(retval, builder.ret_types[-1], stmt.line)
builder.nonlocal_control[-1].gen_return(builder, retval, stmt.line)
def check_unsupported_cls_assignment(builder: IRBuilder, stmt: AssignmentStmt) -> None:
fn = builder.fn_info
method_args = fn.fitem.arg_names
if fn.name != "__new__" or len(method_args) == 0:
return
ir = builder.get_current_class_ir()
if ir is None or ir.inherits_python or not ir.is_ext_class:
return
cls_arg = method_args[0]
def flatten(lvalues: list[Expression]) -> list[Expression]:
flat = []
for lvalue in lvalues:
if isinstance(lvalue, (TupleExpr, ListExpr)):
flat += flatten(lvalue.items)
else:
flat.append(lvalue)
return flat
lvalues = flatten(stmt.lvalues)
for lvalue in lvalues:
if isinstance(lvalue, NameExpr) and lvalue.name == cls_arg:
# Disallowed because it could break the transformation of object.__new__ calls
# inside __new__ methods.
builder.error(
f'Assignment to argument "{cls_arg}" in "__new__" method unsupported', stmt.line
)
def transform_assignment_stmt(builder: IRBuilder, stmt: AssignmentStmt) -> None:
lvalues = stmt.lvalues
assert lvalues
builder.disallow_class_assignments(lvalues, stmt.line)
check_unsupported_cls_assignment(builder, stmt)
first_lvalue = lvalues[0]
if stmt.type and isinstance(stmt.rvalue, TempNode):
# This is actually a variable annotation without initializer. Don't generate
# an assignment but we need to call get_assignment_target since it adds a
# name binding as a side effect.
builder.get_assignment_target(first_lvalue, stmt.line)
return
# Special case multiple assignments like 'x, y = e1, e2'.
if (
isinstance(first_lvalue, (TupleExpr, ListExpr))
and isinstance(stmt.rvalue, (TupleExpr, ListExpr))
and len(first_lvalue.items) == len(stmt.rvalue.items)
and all(is_simple_lvalue(item) for item in first_lvalue.items)
and len(lvalues) == 1
):
temps = []
for right in stmt.rvalue.items:
rvalue_reg = builder.accept(right)
temp = Register(rvalue_reg.type)
builder.assign(temp, rvalue_reg, stmt.line)
temps.append(temp)
for left, temp in zip(first_lvalue.items, temps):
assignment_target = builder.get_assignment_target(left)
builder.assign(assignment_target, temp, stmt.line)
builder.flush_keep_alives()
return
line = stmt.rvalue.line
rvalue_reg = builder.accept(stmt.rvalue)
if builder.non_function_scope() and stmt.is_final_def:
builder.init_final_static(first_lvalue, rvalue_reg)
# Special-case multiple assignments like 'x, y = expr' to reduce refcount ops.
if (
isinstance(first_lvalue, (TupleExpr, ListExpr))
and isinstance(rvalue_reg.type, RTuple)
and len(rvalue_reg.type.types) == len(first_lvalue.items)
and len(lvalues) == 1
and all(is_simple_lvalue(item) for item in first_lvalue.items)
and any(t.is_refcounted for t in rvalue_reg.type.types)
):
n = len(first_lvalue.items)
borrows = [builder.add(TupleGet(rvalue_reg, i, borrow=True)) for i in range(n)]
builder.builder.keep_alive([rvalue_reg], steal=True)
for lvalue_item, rvalue_item in zip(first_lvalue.items, borrows):
rvalue_item = builder.add(Unborrow(rvalue_item))
builder.assign(builder.get_assignment_target(lvalue_item), rvalue_item, line)
builder.flush_keep_alives()
return
for lvalue in lvalues:
# Check for __setitem__ dunder specialization before converting to assignment target
if isinstance(lvalue, IndexExpr):
specialized = apply_dunder_specialization(
builder, lvalue.base, [lvalue.index, stmt.rvalue], "__setitem__", lvalue
)
if specialized is not None:
builder.flush_keep_alives()
continue
target = builder.get_assignment_target(lvalue)
builder.assign(target, rvalue_reg, line)
builder.flush_keep_alives()
def is_simple_lvalue(expr: Expression) -> bool:
return not isinstance(expr, (StarExpr, ListExpr, TupleExpr))
def transform_operator_assignment_stmt(builder: IRBuilder, stmt: OperatorAssignmentStmt) -> None:
"""Operator assignment statement such as x += 1"""
builder.disallow_class_assignments([stmt.lvalue], stmt.line)
if (
is_tagged(builder.node_type(stmt.lvalue))
and is_tagged(builder.node_type(stmt.rvalue))
and stmt.op in int_borrow_friendly_op
):
can_borrow = is_borrow_friendly_expr(builder, stmt.rvalue) and is_borrow_friendly_expr(
builder, stmt.lvalue
)
else:
can_borrow = False
target = builder.get_assignment_target(stmt.lvalue)
target_value = builder.read(target, stmt.line, can_borrow=can_borrow)
rreg = builder.accept(stmt.rvalue, can_borrow=can_borrow)
# the Python parser strips the '=' from operator assignment statements, so re-add it
op = stmt.op + "="
res = builder.binary_op(target_value, rreg, op, stmt.line)
# usually operator assignments are done in-place
# but when target doesn't support that we need to manually assign
builder.assign(target, res, res.line)
builder.flush_keep_alives()
def import_globals_id_and_name(module_id: str, as_name: str | None) -> tuple[str, str]:
"""Compute names for updating the globals dict with the appropriate module.
* For 'import foo.bar as baz' we add 'foo.bar' with the name 'baz'
* For 'import foo.bar' we add 'foo' with the name 'foo'
Typically we then ignore these entries and access things directly
via the module static, but we will use the globals version for
modules that mypy couldn't find, since it doesn't analyze module
references from those properly."""
if as_name:
globals_id = module_id
globals_name = as_name
else:
globals_id = globals_name = module_id.split(".")[0]
return globals_id, globals_name
def transform_import(builder: IRBuilder, node: Import) -> None:
if node.is_mypy_only:
return
# Imports (not from imports!) are processed in an odd way so they can be
# table-driven and compact. Here's how it works:
#
# Import nodes are divided in groups (in the prebuild visitor). Each group
# consists of consecutive Import nodes:
#
# import mod <| group #1
# import mod2 |
#
# def foo() -> None:
# import mod3 <- group #2 (*)
#
# import mod4 <| group #3
# import mod5 |
#
# Every time we encounter the first import of a group, build IR to call a
# helper function that will perform all of the group's imports in one go.
if not node.is_top_level:
# (*) Unless the import is within a function. In that case, prioritize
# speed over codesize when generating IR.
globals = builder.load_globals_dict()
for mod_id, as_name in node.ids:
builder.gen_import(mod_id, node.line)
globals_id, globals_name = import_globals_id_and_name(mod_id, as_name)
builder.gen_method_call(
globals,
"__setitem__",
[builder.load_str(globals_name), builder.get_module(globals_id, node.line)],
result_type=None,
line=node.line,
)
return
if node not in builder.module_import_groups:
return
modules = []
static_ptrs = []
# To show the right line number on failure, we have to add the traceback
# entry within the helper function (which is admittedly ugly). To drive
# this, we need the line number corresponding to each module.
mod_lines = []
for import_node in builder.module_import_groups[node]:
for mod_id, as_name in import_node.ids:
builder.imports[mod_id] = None
modules.append((mod_id, *import_globals_id_and_name(mod_id, as_name)))
mod_static = LoadStatic(object_rprimitive, mod_id, namespace=NAMESPACE_MODULE)
static_ptrs.append(builder.add(LoadAddress(object_pointer_rprimitive, mod_static)))
mod_lines.append(Integer(import_node.line, c_pyssize_t_rprimitive))
static_array_ptr = builder.builder.setup_rarray(object_pointer_rprimitive, static_ptrs)
import_line_ptr = builder.builder.setup_rarray(c_pyssize_t_rprimitive, mod_lines)
builder.call_c(
import_many_op,
[
builder.add(LoadLiteral(tuple(modules), object_rprimitive)),
static_array_ptr,
builder.load_globals_dict(),
builder.load_str(builder.module_path),
builder.load_str(builder.fn_info.name),
import_line_ptr,
],
NO_TRACEBACK_LINE_NO,
)
def transform_import_from(builder: IRBuilder, node: ImportFrom) -> None:
if node.is_mypy_only:
return
module_state = builder.graph[builder.module_name]
if builder.module_path.endswith("__init__.py"):
module_package = builder.module_name
elif module_state.ancestors is not None and module_state.ancestors:
module_package = module_state.ancestors[0]
else:
module_package = ""
id = importlib.util.resolve_name("." * node.relative + node.id, module_package)
builder.imports[id] = None
names = [name for name, _ in node.names]
as_names = [as_name or name for name, as_name in node.names]
names_literal = builder.add(LoadLiteral(tuple(names), object_rprimitive))
if as_names == names:
# Reuse names tuple to reduce verbosity.
as_names_literal = names_literal
else:
as_names_literal = builder.add(LoadLiteral(tuple(as_names), object_rprimitive))
# Note that we miscompile import from inside of functions here,
# since that case *shouldn't* load everything into the globals dict.
# This probably doesn't matter much and the code runs basically right.
module = builder.call_c(
import_from_many_op,
[builder.load_str(id), names_literal, as_names_literal, builder.load_globals_dict()],
node.line,
)
builder.add(InitStatic(module, id, namespace=NAMESPACE_MODULE))
def transform_import_all(builder: IRBuilder, node: ImportAll) -> None:
if node.is_mypy_only:
return
builder.gen_import(node.id, node.line)
def transform_if_stmt(builder: IRBuilder, stmt: IfStmt) -> None:
if_body, next = BasicBlock(), BasicBlock()
else_body = BasicBlock() if stmt.else_body else next
# If statements are normalized
assert len(stmt.expr) == 1
process_conditional(builder, stmt.expr[0], if_body, else_body)
builder.activate_block(if_body)
builder.accept(stmt.body[0])
builder.goto(next)
if stmt.else_body:
builder.activate_block(else_body)
builder.accept(stmt.else_body)
builder.goto(next)
builder.activate_block(next)
def transform_while_stmt(builder: IRBuilder, s: WhileStmt) -> None:
body, next, top, else_block = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
normal_loop_exit = else_block if s.else_body is not None else next
builder.push_loop_stack(top, next)
# Split block so that we get a handle to the top of the loop.
builder.goto_and_activate(top)
process_conditional(builder, s.expr, body, normal_loop_exit)
builder.activate_block(body)
builder.accept(s.body)
# Add branch to the top at the end of the body.
builder.goto(top)
builder.pop_loop_stack()
if s.else_body is not None:
builder.activate_block(else_block)
builder.accept(s.else_body)
builder.goto(next)
builder.activate_block(next)
def transform_for_stmt(builder: IRBuilder, s: ForStmt) -> None:
def body() -> None:
builder.accept(s.body)
def else_block() -> None:
assert s.else_body is not None
builder.accept(s.else_body)
for_loop_helper(
builder, s.index, s.expr, body, else_block if s.else_body else None, s.is_async, s.line
)
def transform_break_stmt(builder: IRBuilder, node: BreakStmt) -> None:
builder.nonlocal_control[-1].gen_break(builder, node.line)
def transform_continue_stmt(builder: IRBuilder, node: ContinueStmt) -> None:
builder.nonlocal_control[-1].gen_continue(builder, node.line)
def transform_raise_stmt(builder: IRBuilder, s: RaiseStmt) -> None:
if s.expr is None:
builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
return
exc = builder.accept(s.expr)
builder.call_c(raise_exception_op, [exc], s.line)
builder.add(Unreachable())
def transform_try_except(
builder: IRBuilder,
body: GenFunc,
handlers: Sequence[tuple[tuple[ValueGenFunc, int] | None, Expression | None, GenFunc]],
else_body: GenFunc | None,
line: int,
) -> None:
"""Generalized try/except/else handling that takes functions to gen the bodies.
The point of this is to also be able to support with."""
assert handlers, "try needs except"
except_entry, exit_block, cleanup_block = BasicBlock(), BasicBlock(), BasicBlock()
double_except_block = BasicBlock()
# If there is an else block, jump there after the try, otherwise just leave
else_block = BasicBlock() if else_body else exit_block
# Compile the try block with an error handler
builder.builder.push_error_handler(except_entry)
builder.goto_and_activate(BasicBlock())
body()
builder.goto(else_block)
builder.builder.pop_error_handler()
# The error handler catches the error and then checks it
# against the except clauses. We compile the error handler
# itself with an error handler so that it can properly restore
# the *old* exc_info if an exception occurs.
# The exception chaining will be done automatically when the
# exception is raised, based on the exception in exc_info.
builder.builder.push_error_handler(double_except_block)
builder.activate_block(except_entry)
old_exc = builder.maybe_spill(builder.call_c(error_catch_op, [], line))
# Compile the except blocks with the nonlocal control flow overridden to clear exc_info
builder.nonlocal_control.append(ExceptNonlocalControl(builder.nonlocal_control[-1], old_exc))
# Process the bodies
for type, var, handler_body in handlers:
next_block = None
if type:
type_f, type_line = type
next_block, body_block = BasicBlock(), BasicBlock()
matches = builder.call_c(exc_matches_op, [type_f()], type_line)
builder.add(Branch(matches, body_block, next_block, Branch.BOOL))
builder.activate_block(body_block)
if var:
target = builder.get_assignment_target(var)
builder.assign(target, builder.call_c(get_exc_value_op, [], var.line), var.line)
handler_body()
builder.goto(cleanup_block)
if next_block:
builder.activate_block(next_block)
# Reraise the exception if needed
if next_block:
builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
builder.nonlocal_control.pop()
builder.builder.pop_error_handler()
# Cleanup for if we leave except through normal control flow:
# restore the saved exc_info information and continue propagating
# the exception if it exists.
builder.activate_block(cleanup_block)
builder.call_c(restore_exc_info_op, [builder.read(old_exc)], line)
builder.goto(exit_block)
# Cleanup for if we leave except through a raised exception:
# restore the saved exc_info information and continue propagating
# the exception.
builder.activate_block(double_except_block)
builder.call_c(restore_exc_info_op, [builder.read(old_exc)], line)
builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
# If present, compile the else body in the obvious way
if else_body:
builder.activate_block(else_block)
else_body()
builder.goto(exit_block)
builder.activate_block(exit_block)
def transform_try_except_stmt(builder: IRBuilder, t: TryStmt) -> None:
def body() -> None:
builder.accept(t.body)
# Work around scoping woes
def make_handler(body: Block) -> GenFunc:
return lambda: builder.accept(body)
def make_entry(type: Expression) -> tuple[ValueGenFunc, int]:
return (lambda: builder.accept(type), type.line)
handlers = [
(make_entry(type) if type else None, var, make_handler(body))
for type, var, body in zip(t.types, t.vars, t.handlers)
]
_else_body = t.else_body
else_body = (lambda: builder.accept(_else_body)) if _else_body else None
transform_try_except(builder, body, handlers, else_body, t.line)
def try_finally_try(
builder: IRBuilder,
err_handler: BasicBlock,
return_entry: BasicBlock,
main_entry: BasicBlock,
try_body: GenFunc,
) -> Register | AssignmentTarget | None:
# Compile the try block with an error handler
control = TryFinallyNonlocalControl(return_entry)
builder.builder.push_error_handler(err_handler)
builder.nonlocal_control.append(control)
builder.goto_and_activate(BasicBlock())
try_body()
builder.goto(main_entry)
builder.nonlocal_control.pop()
builder.builder.pop_error_handler()
return control.ret_reg
def try_finally_entry_blocks(
builder: IRBuilder,
err_handler: BasicBlock,
return_entry: BasicBlock,
main_entry: BasicBlock,
finally_block: BasicBlock,
ret_reg: Register | AssignmentTarget | None,
) -> Value:
old_exc = Register(exc_rtuple)
# Entry block for non-exceptional flow
builder.activate_block(main_entry)
if ret_reg:
builder.assign(ret_reg, builder.add(LoadErrorValue(builder.ret_types[-1])), -1)
builder.goto(return_entry)
builder.activate_block(return_entry)
builder.add(Assign(old_exc, builder.add(LoadErrorValue(exc_rtuple))))
builder.goto(finally_block)
# Entry block for errors
builder.activate_block(err_handler)
if ret_reg:
builder.assign(ret_reg, builder.add(LoadErrorValue(builder.ret_types[-1])), -1)
builder.add(Assign(old_exc, builder.call_c(error_catch_op, [], -1)))
builder.goto(finally_block)
return old_exc
def try_finally_body(
builder: IRBuilder, finally_block: BasicBlock, finally_body: GenFunc, old_exc: Value
) -> tuple[BasicBlock, FinallyNonlocalControl]:
cleanup_block = BasicBlock()
# Compile the finally block with the nonlocal control flow overridden to restore exc_info
builder.builder.push_error_handler(cleanup_block)
finally_control = FinallyNonlocalControl(builder.nonlocal_control[-1], old_exc)
builder.nonlocal_control.append(finally_control)
builder.activate_block(finally_block)
finally_body()
builder.nonlocal_control.pop()
return cleanup_block, finally_control
def try_finally_resolve_control(
builder: IRBuilder,
cleanup_block: BasicBlock,
finally_control: FinallyNonlocalControl,
old_exc: Value,
ret_reg: Register | AssignmentTarget | None,
) -> BasicBlock:
"""Resolve the control flow out of a finally block.
This means returning if there was a return, propagating
exceptions, break/continue (soon), or just continuing on.
"""
reraise, rest = BasicBlock(), BasicBlock()
builder.add(Branch(old_exc, rest, reraise, Branch.IS_ERROR))
# Reraise the exception if there was one
builder.activate_block(reraise)
builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
builder.builder.pop_error_handler()
# If there was a return, keep returning
if ret_reg:
builder.activate_block(rest)
return_block, rest = BasicBlock(), BasicBlock()
# For spill targets in try/finally, use nullable read to avoid AttributeError
if isinstance(ret_reg, AssignmentTargetAttr) and ret_reg.attr.startswith(TEMP_ATTR_NAME):
ret_val = builder.read_nullable_attr(ret_reg.obj, ret_reg.attr, -1)
else:
ret_val = builder.read(ret_reg)
builder.add(Branch(ret_val, rest, return_block, Branch.IS_ERROR))
builder.activate_block(return_block)
builder.nonlocal_control[-1].gen_return(builder, ret_val, -1)
# TODO: handle break/continue
builder.activate_block(rest)
out_block = BasicBlock()
builder.goto(out_block)
# If there was an exception, restore again
builder.activate_block(cleanup_block)
finally_control.gen_cleanup(builder, -1)
builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
return out_block
def transform_try_finally_stmt(
builder: IRBuilder, try_body: GenFunc, finally_body: GenFunc, line: int = -1
) -> None:
"""Generalized try/finally handling that takes functions to gen the bodies.
The point of this is to also be able to support with."""
# Finally is a big pain, because there are so many ways that
# exits can occur. We emit 10+ basic blocks for every finally!
err_handler, main_entry, return_entry, finally_block = (
BasicBlock(),
BasicBlock(),
BasicBlock(),
BasicBlock(),
)
# Compile the body of the try
ret_reg = try_finally_try(builder, err_handler, return_entry, main_entry, try_body)
# Set up the entry blocks for the finally statement
old_exc = try_finally_entry_blocks(
builder, err_handler, return_entry, main_entry, finally_block, ret_reg
)
# Compile the body of the finally
cleanup_block, finally_control = try_finally_body(
builder, finally_block, finally_body, old_exc
)
# Resolve the control flow out of the finally block
out_block = try_finally_resolve_control(
builder, cleanup_block, finally_control, old_exc, ret_reg
)
builder.activate_block(out_block)
def transform_try_finally_stmt_async(
builder: IRBuilder, try_body: GenFunc, finally_body: GenFunc, line: int = -1
) -> None:
"""Async-aware try/finally handling for when finally contains await.
This version uses a modified approach that preserves exceptions across await."""
# We need to handle returns properly, so we'll use TryFinallyNonlocalControl
# to track return values, similar to the regular try/finally implementation
err_handler, main_entry, return_entry, finally_entry = (
BasicBlock(),
BasicBlock(),
BasicBlock(),
BasicBlock(),
)
# Track if we're returning from the try block
control = TryFinallyNonlocalControl(return_entry)
builder.builder.push_error_handler(err_handler)
builder.nonlocal_control.append(control)
builder.goto_and_activate(BasicBlock())
try_body()
builder.goto(main_entry)
builder.nonlocal_control.pop()
builder.builder.pop_error_handler()
ret_reg = control.ret_reg
# Normal case - no exception or return
builder.activate_block(main_entry)
builder.goto(finally_entry)
# Return case
builder.activate_block(return_entry)
builder.goto(finally_entry)
# Exception case - need to catch to clear the error indicator
builder.activate_block(err_handler)
# Catch the error to clear Python's error indicator
builder.call_c(error_catch_op, [], line)
# We're not going to use old_exc since it won't survive await
# The exception is now in sys.exc_info()
builder.goto(finally_entry)
# Finally block
builder.activate_block(finally_entry)
# Execute finally body
finally_body()
# After finally, we need to handle exceptions carefully:
# 1. If finally raised a new exception, it's in the error indicator - let it propagate
# 2. If finally didn't raise, check if we need to reraise the original from sys.exc_info()
# 3. If there was a return, return that value
# 4. Otherwise, normal exit
# First, check if there's a current exception in the error indicator
# (this would be from the finally block)
no_current_exc = builder.call_c(no_err_occurred_op, [], line)
finally_raised = BasicBlock()
check_original = BasicBlock()
builder.add(Branch(no_current_exc, check_original, finally_raised, Branch.BOOL))
# Finally raised an exception - let it propagate naturally
builder.activate_block(finally_raised)
builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
# No exception from finally, check if we need to handle return or original exception
builder.activate_block(check_original)
# Check if we have a return value
if ret_reg:
return_block, check_old_exc = BasicBlock(), BasicBlock()
builder.add(
Branch(
builder.read(ret_reg, allow_error_value=True),
check_old_exc,
return_block,
Branch.IS_ERROR,
)
)
builder.activate_block(return_block)
builder.nonlocal_control[-1].gen_return(builder, builder.read(ret_reg), -1)
builder.activate_block(check_old_exc)
# Check if we need to reraise the original exception from sys.exc_info
exc_info = builder.call_c(get_exc_info_op, [], line)
exc_type = builder.add(TupleGet(exc_info, 0, line))
# Check if exc_type is None
none_obj = builder.none_object()
has_exc = builder.binary_op(exc_type, none_obj, "is not", line)
reraise_block, exit_block = BasicBlock(), BasicBlock()
builder.add(Branch(has_exc, reraise_block, exit_block, Branch.BOOL))
# Reraise the original exception
builder.activate_block(reraise_block)
builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
# Normal exit
builder.activate_block(exit_block)
# A simple visitor to detect await expressions
class AwaitDetector(mypy.traverser.TraverserVisitor):
def __init__(self) -> None:
super().__init__()
self.has_await = False
def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> None:
self.has_await = True
super().visit_await_expr(o)
def transform_try_stmt(builder: IRBuilder, t: TryStmt) -> None:
# Our compilation strategy for try/except/else/finally is to
# treat try/except/else and try/finally as separate language
# constructs that we compile separately. When we have a
# try/except/else/finally, we treat the try/except/else as the
# body of a try/finally block.
if t.is_star:
builder.error("Exception groups and except* cannot be compiled yet", t.line)
# Check if we're in an async function with a finally block that contains await
use_async_version = False
if t.finally_body and builder.fn_info.is_coroutine:
detector = AwaitDetector()
t.finally_body.accept(detector)
if detector.has_await:
# Use the async version that handles exceptions correctly
use_async_version = True
if t.finally_body:
def transform_try_body() -> None:
if t.handlers:
transform_try_except_stmt(builder, t)
else:
builder.accept(t.body)
body = t.finally_body
if use_async_version:
transform_try_finally_stmt_async(
builder, transform_try_body, lambda: builder.accept(body), t.line
)
else:
transform_try_finally_stmt(
builder, transform_try_body, lambda: builder.accept(body), t.line
)
else:
transform_try_except_stmt(builder, t)
def get_sys_exc_info(builder: IRBuilder) -> list[Value]:
exc_info = builder.call_c(get_exc_info_op, [], -1)
return [builder.add(TupleGet(exc_info, i, -1)) for i in range(3)]
def transform_with(
builder: IRBuilder,
expr: Expression,
target: Lvalue | None,
body: GenFunc,
is_async: bool,
line: int,
) -> None:
if (
not is_async
and isinstance(expr, mypy.nodes.CallExpr)
and isinstance(expr.callee, mypy.nodes.RefExpr)
and isinstance(dec := expr.callee.node, mypy.nodes.Decorator)
and len(dec.decorators) == 1
and isinstance(dec1 := dec.decorators[0], mypy.nodes.RefExpr)
and dec1.node
and dec1.node.fullname == "contextlib.contextmanager"
):
return _transform_with_contextmanager(builder, expr, target, body, line)
# This is basically a straight transcription of the Python code in PEP 343.
# I don't actually understand why a bunch of it is the way it is.
# We could probably optimize the case where the manager is compiled by us,
# but that is not our common case at all, so.
al = "a" if is_async else ""
mgr_v = builder.accept(expr)
is_native = isinstance(mgr_v.type, RInstance)
if is_native:
value = builder.add(MethodCall(mgr_v, f"__{al}enter__", args=[], line=line))
exit_ = None
else:
typ = builder.primitive_op(type_op, [mgr_v], line)
exit_ = builder.maybe_spill(builder.py_get_attr(typ, f"__{al}exit__", line))
value = builder.py_call(builder.py_get_attr(typ, f"__{al}enter__", line), [mgr_v], line)
mgr = builder.maybe_spill(mgr_v)
exc = builder.maybe_spill_assignable(builder.true())
if is_async:
value = emit_await(builder, value, line)
def maybe_natively_call_exit(exc_info: bool) -> Value:
if exc_info:
args = get_sys_exc_info(builder)
else:
none = builder.none_object()
args = [none, none, none]
if is_native:
assert isinstance(mgr_v.type, RInstance), mgr_v.type
exit_val = builder.gen_method_call(
builder.read(mgr),
f"__{al}exit__",
arg_values=args,
line=line,
result_type=none_rprimitive,
)
else:
assert exit_ is not None