-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
142 lines (127 loc) · 4.05 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
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
from collections import deque
class SymbolTable():
def __init__(self):
self.scopes = [{}]
def push_scope(self, symbols=None):
if symbols is None:
symbols = {}
self.scopes.append(symbols)
def pop_scope(self):
self.scopes.pop()
if len(self.scopes) == 0:
self.scopes.append({})
def get(self, key):
for scope in reversed(self.scopes):
if key in scope:
return scope[key]
def set(self, key, value):
self.scopes[-1][key] = value
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
def __contains__(self, key):
return any(key in scope for scope in reversed(self.scopes))
def execute(ip, token, stack, queue, symbols, funcs):
# print(token, stack, "=> ", end="")
if token["type"] == "num":
stack.append(token["value"])
elif token["type"] == "function":
func = token["value"]
funcs.append(func)
addr = len(funcs) - 1
stack.append(addr)
elif token["type"] == "return":
return_value = stack.pop()
stack.pop() # Pop the base pointer for parity
return_addr = stack.pop()
for i in range(token["arg_count"]):
stack.pop()
ip = return_addr
stack.append(return_value)
symbols.pop_scope()
elif token["type"] == "constant":
name = token["value"]
value = stack.pop()
symbols[name] = value
elif token["type"] == "reference":
name = token["value"]
if name in symbols:
stack.append(symbols[name])
else:
raise Exception(f"Label '{name}' is undefined.")
elif token["type"] == "if":
condition = stack.pop()
if condition:
queue.extendleft(reversed(token["value"]))
elif token["type"] == "if-else":
condition = stack.pop()
if condition:
queue.extendleft(reversed(token["value"][0]))
else:
queue.extendleft(reversed(token["value"][1]))
elif token["type"] == "op":
op = token["value"]
if op == "@":
a = stack.pop()
stack.append(stack[-(a+1)])
elif op == "void":
stack.pop()
elif op == "!":
addr = stack.pop()
func = funcs[addr]
args = { name: stack[-(i+1)] for i, name in enumerate(reversed(func["args"])) }
symbols.push_scope(args)
stack.append(ip)
stack.append(len(stack))
queue.extendleft(reversed([*func["block"], { "type": "return", "arg_count": len(func["args"]) }]))
elif op == "+":
a = stack.pop()
b = stack.pop()
stack.append(a + b)
elif op == "-":
b = stack.pop()
a = stack.pop()
stack.append(a - b)
elif op == "*":
a = stack.pop()
b = stack.pop()
stack.append(a * b)
elif op == "/":
b = stack.pop()
a = stack.pop()
stack.append(a // b)
elif op == "%":
b = stack.pop()
a = stack.pop()
stack.append(a % b)
elif op == "=":
a = stack.pop()
b = stack.pop()
stack.append(1 if a == b else 0)
elif op == "~":
a = stack.pop()
stack.append(1 if a == 0 else 0)
elif op == ".":
print(stack.pop())
else:
raise Exception(f"Unrecognised operator '{op}'.")
else:
type = token["type"]
raise Exception(f"Unknown token type '{type}'.")
# print(stack)
return ip
def interpret(tokens):
stack = []
ip = 0
queue = deque()
symbols = SymbolTable()
funcs = []
while ip < len(tokens) or len(queue) > 0:
if len(queue) > 0:
token = queue.popleft()
else:
token = tokens[ip]
ip += 1
ip = execute(ip, token, stack, queue, symbols, funcs)
return stack