Debian Codegraph @

mypyc/irbuild/nonlocalcontrol.py

raw
1 """Helpers for dealing with nonlocal control such as 'break' and 'return'.
2
3 Model how these behave differently in different contexts.
4 """
5
6 from __future__ import annotations
7
8 from abc import abstractmethod
9 from typing import TYPE_CHECKING
10
11 from mypyc.ir.ops import (
12 NO_TRACEBACK_LINE_NO,
13 BasicBlock,
14 Branch,
15 Goto,
16 Integer,
17 Register,
18 Return,
19 SetMem,
20 Unreachable,
21 Value,
22 )
23 from mypyc.ir.rtypes import object_rprimitive
24 from mypyc.irbuild.targets import AssignmentTarget
25 from mypyc.primitives.exc_ops import restore_exc_info_op, set_stop_iteration_value
26
27 if TYPE_CHECKING:
28 from mypyc.irbuild.builder import IRBuilder
29
30
31 class NonlocalControl:
32 """ABC representing a stack frame of constructs that modify nonlocal control flow.
33
34 The nonlocal control flow constructs are break, continue, and
35 return, and their behavior is modified by a number of other
36 constructs. The most obvious is loop, which override where break
37 and continue jump to, but also `except` (which needs to clear
38 exc_info when left) and (eventually) finally blocks (which need to
39 ensure that the finally block is always executed when leaving the
40 try/except blocks).
41 """
42
43 @abstractmethod
44 def gen_break(self, builder: IRBuilder, line: int) -> None:
45 pass
46
47 @abstractmethod
48 def gen_continue(self, builder: IRBuilder, line: int) -> None:
49 pass
50
51 @abstractmethod
52 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
53 pass
54
55
56 class BaseNonlocalControl(NonlocalControl):
57 """Default nonlocal control outside any statements that affect it."""
58
59 def gen_break(self, builder: IRBuilder, line: int) -> None:
60 assert False, "break outside of loop"
61
62 def gen_continue(self, builder: IRBuilder, line: int) -> None:
63 assert False, "continue outside of loop"
64
65 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
66 builder.add(Return(value, line))
67
68
69 class LoopNonlocalControl(NonlocalControl):
70 """Nonlocal control within a loop."""
71
72 def __init__(
73 self, outer: NonlocalControl, continue_block: BasicBlock, break_block: BasicBlock
74 ) -> None:
75 self.outer = outer
76 self.continue_block = continue_block
77 self.break_block = break_block
78
79 def gen_break(self, builder: IRBuilder, line: int) -> None:
80 builder.add(Goto(self.break_block))
81
82 def gen_continue(self, builder: IRBuilder, line: int) -> None:
83 builder.add(Goto(self.continue_block))
84
85 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
86 self.outer.gen_return(builder, value, line)
87
88
89 class GeneratorNonlocalControl(BaseNonlocalControl):
90 """Default nonlocal control in a generator function outside statements."""
91
92 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
93 # Assign an invalid next label number so that the next time
94 # __next__ is called, we jump to the case in which
95 # StopIteration is raised.
96 builder.assign(builder.fn_info.generator_class.next_label_target, Integer(-1), line)
97
98 # Raise a StopIteration containing a field for the value that
99 # should be returned. Before doing so, create a new block
100 # without an error handler set so that the implicitly thrown
101 # StopIteration isn't caught by except blocks inside of the
102 # generator function.
103 builder.builder.push_error_handler(None)
104 builder.goto_and_activate(BasicBlock())
105
106 # Skip creating a traceback frame when we raise here, because
107 # we don't care about the traceback frame and it is kind of
108 # expensive since raising StopIteration is an extremely common
109 # case. Also we call a special internal function to set
110 # StopIteration instead of using RaiseStandardError because
111 # the obvious thing doesn't work if the value is a tuple
112 # (???).
113
114 true, false = BasicBlock(), BasicBlock()
115 stop_iter_reg = builder.fn_info.generator_class.stop_iter_value_reg
116 assert stop_iter_reg is not None
117
118 builder.add(Branch(stop_iter_reg, true, false, Branch.IS_ERROR))
119
120 builder.activate_block(true)
121 # The default/slow path is to raise a StopIteration exception with
122 # return value.
123 builder.call_c(set_stop_iteration_value, [value], NO_TRACEBACK_LINE_NO)
124 builder.add(Unreachable())
125 builder.builder.pop_error_handler()
126
127 builder.activate_block(false)
128 # The fast path is to store return value via caller-provided pointer
129 # instead of raising an exception. This can only be used when the
130 # caller is a native function.
131 builder.add(SetMem(object_rprimitive, stop_iter_reg, value))
132 builder.add(Return(Integer(0, object_rprimitive)))
133
134
135 class CleanupNonlocalControl(NonlocalControl):
136 """Abstract nonlocal control that runs some cleanup code."""
137
138 def __init__(self, outer: NonlocalControl) -> None:
139 self.outer = outer
140
141 @abstractmethod
142 def gen_cleanup(self, builder: IRBuilder, line: int) -> None: ...
143
144 def gen_break(self, builder: IRBuilder, line: int) -> None:
145 self.gen_cleanup(builder, line)
146 self.outer.gen_break(builder, line)
147
148 def gen_continue(self, builder: IRBuilder, line: int) -> None:
149 self.gen_cleanup(builder, line)
150 self.outer.gen_continue(builder, line)
151
152 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
153 self.gen_cleanup(builder, line)
154 self.outer.gen_return(builder, value, line)
155
156
157 class TryFinallyNonlocalControl(NonlocalControl):
158 """Nonlocal control within try/finally."""
159
160 def __init__(self, target: BasicBlock) -> None:
161 self.target = target
162 self.ret_reg: None | Register | AssignmentTarget = None
163
164 def gen_break(self, builder: IRBuilder, line: int) -> None:
165 builder.error("break inside try/finally block is unimplemented", line)
166
167 def gen_continue(self, builder: IRBuilder, line: int) -> None:
168 builder.error("continue inside try/finally block is unimplemented", line)
169
170 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
171 if self.ret_reg is None:
172 if builder.fn_info.is_generator:
173 self.ret_reg = builder.make_spill_target(builder.ret_types[-1])
174 else:
175 self.ret_reg = Register(builder.ret_types[-1])
176 # assert needed because of apparent mypy bug... it loses track of the union
177 # and infers the type as object
178 assert isinstance(self.ret_reg, (Register, AssignmentTarget)), self.ret_reg
179 builder.assign(self.ret_reg, value, line)
180
181 builder.add(Goto(self.target))
182
183
184 class ExceptNonlocalControl(CleanupNonlocalControl):
185 """Nonlocal control for except blocks.
186
187 Just makes sure that sys.exc_info always gets restored when we leave.
188 This is super annoying.
189 """
190
191 def __init__(self, outer: NonlocalControl, saved: Value | AssignmentTarget) -> None:
192 super().__init__(outer)
193 self.saved = saved
194
195 def gen_cleanup(self, builder: IRBuilder, line: int) -> None:
196 builder.call_c(restore_exc_info_op, [builder.read(self.saved, line)], line)
197
198
199 class FinallyNonlocalControl(CleanupNonlocalControl):
200 """Nonlocal control for finally blocks.
201
202 Just makes sure that sys.exc_info always gets restored when we
203 leave and the return register is decrefed if it isn't null.
204 """
205
206 def __init__(self, outer: NonlocalControl, saved: Value) -> None:
207 super().__init__(outer)
208 self.saved = saved
209
210 def gen_cleanup(self, builder: IRBuilder, line: int) -> None:
211 # Restore the old exc_info
212 target, cleanup = BasicBlock(), BasicBlock()
213 builder.add(Branch(self.saved, target, cleanup, Branch.IS_ERROR))
214 builder.activate_block(cleanup)
215 builder.call_c(restore_exc_info_op, [self.saved], line)
216 builder.goto_and_activate(target)