-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
66 lines (48 loc) · 1.26 KB
/
interpreter.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
from errors import *
from handlers import *
import sys
# read program
with open(sys.argv[1], 'r') as f:
text = f.read()
instrs = text.split('\n')
# pass 1: split ops and args
for i in range(len(instrs)):
instrs[i] = instrs[i].split()
# get labels
labels = dict()
for i in range(len(instrs)):
if instrs[i][0] != 'label':
continue
arg = instrs[i][1]
if arg in labels:
raise LabelAlreadyFoundException(arg)
labels[arg] = i
if 'main' not in labels:
raise MainLabelNotFoundException()
else:
vm.pc = labels['main']
# pass 2: cast args to ints
for i in range(len(instrs)):
if len(instrs[i]) == 1:
continue
op = instrs[i][0]
arg = instrs[i][1]
if op == 'push':
instrs[i][1] = int(arg)
elif op == 'call' or 'j' in op:
if arg not in labels:
raise LabelNotFoundException(arg)
instrs[i][1] = labels[arg]
# call handlers, instruction by instruction
while vm.pc >= 0 and vm.pc < len(instrs):
instr = instrs[vm.pc]
op = instr[0]
if op not in handlers:
raise InstructionNotFoundException(op)
if len(instr) == 1:
handlers[op]()
else:
arg = instr[1]
handlers[op](arg)
vm.pc += 1
raise UnexpectedHaltException()