-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
210 lines (157 loc) · 5.86 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
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
"""Interpreter class that holds the callstack"""
from enum import Enum
from token import TokenType
###############################################################################
# #
# AST visitors (walkers) #
# #
###############################################################################
class NodeVisitor:
def visit(self, node):
method_name = 'visit_' + type(node).__name__
visitor = getattr(self, method_name, self.generic_visit)
return visitor(node)
def generic_visit(self, node):
raise Exception('No visit_{} method'.format(type(node).__name__))
###############################################################################
# #
# INTERPRETER #
# #
###############################################################################
class ARType(Enum):
PROGRAM = 'PROGRAM'
PROCEDURE = 'PROCEDURE'
class CallStack:
def __init__(self):
self._records = []
def push(self, ar):
self._records.append(ar)
def pop(self):
return self._records.pop()
def peek(self):
return self._records[-1]
def __str__(self):
s = '\n'.join(repr(ar) for ar in reversed(self._records))
s = f'CALL STACK\n{s}\n\n'
return s
def __repr__(self):
return self.__str__()
class ActivationRecord:
def __init__(self, name, type, nesting_level):
self.name = name
self.type = type
self.nesting_level = nesting_level
self.members = {}
def __setitem__(self, key, value):
self.members[key] = value
def __getitem__(self, key):
return self.members[key]
def get(self, key):
return self.members.get(key)
def __str__(self):
lines = [
'{level}: {type} {name}'.format(
level=self.nesting_level,
type=self.type.value,
name=self.name,
)
]
for name, val in self.members.items():
lines.append(f' {name:<20}: {val}')
s = '\n'.join(lines)
return s
def __repr__(self):
return self.__str__()
class Interpreter(NodeVisitor):
def __init__(self, tree, _SHOULD_LOG_STACK=False):
self.tree = tree
self.call_stack = CallStack()
self._SHOULD_LOG_STACK = _SHOULD_LOG_STACK
def log(self, msg):
if self._SHOULD_LOG_STACK:
print(msg)
def visit_Program(self, node):
program_name = node.name
self.log(f'ENTER: PROGRAM {program_name}')
ar = ActivationRecord(
name=program_name,
type=ARType.PROGRAM,
nesting_level=1,
)
self.call_stack.push(ar)
self.log(str(self.call_stack))
self.visit(node.block)
self.log(f'LEAVE: PROGRAM {program_name}')
self.log(str(self.call_stack))
self.call_stack.pop()
def visit_Block(self, node):
for declaration in node.declarations:
self.visit(declaration)
self.visit(node.compound_statement)
def visit_VarDecl(self, node):
# Do nothing
pass
def visit_Type(self, node):
# Do nothing
pass
def visit_BinOp(self, node):
if node.op.type == TokenType.PLUS:
return self.visit(node.left) + self.visit(node.right)
elif node.op.type == TokenType.MINUS:
return self.visit(node.left) - self.visit(node.right)
elif node.op.type == TokenType.MUL:
return self.visit(node.left) * self.visit(node.right)
elif node.op.type == TokenType.INTEGER_DIV:
return self.visit(node.left) // self.visit(node.right)
elif node.op.type == TokenType.FLOAT_DIV:
return float(self.visit(node.left)) / float(self.visit(node.right))
def visit_Num(self, node):
return node.value
def visit_UnaryOp(self, node):
op = node.op.type
if op == TokenType.PLUS:
return +self.visit(node.expr)
elif op == TokenType.MINUS:
return -self.visit(node.expr)
def visit_Compound(self, node):
for child in node.children:
self.visit(child)
def visit_Assign(self, node):
var_name = node.left.value
var_value = self.visit(node.right)
ar = self.call_stack.peek()
ar[var_name] = var_value
def visit_Var(self, node):
var_name = node.value
ar = self.call_stack.peek()
var_value = ar.get(var_name)
return var_value
def visit_NoOp(self, node):
pass
def visit_ProcedureDecl(self, node):
pass
def visit_ProcedureCall(self, node):
proc_name = node.proc_name
proc_symbol = node.proc_symbol
ar = ActivationRecord(
name=proc_name,
type=ARType.PROCEDURE,
nesting_level=proc_symbol.scope_level + 1,
)
formal_params = proc_symbol.formal_params
actual_params = node.actual_params
for param_symbol, argument_node in zip(formal_params, actual_params):
ar[param_symbol.name] = self.visit(argument_node)
self.call_stack.push(ar)
self.log(f'ENTER: PROCEDURE {proc_name}')
self.log(str(self.call_stack))
# evaluate procedure body
self.visit(proc_symbol.block_ast)
self.log(f'LEAVE: PROCEDURE {proc_name}')
self.log(str(self.call_stack))
self.call_stack.pop()
def interpret(self):
tree = self.tree
if tree is None:
return ''
return self.visit(tree)