| 1 |
""" |
| 2 |
An interpreter for a strange word-based language: the program is a list |
| 3 |
of space-separated words. Most words push themselves on a stack; some |
| 4 |
words have another action. The result is the space-separated words |
| 5 |
from the stack. |
| 6 |
|
| 7 |
6 7 ADD => '13' 'ADD' is a special word |
| 8 |
7 * 5 = 7 5 MUL => '7 * 5 = 35' '*' and '=' are not special words |
| 9 |
3.8 => 3.8 |
| 10 |
|
| 11 |
Arithmetic on integers and floats automatically casts arguments |
| 12 |
to floats (always). |
| 13 |
|
| 14 |
3.8 1 ADD => 4.8 |
| 15 |
|
| 16 |
Input arguments can be passed on the command-line, and used as #1, #2, etc.: |
| 17 |
|
| 18 |
#1 1 ADD => one more than the argument on the command-line, |
| 19 |
or if it was not an integer, concatenates '+1' |
| 20 |
|
| 21 |
You can store back into an (existing) argument index with ->#N: |
| 22 |
|
| 23 |
#1 5 ADD ->#1 |
| 24 |
|
| 25 |
Braces { } delimitate a loop. Don't forget spaces around each one. |
| 26 |
The '}' pops an integer value off the stack and loops if it is not zero: |
| 27 |
|
| 28 |
{ #1 #1 1 SUB ->#1 #1 } => when called with 5, gives '5 4 3 2 1' |
| 29 |
|
| 30 |
""" |
| 31 |
from rpython.rlib.jit import promote, hint, JitDriver |
| 32 |
from rpython.rlib.objectmodel import specialize |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
class Box: |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
pass |
| 46 |
|
| 47 |
class IntBox(Box): |
| 48 |
_immutable_ = True |
| 49 |
def __init__(self, intval): |
| 50 |
self.intval = intval |
| 51 |
def as_int(self): |
| 52 |
return self.intval |
| 53 |
def as_float(self): |
| 54 |
return myfloat(self.intval) |
| 55 |
def as_str(self): |
| 56 |
return str(self.intval) |
| 57 |
|
| 58 |
class FloatBox(Box): |
| 59 |
_immutable_ = True |
| 60 |
def __init__(self, floatval): |
| 61 |
self.floatval = floatval |
| 62 |
def as_int(self): |
| 63 |
return int(self.floatval) |
| 64 |
def as_float(self): |
| 65 |
return self.floatval |
| 66 |
def as_str(self): |
| 67 |
return str(self.floatval) |
| 68 |
|
| 69 |
|
| 70 |
def func_add_int(ix, iy): return ix + iy |
| 71 |
def func_sub_int(ix, iy): return ix - iy |
| 72 |
def func_mul_int(ix, iy): return ix * iy |
| 73 |
|
| 74 |
def func_add_float(fx, fy): return fx + fy |
| 75 |
def func_sub_float(fx, fy): return fx - fy |
| 76 |
def func_mul_float(fx, fy): return fx * fy |
| 77 |
|
| 78 |
def op2(stack, func_int, func_float): |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
stack, y = stack.pop() |
| 86 |
promote(y.__class__) |
| 87 |
stack, x = stack.pop() |
| 88 |
promote(x.__class__) |
| 89 |
if isinstance(x, IntBox) and isinstance(y, IntBox): |
| 90 |
z = IntBox(func_int(x.as_int(), y.as_int())) |
| 91 |
else: |
| 92 |
z = FloatBox(func_float(x.as_float(), y.as_float())) |
| 93 |
stack = Stack(z, stack) |
| 94 |
return stack |
| 95 |
|
| 96 |
class Stack(object): |
| 97 |
def __init__(self, value, next=None): |
| 98 |
self.next = next |
| 99 |
self.value = value |
| 100 |
|
| 101 |
def pop(self): |
| 102 |
return self.next, self.value |
| 103 |
|
| 104 |
def empty_stack(): |
| 105 |
return None |
| 106 |
|
| 107 |
class TinyJitDriver(JitDriver): |
| 108 |
reds = ['args', 'loops', 'stack'] |
| 109 |
greens = ['bytecode', 'pos'] |
| 110 |
|
| 111 |
def compute_invariants(self, reds, bytecode, pos): |
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
return reds.loops |
| 119 |
|
| 120 |
def on_enter_jit(self, invariants, reds, bytecode, pos): |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
oldloops = invariants |
| 127 |
oldargs = reds.args |
| 128 |
argcount = promote(len(oldargs)) |
| 129 |
args = [] |
| 130 |
n = 0 |
| 131 |
while n < argcount: |
| 132 |
hint(n, concrete=True) |
| 133 |
args.append(oldargs[n]) |
| 134 |
n += 1 |
| 135 |
reds.args = args |
| 136 |
|
| 137 |
oldloops = hint(oldloops, deepfreeze=True) |
| 138 |
argcount = len(oldloops) |
| 139 |
loops = [] |
| 140 |
n = 0 |
| 141 |
while n < argcount: |
| 142 |
hint(n, concrete=True) |
| 143 |
loops.append(oldloops[n]) |
| 144 |
n += 1 |
| 145 |
reds.loops = loops |
| 146 |
|
| 147 |
tinyjitdriver = TinyJitDriver() |
| 148 |
|
| 149 |
def interpret(bytecode, args): |
| 150 |
"""The interpreter's entry point and portal function. |
| 151 |
""" |
| 152 |
loops = [] |
| 153 |
stack = empty_stack() |
| 154 |
pos = 0 |
| 155 |
while True: |
| 156 |
tinyjitdriver.jit_merge_point(args=args, loops=loops, stack=stack, |
| 157 |
bytecode=bytecode, pos=pos) |
| 158 |
bytecode = hint(bytecode, deepfreeze=True) |
| 159 |
if pos >= len(bytecode): |
| 160 |
break |
| 161 |
opcode = bytecode[pos] |
| 162 |
hint(opcode, concrete=True) |
| 163 |
pos += 1 |
| 164 |
if opcode == 'ADD': |
| 165 |
stack = op2(stack, func_add_int, func_add_float) |
| 166 |
elif opcode == 'SUB': |
| 167 |
stack = op2(stack, func_sub_int, func_sub_float) |
| 168 |
elif opcode == 'MUL': |
| 169 |
stack = op2(stack, func_mul_int, func_mul_float) |
| 170 |
elif opcode[0] == '#': |
| 171 |
n = myint(opcode, start=1) |
| 172 |
stack = Stack(args[n-1], stack) |
| 173 |
elif opcode.startswith('->#'): |
| 174 |
n = myint(opcode, start=3) |
| 175 |
if n > len(args): |
| 176 |
raise IndexError |
| 177 |
stack, args[n-1] = stack.pop() |
| 178 |
elif opcode == '{': |
| 179 |
loops.append(pos) |
| 180 |
elif opcode == '}': |
| 181 |
stack, flag = stack.pop() |
| 182 |
if flag.as_int() == 0: |
| 183 |
loops.pop() |
| 184 |
else: |
| 185 |
pos = loops[-1] |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
pos = promote(pos) |
| 198 |
tinyjitdriver.can_enter_jit(args=args, loops=loops, stack=stack, |
| 199 |
bytecode=bytecode, pos=pos) |
| 200 |
else: |
| 201 |
try: |
| 202 |
try: |
| 203 |
v = IntBox(int(opcode)) |
| 204 |
except ValueError: |
| 205 |
v = FloatBox(myfloat(opcode)) |
| 206 |
stack = Stack(v, stack) |
| 207 |
except ValueError: |
| 208 |
pass |
| 209 |
return stack |
| 210 |
|
| 211 |
|
| 212 |
def repr(stack): |
| 213 |
|
| 214 |
|
| 215 |
lst = [] |
| 216 |
while stack: |
| 217 |
stack, x = stack.pop() |
| 218 |
lst.append(x.as_str()) |
| 219 |
lst.reverse() |
| 220 |
return ' '.join(lst) |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
def myint_internal(s, start=0): |
| 228 |
if start >= len(s): |
| 229 |
return -1 |
| 230 |
res = 0 |
| 231 |
while start < len(s): |
| 232 |
c = s[start] |
| 233 |
n = ord(c) - ord('0') |
| 234 |
if not (0 <= n <= 9): |
| 235 |
return -1 |
| 236 |
res = res * 10 + n |
| 237 |
start += 1 |
| 238 |
return res |
| 239 |
def myint(s, start=0): |
| 240 |
n = myint_internal(s, start) |
| 241 |
if n < 0: |
| 242 |
raise ValueError |
| 243 |
return n |
| 244 |
|
| 245 |
@specialize.argtype(0) |
| 246 |
def myfloat(i): |
| 247 |
return float(i) |
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
def test_main(): |
| 252 |
main = """#1 5 ADD""".split() |
| 253 |
res = interpret(main, [IntBox(20)]) |
| 254 |
assert repr(res) == '25' |
| 255 |
res = interpret(main, [FloatBox(3.2)]) |
| 256 |
assert repr(res) == '8.2' |
| 257 |
|
| 258 |
FACTORIAL = """The factorial of #1 is |
| 259 |
1 { #1 MUL #1 1 SUB ->#1 #1 }""".split() |
| 260 |
|
| 261 |
def test_factorial(): |
| 262 |
res = interpret(FACTORIAL, [IntBox(5)]) |
| 263 |
assert repr(res) == '5 120' |
| 264 |
|
| 265 |
FIBONACCI = """Fibonacci numbers: |
| 266 |
{ #1 #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 }""".split() |
| 267 |
|
| 268 |
def test_fibonacci(): |
| 269 |
res = interpret(FIBONACCI, [IntBox(1), IntBox(1), IntBox(10)]) |
| 270 |
assert repr(res) == "1 1 2 3 5 8 13 21 34 55" |
| 271 |
|
| 272 |
|
| 273 |
FIBONACCI_SINGLE = """#3 1 SUB ->#3 { #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 } #1""".split() |
| 274 |
|
| 275 |
def test_fibonacci_single(): |
| 276 |
res = interpret(FIBONACCI_SINGLE, [IntBox(1), IntBox(1), IntBox(11)]) |
| 277 |
assert repr(res) == "89" |