| 1 |
from __future__ import print_function |
| 2 |
|
| 3 |
|
| 4 |
""" |
| 5 |
Run tinyframe.py <input file> [int value reg0] [int value reg1] ... |
| 6 |
|
| 7 |
Interpreter for a tiny interpreter with frame introspection. Supports |
| 8 |
integer values and function values. The machine is |
| 9 |
register based with untyped registers. |
| 10 |
|
| 11 |
Opcodes: |
| 12 |
ADD r1 r2 => r3 # integer addition or function combination, |
| 13 |
# depending on argument types |
| 14 |
# if r1 has a function f and r2 has a function g |
| 15 |
# the result will be a function lambda arg : f(g(arg)) |
| 16 |
# this is also a way to achieve indirect call |
| 17 |
INTROSPECT r1 => r2 # frame introspection - load a register with number |
| 18 |
# pointed by r1 (must be int) to r2 |
| 19 |
PRINT r # print a register |
| 20 |
CALL r1 r2 => r3 # call a function in register one with argument in r2 and |
| 21 |
# result in r3 |
| 22 |
LOAD_FUNCTION <name> => r # load a function named name into register r |
| 23 |
LOAD <int constant> => r # load an integer constant into register r |
| 24 |
RETURN r1 |
| 25 |
JUMP @label # jump + or - by x opcodes |
| 26 |
JUMP_IF_ABOVE r1 r2 @label # jump if value in r1 is above |
| 27 |
# value in r2 |
| 28 |
|
| 29 |
function argument always comes in r0 |
| 30 |
""" |
| 31 |
|
| 32 |
from rpython.rlib.streamio import open_file_as_stream |
| 33 |
from rpython.jit.tl.tinyframe.support import sort |
| 34 |
from rpython.rlib.unroll import unrolling_iterable |
| 35 |
from rpython.rlib.jit import JitDriver, hint, dont_look_inside |
| 36 |
|
| 37 |
opcodes = ['ADD', 'INTROSPECT', 'PRINT', 'CALL', 'LOAD', 'LOAD_FUNCTION', |
| 38 |
'RETURN', 'JUMP', 'JUMP_IF_ABOVE'] |
| 39 |
unrolling_opcodes = unrolling_iterable(opcodes) |
| 40 |
for i, opcode in enumerate(opcodes): |
| 41 |
globals()[opcode] = i |
| 42 |
|
| 43 |
class Code(object): |
| 44 |
def __init__(self, code, regno, functions, name): |
| 45 |
self.code = code |
| 46 |
self.regno = regno |
| 47 |
self.functions = functions |
| 48 |
self.name = name |
| 49 |
|
| 50 |
class Parser(object): |
| 51 |
|
| 52 |
name = None |
| 53 |
|
| 54 |
def compile(self, strrepr): |
| 55 |
self.code = [] |
| 56 |
self.maxregno = 0 |
| 57 |
self.functions = {} |
| 58 |
self.labels = {} |
| 59 |
lines = strrepr.splitlines() |
| 60 |
for line in lines: |
| 61 |
comment = line.find('#') |
| 62 |
if comment != -1: |
| 63 |
assert comment >= 0 |
| 64 |
line = line[:comment] |
| 65 |
line = line.strip(" ") |
| 66 |
if not line: |
| 67 |
continue |
| 68 |
if line.endswith(':'): |
| 69 |
|
| 70 |
self.finish_currect_code() |
| 71 |
self.name = line[:-1] |
| 72 |
continue |
| 73 |
if line.startswith('@'): |
| 74 |
self.labels[line[1:]] = len(self.code) |
| 75 |
continue |
| 76 |
firstspace = line.find(" ") |
| 77 |
assert firstspace >= 0 |
| 78 |
opcode = line[:firstspace] |
| 79 |
args = line[firstspace + 1:] |
| 80 |
for name in unrolling_opcodes: |
| 81 |
if opcode == name: |
| 82 |
getattr(self, 'compile_' + name)(args) |
| 83 |
values = self.functions.values() |
| 84 |
sort(values) |
| 85 |
functions = [code for i, code in values] |
| 86 |
assert self.name == 'main' |
| 87 |
return Code("".join([chr(i) for i in self.code]), self.maxregno + 1, |
| 88 |
functions, self.name) |
| 89 |
|
| 90 |
def finish_currect_code(self): |
| 91 |
if self.name is None: |
| 92 |
assert not self.code |
| 93 |
return |
| 94 |
code = Code("".join([chr(i) for i in self.code]), self.maxregno + 1, |
| 95 |
[], self.name) |
| 96 |
self.functions[self.name] = (len(self.functions), code) |
| 97 |
self.name = None |
| 98 |
self.labels = {} |
| 99 |
self.code = [] |
| 100 |
self.maxregno = 0 |
| 101 |
|
| 102 |
def rint(self, arg): |
| 103 |
assert arg.startswith('r') |
| 104 |
no = int(arg[1:]) |
| 105 |
self.maxregno = max(self.maxregno, no) |
| 106 |
return no |
| 107 |
|
| 108 |
def compile_ADD(self, args): |
| 109 |
args, result = args.split("=") |
| 110 |
result = result[1:] |
| 111 |
arg0, arg1 = args.strip(" ").split(" ") |
| 112 |
self.code += [ADD, self.rint(arg0), self.rint(arg1), |
| 113 |
self.rint(result.strip(" "))] |
| 114 |
|
| 115 |
def compile_LOAD(self, args): |
| 116 |
arg0, result = args.split("=") |
| 117 |
result = result[1:] |
| 118 |
arg0 = arg0.strip(" ") |
| 119 |
self.code += [LOAD, int(arg0), self.rint(result.strip(" "))] |
| 120 |
|
| 121 |
def compile_PRINT(self, args): |
| 122 |
arg = self.rint(args.strip(" ")) |
| 123 |
self.code += [PRINT, arg] |
| 124 |
|
| 125 |
def compile_RETURN(self, args): |
| 126 |
arg = self.rint(args.strip(" ")) |
| 127 |
self.code += [RETURN, arg] |
| 128 |
|
| 129 |
def compile_JUMP_IF_ABOVE(self, args): |
| 130 |
arg0, arg1, label = args.split(" ") |
| 131 |
self.code += [JUMP_IF_ABOVE, self.rint(arg0.strip(" ")), |
| 132 |
self.rint(arg1.strip(" ")), self.labels[label[1:]]] |
| 133 |
|
| 134 |
def compile_LOAD_FUNCTION(self, args): |
| 135 |
name, res = args.split("=") |
| 136 |
res = res[1:] |
| 137 |
no, code = self.functions[name.strip(" ")] |
| 138 |
self.code += [LOAD_FUNCTION, no, self.rint(res.strip(" "))] |
| 139 |
|
| 140 |
def compile_CALL(self, args): |
| 141 |
args, res = args.split("=") |
| 142 |
res = res[1:] |
| 143 |
arg0, arg1 = args.strip(" ").split(" ") |
| 144 |
self.code += [CALL, self.rint(arg0.strip(" ")), |
| 145 |
self.rint(arg1.strip(" ")), |
| 146 |
self.rint(res.strip(" "))] |
| 147 |
|
| 148 |
def compile_INTROSPECT(self, args): |
| 149 |
arg, res = args.split("=") |
| 150 |
res = res[1:] |
| 151 |
self.code += [INTROSPECT, self.rint(arg.strip(" ")), |
| 152 |
self.rint(res.strip(" "))] |
| 153 |
|
| 154 |
def compile_JUMP(self, args): |
| 155 |
raise NotImplementedError |
| 156 |
|
| 157 |
def compile(strrepr): |
| 158 |
parser = Parser() |
| 159 |
return parser.compile(strrepr) |
| 160 |
|
| 161 |
def disassemble(code): |
| 162 |
return [ord(i) for i in code.code] |
| 163 |
|
| 164 |
class Object(object): |
| 165 |
def __init__(self): |
| 166 |
raise NotImplementedError("abstract base class") |
| 167 |
|
| 168 |
def add(self, other): |
| 169 |
raise NotImplementedError("abstract base class") |
| 170 |
|
| 171 |
def gt(self, other): |
| 172 |
raise NotImplementedError("abstract base class") |
| 173 |
|
| 174 |
def repr(self): |
| 175 |
raise NotImplementedError("abstract base class") |
| 176 |
|
| 177 |
class Int(Object): |
| 178 |
def __init__(self, val): |
| 179 |
self.val = val |
| 180 |
|
| 181 |
def add(self, other): |
| 182 |
return Int(self.val + other.val) |
| 183 |
|
| 184 |
def gt(self, other): |
| 185 |
return self.val > other.val |
| 186 |
|
| 187 |
def repr(self): |
| 188 |
return str(self.val) |
| 189 |
|
| 190 |
class Func(Object): |
| 191 |
def __init__(self, code): |
| 192 |
self.code = code |
| 193 |
|
| 194 |
def call(self, arg): |
| 195 |
f = Frame(self.code, arg) |
| 196 |
return f.interpret() |
| 197 |
|
| 198 |
def add(self, other): |
| 199 |
return CombinedFunc(self, other) |
| 200 |
|
| 201 |
def repr(self): |
| 202 |
return "<function %s>" % self.code.name |
| 203 |
|
| 204 |
class CombinedFunc(Func): |
| 205 |
def __init__(self, outer, inner): |
| 206 |
self.outer = outer |
| 207 |
self.inner = inner |
| 208 |
|
| 209 |
def call(self, arg): |
| 210 |
return self.outer.call(self.inner.call(arg)) |
| 211 |
|
| 212 |
def repr(self): |
| 213 |
return "<function %s(%s)>" % (self.outer.repr(), self.inner.repr()) |
| 214 |
|
| 215 |
driver = JitDriver(greens = ['i', 'code'], reds = ['self'], |
| 216 |
virtualizables = ['self']) |
| 217 |
|
| 218 |
class Frame(object): |
| 219 |
_virtualizable_ = ['registers[*]', 'code'] |
| 220 |
|
| 221 |
def __init__(self, code, arg=None): |
| 222 |
self = hint(self, access_directly=True, fresh_virtualizable=True) |
| 223 |
self.code = code |
| 224 |
self.registers = [None] * code.regno |
| 225 |
self.registers[0] = arg |
| 226 |
|
| 227 |
def interpret(self): |
| 228 |
i = 0 |
| 229 |
code = self.code.code |
| 230 |
while True: |
| 231 |
driver.jit_merge_point(self=self, code=code, i=i) |
| 232 |
opcode = ord(code[i]) |
| 233 |
if opcode == LOAD: |
| 234 |
self.registers[ord(code[i + 2])] = Int(ord(code[i + 1])) |
| 235 |
i += 3 |
| 236 |
elif opcode == ADD: |
| 237 |
arg1 = self.registers[ord(code[i + 1])] |
| 238 |
arg2 = self.registers[ord(code[i + 2])] |
| 239 |
self.registers[ord(code[i + 3])] = arg1.add(arg2) |
| 240 |
i += 4 |
| 241 |
elif opcode == RETURN: |
| 242 |
return self.registers[ord(code[i + 1])] |
| 243 |
elif opcode == JUMP_IF_ABOVE: |
| 244 |
arg0 = self.registers[ord(code[i + 1])] |
| 245 |
arg1 = self.registers[ord(code[i + 2])] |
| 246 |
tgt = ord(code[i + 3]) |
| 247 |
if arg0.gt(arg1): |
| 248 |
i = tgt |
| 249 |
driver.can_enter_jit(code=code, i=tgt, self=self) |
| 250 |
else: |
| 251 |
i += 4 |
| 252 |
elif opcode == LOAD_FUNCTION: |
| 253 |
f = self.code.functions[ord(code[i + 1])] |
| 254 |
self.registers[ord(code[i + 2])] = Func(f) |
| 255 |
i += 3 |
| 256 |
elif opcode == CALL: |
| 257 |
f = self.registers[ord(code[i + 1])] |
| 258 |
arg = self.registers[ord(code[i + 2])] |
| 259 |
assert isinstance(f, Func) |
| 260 |
self.registers[ord(code[i + 3])] = f.call(arg) |
| 261 |
i += 4 |
| 262 |
elif opcode == PRINT: |
| 263 |
arg = self.registers[ord(code[i + 1])] |
| 264 |
print(arg.repr()) |
| 265 |
i += 2 |
| 266 |
elif opcode == INTROSPECT: |
| 267 |
self.introspect(ord(code[i + 1]), ord(code[i + 2])) |
| 268 |
i += 3 |
| 269 |
else: |
| 270 |
raise Exception("unimplemented opcode %s" % opcodes[opcode]) |
| 271 |
|
| 272 |
@dont_look_inside |
| 273 |
def introspect(self, rarg, rresult): |
| 274 |
source = self.registers[rarg] |
| 275 |
assert isinstance(source, Int) |
| 276 |
self.registers[rresult] = self.registers[source.val] |
| 277 |
|
| 278 |
def interpret(code): |
| 279 |
return Frame(code).interpret() |
| 280 |
|
| 281 |
def main(fname, argv): |
| 282 |
f = open_file_as_stream(fname, "r") |
| 283 |
input = f.readall() |
| 284 |
f.close() |
| 285 |
code = compile(input) |
| 286 |
mainframe = Frame(code) |
| 287 |
for i in range(len(argv)): |
| 288 |
mainframe.registers[i] = Int(int(argv[i])) |
| 289 |
res = mainframe.interpret() |
| 290 |
print("Result:", res.repr()) |
| 291 |
|
| 292 |
if __name__ == '__main__': |
| 293 |
import sys |
| 294 |
if len(sys.argv) < 2: |
| 295 |
print(__doc__) |
| 296 |
sys.exit(1) |
| 297 |
fname = sys.argv[1] |
| 298 |
main(fname, sys.argv[2:]) |