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.class_ir import ClassIR
12 from mypyc.ir.ops import (
13 ERR_NEVER,
14 NO_TRACEBACK_LINE_NO,
15 BasicBlock,
16 Branch,
17 Call,
18 Goto,
19 Integer,
20 Register,
21 Return,
22 SetMem,
23 Unreachable,
24 Value,
25 )
26 from mypyc.ir.rtypes import object_rprimitive
27 from mypyc.irbuild.targets import AssignmentTarget
28 from mypyc.primitives.exc_ops import restore_exc_info_op, set_stop_iteration_value
29
30 if TYPE_CHECKING:
31 from mypyc.irbuild.builder import IRBuilder
32
33
34 class NonlocalControl:
35 """ABC representing a stack frame of constructs that modify nonlocal control flow.
36
37 The nonlocal control flow constructs are break, continue, and
38 return, and their behavior is modified by a number of other
39 constructs. The most obvious is loop, which override where break
40 and continue jump to, but also `except` (which needs to clear
41 exc_info when left) and (eventually) finally blocks (which need to
42 ensure that the finally block is always executed when leaving the
43 try/except blocks).
44 """
45
46 @abstractmethod
47 def gen_break(self, builder: IRBuilder, line: int) -> None:
48 pass
49
50 @abstractmethod
51 def gen_continue(self, builder: IRBuilder, line: int) -> None:
52 pass
53
54 @abstractmethod
55 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
56 pass
57
58
59 class BaseNonlocalControl(NonlocalControl):
60 """Default nonlocal control outside any statements that affect it."""
61
62 def gen_break(self, builder: IRBuilder, line: int) -> None:
63 assert False, "break outside of loop"
64
65 def gen_continue(self, builder: IRBuilder, line: int) -> None:
66 assert False, "continue outside of loop"
67
68 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
69 builder.add(Return(value, line))
70
71
72 class LoopNonlocalControl(NonlocalControl):
73 """Nonlocal control within a loop."""
74
75 def __init__(
76 self, outer: NonlocalControl, continue_block: BasicBlock, break_block: BasicBlock
77 ) -> None:
78 self.outer = outer
79 self.continue_block = continue_block
80 self.break_block = break_block
81
82 def gen_break(self, builder: IRBuilder, line: int) -> None:
83 builder.add(Goto(self.break_block))
84
85 def gen_continue(self, builder: IRBuilder, line: int) -> None:
86 builder.add(Goto(self.continue_block))
87
88 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
89 self.outer.gen_return(builder, value, line)
90
91
92 class GeneratorNonlocalControl(BaseNonlocalControl):
93 """Default nonlocal control in a generator function outside statements."""
94
95 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
96 gen_generator_func_cleanup(builder, 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 def gen_class_clear_on_completion(builder: IRBuilder, obj: Value, cl: ClassIR, line: int) -> None:
136 call = Call(cl.clear_on_completion, [obj], line)
137 call.error_kind = ERR_NEVER
138 builder.add(call)
139
140
141 def gen_generator_func_cleanup(builder: IRBuilder, line: int) -> None:
142 """Clear references held by a completed generator or coroutine."""
143 cls = builder.fn_info.generator_class
144
145 # Assign an invalid next label number so that the next time __next__ is
146 # called, we jump to the case in which StopIteration is raised.
147 builder.assign(cls.next_label_target, Integer(-1), line)
148
149 gen_class_clear_on_completion(builder, cls.curr_env_reg, builder.fn_info.env_class, line)
150 if builder.fn_info.env_class is not cls.ir:
151 gen_class_clear_on_completion(builder, cls.self_reg, cls.ir, line)
152
153
154 class CleanupNonlocalControl(NonlocalControl):
155 """Abstract nonlocal control that runs some cleanup code."""
156
157 def __init__(self, outer: NonlocalControl) -> None:
158 self.outer = outer
159
160 @abstractmethod
161 def gen_cleanup(self, builder: IRBuilder, line: int) -> None: ...
162
163 def gen_break(self, builder: IRBuilder, line: int) -> None:
164 self.gen_cleanup(builder, line)
165 self.outer.gen_break(builder, line)
166
167 def gen_continue(self, builder: IRBuilder, line: int) -> None:
168 self.gen_cleanup(builder, line)
169 self.outer.gen_continue(builder, line)
170
171 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
172 self.gen_cleanup(builder, line)
173 self.outer.gen_return(builder, value, line)
174
175
176 class TryFinallyNonlocalControl(NonlocalControl):
177 """Nonlocal control within try/finally."""
178
179 def __init__(self, target: BasicBlock) -> None:
180 self.target = target
181 self.ret_reg: None | Register | AssignmentTarget = None
182
183 def gen_break(self, builder: IRBuilder, line: int) -> None:
184 builder.error("break inside try/finally block is unimplemented", line)
185
186 def gen_continue(self, builder: IRBuilder, line: int) -> None:
187 builder.error("continue inside try/finally block is unimplemented", line)
188
189 def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:
190 if self.ret_reg is None:
191 if builder.fn_info.is_generator:
192 self.ret_reg = builder.make_spill_target(builder.ret_types[-1])
193 else:
194 self.ret_reg = Register(builder.ret_types[-1])
195 # assert needed because of apparent mypy bug... it loses track of the union
196 # and infers the type as object
197 assert isinstance(self.ret_reg, (Register, AssignmentTarget)), self.ret_reg
198 builder.assign(self.ret_reg, value, line)
199
200 builder.add(Goto(self.target))
201
202
203 class ExceptNonlocalControl(CleanupNonlocalControl):
204 """Nonlocal control for except blocks.
205
206 Just makes sure that sys.exc_info always gets restored when we leave.
207 This is super annoying.
208 """
209
210 def __init__(self, outer: NonlocalControl, saved: Value | AssignmentTarget) -> None:
211 super().__init__(outer)
212 self.saved = saved
213
214 def gen_cleanup(self, builder: IRBuilder, line: int) -> None:
215 builder.call_c(restore_exc_info_op, [builder.read(self.saved, line)], line)
216
217
218 class FinallyNonlocalControl(CleanupNonlocalControl):
219 """Nonlocal control for finally blocks.
220
221 Just makes sure that sys.exc_info always gets restored when we
222 leave and the return register is decrefed if it isn't null.
223 """
224
225 def __init__(self, outer: NonlocalControl, saved: Value) -> None:
226 super().__init__(outer)
227 self.saved = saved
228
229 def gen_cleanup(self, builder: IRBuilder, line: int) -> None:
230 # Restore the old exc_info
231 target, cleanup = BasicBlock(), BasicBlock()
232 builder.add(Branch(self.saved, target, cleanup, Branch.IS_ERROR))
233 builder.activate_block(cleanup)
234 builder.call_c(restore_exc_info_op, [self.saved], line)
235 builder.goto_and_activate(target)