-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbelt.py
334 lines (274 loc) · 8.99 KB
/
belt.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
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
import operator as op
from rpython.rlib import streamio
from rpython.rlib import jit, debug, objectmodel, unroll
from rpython.rlib import rstring
BELT_LEN = 16
class Done(Exception):
def __init__(self, vals):
self.values = vals
class Instruction(object):
def __init__(self):
raise Exception("Abstract base class")
def interpret(self, pc, belt, stack):
raise Exception("Abstract base class")
def tostring(self):
return str(self)
class Copy(Instruction):
_immutable_fields_ = ["value"]
def __init__(self, val):
assert 0 <= val < BELT_LEN
self.value = val
def interpret(self, pc, belt, stack):
belt.put(belt.get(self.value))
return pc + 1, stack, False
def tostring(self):
return "COPY %d" % self.value
class Const(Instruction):
_immutable_fields_ = ["value"]
def __init__(self, val):
self.value = val
def interpret(self, pc, belt, stack):
belt.put(self.value)
return pc + 1, stack, False
def tostring(self):
return "CONST %d" % self.value
class Call(Instruction):
_immutable_fields_ = ["destination", "args[*]", "targets"]
def __init__(self, destination, args):
self.destination = destination
self.args = [i for i in reversed(args)]
self.targets = {}
@jit.unroll_safe
def interpret(self, pc, belt, stack):
target = jit.promote(belt.get(self.destination))
stack = ActivationRecord(pc + 1, belt, stack)
vals = [belt.get(i) for i in self.args]
belt.reset()
for v in vals:
belt.put(v)
return target, stack, target < pc
def tostring(self):
args = " ".join(["B%d" % i for i in reversed(self.args)])
return "CALL B%d %s" % (self.destination, args)
class Jump(Instruction):
_immutable_fields_ = ["destination"]
def __init__(self, destination):
self.destination = destination
def interpret(self, pc, belt, stack):
target = jit.promote(belt.get(self.destination))
return target, stack, target < pc
def tostring(self):
return "JUMP B%d" % self.destination
class Return(Instruction):
_immutable_fields_ = ["results[*]"]
def __init__(self, results):
self.results = [i for i in reversed(results)]
@jit.unroll_safe
def interpret(self, pc, belt, stack):
if stack is None:
raise Done([belt.get(i) for i in reversed(self.results)])
vals = [belt.get(i) for i in self.results]
stack.restore(belt)
for v in vals:
belt.put(v)
ret = jit.promote(stack.pc)
return ret, stack.prev, ret < pc
def tostring(self):
args = " ".join(["B%d" % i for i in reversed(self.results)])
return "RETURN %s" % args
class Binop(Instruction):
_immutable_fields_ = ["lhs", "rhs"]
name = "BINOP"
classes = {}
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
@staticmethod
def binop(v0, v1):
raise Exception("abstract method")
@staticmethod
def get_cls(name):
return Binop.classes[name]
@staticmethod
def add_cls(cls):
Binop.classes[cls.name] = cls
def interpret(self, pc, belt, stack):
v0 = belt.get(self.lhs)
v1 = belt.get(self.rhs)
belt.put(self.binop(v0, v1))
return pc + 1, stack, False
def tostring(self):
return "%s B%d B%d" % (self.name, self.lhs, self.rhs)
def make_binop(ins_name, op):
class BinopImp(Binop):
name = ins_name
@staticmethod
def binop(v0, v1):
return op(v0, v1)
BinopImp.__name__ += "ins_name"
Binop.add_cls(BinopImp)
return BinopImp
def make_cmp(ins_name, op):
class Cmp(Binop):
name = ins_name
@staticmethod
def binop(v0, v1):
return 1 if op(v0, v1) else 0
Binop.add_cls(Cmp)
return Cmp
BINOPS = [("ADD", op.add),
("SUB", op.sub),
("MUL", op.mul),
("DIV", op.div),
("MOD", op.mod),
]
for i in BINOPS:
make_binop(*i)
CMPS = [("LTE", op.le),
("GTE", op.ge),
("EQ" , op.eq),
("LT" , op.lt),
("GT" , op.gt),
("NEQ", op.ne),
]
for i in CMPS:
make_cmp(*i)
class Pick(Instruction):
_immutable_fields_ = ["pred", "cons", "alt"]
def __init__(self, pred, cons, alt):
self.pred = pred
self.cons = cons
self.alt = alt
def interpret(self, pc, belt, stack):
belt.put(belt.get(self.cons) if belt.get(self.pred) != 0 else belt.get(self.alt))
return pc + 1, stack, False
def tostring(self):
return "PICK B%d B%d B%d" % (self.pred, self.cons, self.alt)
def get_labels(instructions):
labels = {}
i = 0
for ins in instructions:
if not ins:
continue
if ins[-1] == ':':
labels[ins[:-1]] = i
else:
i += 1
return labels
def convert_arg(val, labels):
val = rstring.strip_spaces(val)
if val in labels:
return labels[val]
val = val[1:] if val[0] == 'b' or val[0] == 'B' else val
int_rep = int(val, 10)
return int_rep
def parse(input):
program = []
lines = [rstring.strip_spaces(i) for i in rstring.split(input, '\n')]
labels = get_labels(lines)
for line in lines:
line = [i for i in rstring.split(line, ' ') if i]
if not line:
continue
ins, args = line[0].upper(), [convert_arg(i, labels) for i in line[1:]]
if ins[-1] == ':':
continue
elif ins == "COPY":
val = Copy(args[0])
elif ins == "CONST":
val = Const(args[0])
elif ins == "CALL":
val = Call(args[0], args[1:])
elif ins == "JUMP":
val = Jump(args[0])
elif ins == "RETURN":
val = Return(args)
elif ins == "PICK":
val = Pick(args[0], args[1], args[2])
elif ins in Binop.classes:
val = Binop.get_cls(ins)(args[0], args[1])
else:
raise Exception("Unparsable instruction %s" % ins)
program.append(val)
return program[:]
def get_printable_location(pc, program):
if pc is None or program is None:
return "Greens are None"
return "%d: %s" % (pc, program[pc].tostring())
driver = jit.JitDriver(reds=["stack", "belt"],
greens=["pc", "program"],
virtualizables=["belt"],
get_printable_location=get_printable_location)
def make_belt(LEN):
attrs = ["_elem_%d_of_%d" % (d, LEN) for d in range(LEN)]
unrolled = unroll.unrolling_iterable(enumerate(attrs))
swaps = unroll.unrolling_iterable(zip(attrs[-2::-1], attrs[-1::-1]))
class Belt(object):
_virtualizable_ = attrs
def __init__(self):
self = jit.hint(self, access_directly=True, fresh_virtualizable=True)
self.reset()
def get(self, idx):
for i, attr in unrolled:
if i == idx:
return getattr(self, attr)
assert False, "belt index error"
def put(self, val):
for src, target in swaps:
setattr(self, target, getattr(self, src))
setattr(self, attrs[0], val)
def reset(self):
for _, attr in unrolled:
setattr(self, attr, 0)
class ActivationRecord(object):
_immutable_fields_ = ["pc", "prev"] + attrs
def __init__(self, pc, belt, prev):
self.pc = pc
self.prev = prev
for i, attr in unrolled:
setattr(self, attr, getattr(belt, attr))
def restore(self, belt):
for _, attr in unrolled:
setattr(belt, attr, getattr(self, attr))
return Belt, ActivationRecord
Belt, ActivationRecord = make_belt(BELT_LEN)
binops = unroll.unrolling_iterable(Binop.classes.values())
def main_loop(program):
pc = 0
belt = Belt()
stack = None
try:
while True:
driver.jit_merge_point(pc=pc, program=program, belt=belt, stack=stack)
ins = program[pc]
pc, stack, can_enter = ins.interpret(pc, belt, stack)
if can_enter:
driver.can_enter_jit(pc=pc, program=program, belt=belt, stack=stack)
except Done as d:
print "Results: ", d.values
def readfile_rpython(fname):
f = streamio.open_file_as_stream(fname)
s = f.readall()
f.close()
return s
def run(fname):
contents = readfile_rpython(fname)
program = parse(contents)
main_loop(program)
def entry_point(argv):
try:
filename = argv[1]
except IndexError:
print "You must supply a filename"
return 1
run(filename)
return 0
def target(driver, args):
if driver.config.translation.jit:
driver.exe_name = 'belt-oo-%(backend)s'
else:
driver.exe_name = 'belt-oo-%(backend)s-nojit'
return entry_point, None
if __name__ == "__main__":
import sys
entry_point(sys.argv)