This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpeter.py
317 lines (252 loc) · 10.3 KB
/
interpeter.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
#!/usr/bin/env python
"""Quad Interpreter, by Segev Finer."""
from __future__ import print_function, division
import sys
import io
import re
import argparse
PY2 = sys.version_info[0] == 2
if PY2:
input = raw_input
COMMENTS_RE = re.compile(r"/\*(?:.|\n)*?\*/|#.*")
OP_RE = re.compile(r"^[A-Z]+?$")
LABEL_DEF_RE = re.compile(r"^[a-zA-Z]+[a-zA-Z0-9_]*:$")
ID_RE = re.compile(r"^[a-z_]+[a-z0-9_]*$")
INT_RE = re.compile(r"^[0-9]+$")
FLOAT_RE = re.compile(r"^[0-9]+\.[0-9]*$")
LABEL_RE = re.compile(r"^[a-zA-Z]+[a-zA-Z0-9_]*$")
class QuadError(Exception):
def __init__(self, lineno, msg):
super(QuadError, self).__init__(lineno, msg)
self.lineno = lineno
self.msg = msg
def __str__(self):
return "{}: {}".format(self.lineno, self.msg)
class QuadInst(object):
def __init__(self, inst, lineno=None):
self.inst = inst
self.lineno = lineno
tokens = inst.split()
self.op, self.opers = tokens[0], tokens[1:]
if not OP_RE.match(self.op):
if LABEL_DEF_RE.match(self.op):
self.opers.append(self.op[:-1])
self.op = "LABEL"
else:
raise QuadError(lineno, "invalid op: '{}'".format(self.op))
for i, oper in enumerate(self.opers):
if ID_RE.match(oper):
continue
elif INT_RE.match(oper):
self.opers[i] = int(oper)
elif FLOAT_RE.match(oper):
self.opers[i] = float(oper)
elif LABEL_RE.match(oper):
pass
else:
print(self.op)
raise QuadError(lineno, "invalid oper: '{}'".format(oper))
def __repr__(self):
return "QuadInst({!r}, {!r})".format(self.inst, self.lineno)
def __str__(self):
return self.inst
class QuadProgram(object):
def __init__(self, src):
self.code = []
self.labels = {}
if isinstance(src, str):
src = io.StringIO(src)
for lineno, line in enumerate(src, 1):
# Strip comments and leading/trailing whitespace
line = COMMENTS_RE.sub("", line).strip()
# Skip empty lines
if not line:
continue
inst = QuadInst(line, lineno)
self.code.append(inst)
if inst.op == "HALT":
break
if inst.op == "LABEL":
self.labels[inst.opers[0]] = lineno
else:
raise QuadError(999, "missing HALT")
def __repr__(self):
return "<QuadProgram: {} instructions>".format(len(self.code))
def is_type(value, type_):
if PY2 and type_ is int:
type_ = (int, float)
return isinstance(value, type_)
class Namespace(object):
class Entry(object):
def __init__(self, lineno, value):
self.lineno = lineno
self.value = value
def __repr__(self):
return "Namespace.Entry({!r}, {!r})".format(self.lineno, self.value)
def __init__(self):
self._ns = {}
def __repr__(self):
return "Namespace({!r})".format(self._ns)
def get(self, lineno, type_, name):
return self._lookup(lineno, type_, name).value
def set(self, lineno, type_, name, value):
try:
self._lookup(lineno, type_, name).value = value
except KeyError:
self._ns[name] = self.Entry(lineno, value)
def _lookup(self, lineno, type_, name):
if not isinstance(name, str):
raise QuadError(lineno, "invalid identifier '{}'".format(name))
entry = self._ns[name]
if not is_type(entry.value, type_):
raise QuadError(
lineno,
"type mismatch for variable '{}' (declared at line {}), "
"expected {}, found {}".format(
name, entry.lineno, type_.__name__, type(entry.value).__name__))
return entry
class QuadInterpreter(object):
def __init__(self, prog, trace=False):
self.prog = prog
self.code = prog.code
self.trace = trace
self.pc = 1
self.labels = prog.labels
self.ns = Namespace()
def run(self):
while True:
if self.pc is None:
break
inst = self.code[self.pc - 1]
if self.trace:
print("#{} {}".format(self.pc, inst), file=sys.stderr)
self.pc += 1
try:
eval_inst = getattr(self, "eval_" + inst.op)
except AttributeError:
raise QuadError(inst.lineno, "unknown op: '{}'".format(inst.op))
eval_inst(inst)
def val(self, lineno, type_, oper):
if isinstance(oper, str):
return self.ns.get(lineno, type_, oper)
else:
if not is_type(oper, type_):
raise QuadError(
lineno,
"type mismatch for operand, expected {}, found {}".format(
type_.__name__, type(oper).__name__))
return oper
def eval_LABEL(self, inst):
self.labels[inst.opers[0]] = self.pc
def do_ASN(self, type_, inst):
self.ns.set(inst.lineno, type_, inst.opers[0], self.val(inst.lineno, type_, inst.opers[1]))
def do_PRT(self, type_, inst):
print(self.val(inst.lineno, type_, inst.opers[0]))
def do_INP(self, type_, inst):
while True:
try:
value = type_(input("{} ({})? ".format(inst.opers[0], type_.__name__)))
break
except ValueError:
print("Invalid input!")
self.ns.set(inst.lineno, type_, inst.opers[0], value)
def do_EQL(self, type_, inst):
self.ns.set(
inst.lineno, int, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) == self.val(inst.lineno, type_, inst.opers[2]))
def do_NQL(self, type_, inst):
self.ns.set(
inst.lineno, int, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) != self.val(inst.lineno, type_, inst.opers[2]))
def do_LSS(self, type_, inst):
self.ns.set(
inst.lineno, int, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) < self.val(inst.lineno, type_, inst.opers[2]))
def do_GRT(self, type_, inst):
self.ns.set(
inst.lineno, int, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) > self.val(inst.lineno, type_, inst.opers[2]))
def do_ADD(self, type_, inst):
self.ns.set(
inst.lineno, type_, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) + self.val(inst.lineno, type_, inst.opers[2]))
def do_SUB(self, type_, inst):
self.ns.set(
inst.lineno, type_, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) - self.val(inst.lineno, type_, inst.opers[2]))
def do_MLT(self, type_, inst):
self.ns.set(
inst.lineno, type_, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) * self.val(inst.lineno, type_, inst.opers[2]))
def do_DIV(self, type_, inst):
if type_ is int:
self.ns.set(
inst.lineno, type_, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) // self.val(inst.lineno, type_, inst.opers[2]))
else:
self.ns.set(
inst.lineno, type_, inst.opers[0],
self.val(inst.lineno, type_, inst.opers[1]) / self.val(inst.lineno, type_, inst.opers[2]))
def eval_IASN(self, inst): self.do_ASN(int, inst)
def eval_IPRT(self, inst): self.do_PRT(int, inst)
def eval_IINP(self, inst): self.do_INP(int, inst)
def eval_IEQL(self, inst): self.do_EQL(int, inst)
def eval_INQL(self, inst): self.do_NQL(int, inst)
def eval_ILSS(self, inst): self.do_LSS(int, inst)
def eval_IGRT(self, inst): self.do_GRT(int, inst)
def eval_IADD(self, inst): self.do_ADD(int, inst)
def eval_ISUB(self, inst): self.do_SUB(int, inst)
def eval_IMLT(self, inst): self.do_MLT(int, inst)
def eval_IDIV(self, inst): self.do_DIV(int, inst)
def eval_RASN(self, inst): self.do_ASN(float, inst)
def eval_RPRT(self, inst): self.do_PRT(float, inst)
def eval_RINP(self, inst): self.do_INP(float, inst)
def eval_REQL(self, inst): self.do_EQL(float, inst)
def eval_RNQL(self, inst): self.do_NQL(float, inst)
def eval_RLSS(self, inst): self.do_LSS(float, inst)
def eval_RGRT(self, inst): self.do_GRT(float, inst)
def eval_RADD(self, inst): self.do_ADD(float, inst)
def eval_RSUB(self, inst): self.do_SUB(float, inst)
def eval_RMLT(self, inst): self.do_MLT(float, inst)
def eval_RDIV(self, inst): self.do_DIV(float, inst)
def eval_ITOR(self, inst):
self.ns.set(
inst.lineno, float, inst.opers[0],
float(self.val(inst.lineno, int, inst.opers[1])))
def eval_RTOI(self, inst):
self.ns.set(
inst.lineno, int, inst.opers[0],
int(self.val(inst.lineno, float, inst.opers[1])))
def eval_JUMP(self, inst):
if inst.opers[0][0] == 'L':
self.pc = self.labels[inst.opers[0]]
else:
if not isinstance(inst.opers[0], int):
raise QuadError(inst.lineno, "invalid instruction number: '{}'".format(inst.opers[0]))
self.pc = inst.opers[0]
def eval_JMPZ(self, inst):
if self.ns.get(inst.lineno, int, inst.opers[1]) == 0:
if inst.opers[0][0] == 'L':
self.pc = self.labels[inst.opers[0]]
else:
if not isinstance(inst.opers[0], int):
raise QuadError(inst.lineno, "invalid instruction number: '{}'".format(inst.opers[0]))
self.pc = inst.opers[0]
def eval_HALT(self, inst):
self.pc = None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source")
parser.add_argument("-t", "--trace", action="store_true",
help="enable tracing")
args = parser.parse_args()
try:
with open(args.source, "r") as f:
program = QuadProgram(f)
interpreter = QuadInterpreter(program, trace=args.trace)
interpreter.run()
except QuadError as e:
print("{}:{}: error: {}".format(args.source, e.lineno, e.msg), file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())