-
Notifications
You must be signed in to change notification settings - Fork 30
/
goto.py
288 lines (245 loc) · 9.41 KB
/
goto.py
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
import ast
import sys
import six
PY2 = sys.version_info[0] == 2
# We could use this funny little hack:
# background: http://stackoverflow.com/questions/6959360/goto-in-python
# code from here: http://code.activestate.com/recipes/576944-the-goto-decorator/
# by Carl Cerecke
# Licensed under the MIT License
class MissingLabelError(Exception):
"""'goto' without matching 'label'."""
pass
def goto(fn):
"""
A function decorator to add the goto command for a function.
Specify labels like so:
label .foo
Goto labels like so:
goto .foo
"""
import dis
import new
labels = {}
gotos = {}
globalName = None
index = 0
end = len(fn.func_code.co_code)
i = 0
# scan through the byte codes to find the labels and gotos
while i < end:
op = ord(fn.func_code.co_code[i])
i += 1
name = dis.opname[op]
if op > dis.HAVE_ARGUMENT:
b1 = ord(fn.func_code.co_code[i])
b2 = ord(fn.func_code.co_code[i+1])
num = b2 * 256 + b1
if name == 'LOAD_GLOBAL':
globalName = fn.func_code.co_names[num]
index = i - 1
i += 2
continue
if name == 'LOAD_ATTR':
if globalName == 'label':
labels[fn.func_code.co_names[num]] = index
elif globalName == 'goto':
gotos[fn.func_code.co_names[num]] = index
name = None
i += 2
# no-op the labels
ilist = list(fn.func_code.co_code)
for label,index in labels.items():
ilist[index:index+7] = [chr(dis.opmap['NOP'])]*7
# change gotos to jumps
for label,index in gotos.items():
if label not in labels:
raise MissingLabelError("Missing label: %s"%label)
target = labels[label] + 7 # skip NOPs
ilist[index] = chr(dis.opmap['JUMP_ABSOLUTE'])
ilist[index + 1] = chr(target & 255)
ilist[index + 2] = chr(target >> 8)
# create new function from existing function
c = fn.func_code
newcode = new.code(c.co_argcount,
c.co_nlocals,
c.co_stacksize,
c.co_flags,
''.join(ilist),
c.co_consts,
c.co_names,
c.co_varnames,
c.co_filename,
c.co_name,
c.co_firstlineno,
c.co_lnotab)
newfn = new.function(newcode,fn.func_globals)
return newfn
# Or, to avoid messing around with the bytecode, we can go the
# much more complicated route:
# - First, we flatten any Python AST into a series of statements,
# with even more goto's added for while/for loops, if's, etc.
# (We can avoid doing this for all sub-ASTs where there are no
# no goto-labels. The goal is to have all goto-labels at
# the top-level, not inside a sub-AST.)
# - Only conditional goto's can stay.
# - All Gotos and Goto-labels are marked somehow as special elements.
# So, we end up with sth like:
# x()
# y()
# <goto-label "a">
# z()
# <goto-stmnt "a">
# w()
# if v(): <goto-stmnt "a">
# q()
# Now, we can implement the goto-handling based on this flattened code:
# - Add a big endless loop around it. After the final statement,
# a break would leave the loop.
# - Before the loop, we add the statement `goto = None`.
# - The goto-labels will split the code into multiple part, where
# we add some `if goto is None:` before each part
# (excluding the goto-labels).
# - For the goto-labels itself, we add this code:
# `if goto == <goto-label>: goto = None`
# - For every goto-statement, we add this code:
# `goto = <goto-stmnt>; continue`
class GotoLabel:
def __init__(self, label):
self.label = label
class GotoStatement:
def __init__(self, label):
self.label = label
class _Flatten:
def __init__(self):
self.c = 1
def make_jump(self):
label = self.c
self.c += 1
return GotoStatement(label)
def flatten(self, body, breakJump=None):
"""
:type body: list[ast.AST]
:param breakJump: if we find some ast.Break in a while-loop, add this jump
:rtype: list[ast.AST]
"""
r = []
for s in body:
if isinstance(s, ast.If):
a = ast.UnaryOp()
a.op = ast.Not()
a.operand = s.test
goto_final_stmnt = self.make_jump()
if s.orelse:
goto_orelse_stmnt = self.make_jump()
r += [ast.If(test=a, body=[goto_orelse_stmnt], orelse=[])]
else:
goto_orelse_stmnt = None
r += [ast.If(test=a, body=[goto_final_stmnt], orelse=[])]
r += self.flatten(s.body, breakJump=breakJump)
if s.orelse:
r += [goto_final_stmnt]
r += [GotoLabel(goto_orelse_stmnt.label)]
r += self.flatten(s.orelse, breakJump=breakJump)
r += [GotoLabel(goto_final_stmnt.label)]
elif isinstance(s, ast.While):
if s.orelse: raise NotImplementedError
goto_repeat_stmnt = self.make_jump()
r += [GotoLabel(goto_repeat_stmnt.label)]
a = ast.UnaryOp()
a.op = ast.Not()
a.operand = s.test
goto_final_stmnt = self.make_jump()
r += [ast.If(test=a, body=[goto_final_stmnt], orelse=[])]
r += self.flatten(s.body, breakJump=goto_final_stmnt)
r += [goto_repeat_stmnt]
r += [GotoLabel(goto_final_stmnt.label)]
elif isinstance(s, ast.For):
raise NotImplementedError
elif isinstance(s, (ast.TryExcept, ast.TryFinally) if PY2 else ast.Try):
raise NotImplementedError
elif isinstance(s, ast.Break):
assert breakJump, "found break in unexpected scope"
r += [breakJump]
else:
r += [s]
return r
def _ast_for_value(v):
if isinstance(v, six.string_types): return ast.Str(s=v)
elif isinstance(v, int): return ast.Num(n=v)
else: raise NotImplementedError("type (%r) %r" % (type(v), v))
class _HandleGoto:
def __init__(self, gotoVarName):
self.gotoVarName = gotoVarName
def handle_goto_stmnt(self, stmnt):
assert isinstance(stmnt, GotoStatement)
a = ast.Assign()
a.targets = [ast.Name(id=self.gotoVarName, ctx=ast.Store())]
a.value = _ast_for_value(stmnt.label)
return [a, ast.Continue()]
def handle_goto_label(self, stmnt):
assert isinstance(stmnt, GotoLabel)
reset_ast = ast.Assign()
reset_ast.targets = [ast.Name(id=self.gotoVarName, ctx=ast.Store())]
reset_ast.value = ast.Name(id="None", ctx=ast.Load())
test_ast = ast.Compare()
test_ast.ops = [ast.Eq()]
test_ast.left = ast.Name(id=self.gotoVarName, ctx=ast.Store())
test_ast.comparators = [_ast_for_value(stmnt.label)]
return [ast.If(test=test_ast, body=[reset_ast], orelse=[])]
def handle_body(self, body):
"""
:type body: list[ast.AST]
:rtype: list[ast.AST]
"""
parts = [[]]
for s in body:
if isinstance(s, GotoLabel):
parts += [s, []]
else:
parts[-1].append(s)
r = []
for l in parts:
if not l: continue
if isinstance(l, GotoLabel):
r += self.handle_goto_label(l)
else:
sr = []
for s in l:
if isinstance(s, ast.If):
assert not s.orelse
assert len(s.body) == 1
assert isinstance(s.body[0], GotoStatement)
sr += [ast.If(test=s.test, orelse=[],
body=self.handle_goto_stmnt(s.body[0]))]
elif isinstance(s, (ast.While, ast.For)):
assert False, "not expected: %r" % s
elif isinstance(s, GotoStatement):
sr += self.handle_goto_stmnt(s)
else:
sr += [s]
test_ast = ast.Compare()
test_ast.ops = [ast.Is()]
test_ast.left = ast.Name(id=self.gotoVarName, ctx=ast.Store())
test_ast.comparators = [ast.Name(id="None", ctx=ast.Load())]
r += [ast.If(test=test_ast, body=sr, orelse=[])]
return r
def wrap_func_body(self, flat_body):
var_ast = ast.Assign()
var_ast.targets = [ast.Name(id=self.gotoVarName, ctx=ast.Store())]
var_ast.value = ast.Name(id="None", ctx=ast.Load())
main_loop_ast = ast.While(orelse=[])
main_loop_ast.test = ast.Name(id="True", ctx=ast.Load())
main_loop_ast.body = self.handle_body(flat_body)
main_loop_ast.body += [ast.Break()]
return [var_ast, main_loop_ast]
def transform_goto(f, gotoVarName):
assert isinstance(f, ast.FunctionDef)
flat_body = _Flatten().flatten(f.body)
new_body = _HandleGoto(gotoVarName).wrap_func_body(flat_body)
new_func_ast = ast.FunctionDef(
name=f.name,
args=f.args,
decorator_list=f.decorator_list,
body=new_body)
return new_func_ast