-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpreter.py
413 lines (331 loc) · 12.5 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import argparse
import sys
from enum import Enum
from astvisitor import NodeVisitor
from base import (_SHOULD_LOG_SCOPE, _SHOULD_LOG_STACK, Error, ErrorCode,
LexerError, ParserError, SemanticError)
from lex import Lexer, TokenType
from parse import FunctionDecl, Parser, ProcedureDecl
from sts import SemanticAnalyzer
###############################################################################
# #
# INTERPRETER #
# #
###############################################################################
class ARType(Enum):
PROGRAM = "PROGRAM"
class CallStack:
def __init__(self):
self._records = []
def push(self, ar):
arNow = self.peek()
if arNow != None:
ar.enclosingActivationRecord = arNow
ar.nestingLevel = arNow.nestingLevel + 1
self._records.append(ar)
def pop(self):
return self._records.pop()
def peek(self):
if self._records != []:
return self._records[-1]
else:
return None
# return
def __str__(self):
s = "\n".join(repr(ar) for ar in reversed(self._records))
s = f"CALL STACK\n{s}\n"
return s
def __repr__(self):
return self.__str__()
class ActivationRecord:
def __init__(self, name, type, nesting_level=1, enclosingActivationRecord=None):
self.name = name
self.type = type
self.nestingLevel = nesting_level
self.members = {}
self.enclosingActivationRecord = enclosingActivationRecord
# 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 declareItem(self, key):
self.members[key] = None
def setItem(self, key, value):
if key in self.members.keys():
self.members[key] = value
elif self.enclosingActivationRecord != None:
self.enclosingActivationRecord.setItem(key, value)
else:
raise RuntimeError(ErrorCode.ID_NOT_FOUND, None, "ID_NOT_FOUND")
def getItem(self, key):
if key in self.members.keys():
return self.members[key]
elif self.enclosingActivationRecord != None:
return self.enclosingActivationRecord.getItem(key)
else:
raise RuntimeError(ErrorCode.ID_NOT_FOUND, None, "ID_NOT_FOUND")
def hasItem(self, key):
if key in self.members.keys():
return True
elif self.enclosingActivationRecord != None:
return self.enclosingActivationRecord.hasItem(key)
else:
return False
def setReturn(self, value):
self.returnValue = value
def __str__(self):
lines = [
"{level}: {type} {name}".format(
level=self.nestingLevel, 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 BreakError(Error):
name = "BreakError"
def __init__(self, token=None):
pass
class ContinueError(Error):
name = "ContinueError"
def __init__(self, token=None):
pass
class Interpreter(NodeVisitor):
def __init__(self):
# self.tree = tree
self.call_stack = CallStack()
self.programActivationRecord = None
def log(self, msg):
if _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):
varName = node.var_node.value
ar = self.call_stack.peek()
ar.declareItem(varName)
def visit_Type(self, node):
# Do nothing
pass
def visit_BinOp(self, node):
leftVal = self.visit(node.left)
rightVal = self.visit(node.right)
if node.op.type == TokenType.PLUS:
return leftVal + rightVal
elif node.op.type == TokenType.MINUS:
return leftVal - rightVal
elif node.op.type == TokenType.MUL:
return leftVal * rightVal
elif node.op.type == TokenType.INTEGER_DIV:
return leftVal // rightVal
elif node.op.type == TokenType.FLOAT_DIV:
return float(leftVal) / float(rightVal)
elif node.op.type == TokenType.BWISESHIFTLEFT:
return leftVal << rightVal
elif node.op.type == TokenType.BWISESHIFTRIGHT:
return leftVal >> rightVal
elif node.op.type == TokenType.BWISEOR:
return leftVal | rightVal
elif node.op.type == TokenType.BWISEAND:
return leftVal & rightVal
elif node.op.type == TokenType.BWISEXOR:
return leftVal ^ rightVal
elif node.op.type == TokenType.AND:
return leftVal and rightVal
elif node.op.type == TokenType.OR:
return leftVal or rightVal
elif node.op.type == TokenType.EQUALS:
return leftVal == rightVal
elif node.op.type == TokenType.NOT_EQUALS:
return leftVal != rightVal
elif node.op.type == TokenType.GREATER_THAN:
return leftVal > rightVal
elif node.op.type == TokenType.GREATER_OR_EQUALS_THAN:
return leftVal >= rightVal
elif node.op.type == TokenType.LESS_THAN:
return leftVal < rightVal
elif node.op.type == TokenType.LESS_OR_EQUALS_THAN:
return leftVal <= rightVal
else:
raise self.runtimeError(ErrorCode.UNEXPECTED_TOKEN, node.token)
def visit_Num(self, node):
return node.value
def visit_String(self, node):
return node.value
def visit_MyBoolean(self, node):
return node.value
def visit_UnaryOp(self, node):
op = node.op.type
if self.visit(node.right) == None:
raise self.runtimeError(ErrorCode.ID_NOT_FOUND, node.token)
if op == TokenType.PLUS:
return +self.visit(node.right)
elif op == TokenType.MINUS:
return -self.visit(node.right)
elif op == TokenType.NOT:
return not self.visit(node.right)
elif op == TokenType.BWISENOT:
return ~self.visit(node.right)
else:
raise self.runtimeError(ErrorCode.UNEXPECTED_TOKEN, node.token)
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()
if ar.type == TokenType.FUNCTION and var_name == ar.name:
ar.setReturn(var_value)
else:
# print(var_name,var_value)
ar.setItem(var_name, var_value)
def visit_Var(self, node):
varName = node.value
ar = self.call_stack.peek()
if ar.hasItem(varName):
val = ar.getItem(varName)
if val == None:
raise self.runtimeError(ErrorCode.VARIABLE_NOT_INITIALISER, node.token)
return val
raise self.runtimeError(ErrorCode.ID_NOT_FOUND, node.token)
def visit_NoOp(self, node):
pass
def visit_ProcedureDecl(self, node):
procName = node.procName
ar = self.call_stack.peek()
ar.declareItem(procName)
ar.setItem(procName, node)
def visit_FunctionDecl(self, node):
funcName = node.funcName
ar = self.call_stack.peek()
ar.declareItem(funcName)
ar.setItem(funcName, node)
def visit_ProcedureCall(self, node):
pass
def visit_WritelnCall(self, node):
for param in node.actual_params:
print(self.visit(param))
def visit_Readint(self, node):
return int(input())
def visit_Readfloat(self, node):
return float(input())
def visit_Readstring(self, node):
return str(input())
def visit_Call(self, node):
name = node.name
ar = self.call_stack.peek()
proc = ar.getItem(name)
if isinstance(proc, ProcedureDecl):
self.log("ENTER : PROCEDURE {}".format(name))
actualParamValues = []
for actualParam in node.actualParams:
actualParamValues.append(self.visit(actualParam))
newAr = ActivationRecord(name, TokenType.PROCEDURE)
self.call_stack.push(newAr)
ar = self.call_stack.peek()
for i in range(0, len(proc.params)):
ar.declareItem(proc.params[i].var_node.value)
ar.setItem(proc.params[i].var_node.value, actualParamValues[i])
self.visit(proc.blockNode)
self.log("{}".format(self.call_stack))
self.log("LEAVE: PROCEDURE {}".format(name))
elif isinstance(proc, FunctionDecl):
self.log("ENTER: FUNCTION {}".format(name))
actualParamValues = []
for actualParam in node.actualParams:
actualParamValues.append(self.visit(actualParam))
newAr = ActivationRecord(name, TokenType.FUNCTION)
self.call_stack.push(newAr)
ar = self.call_stack.peek()
for i in range(0, len(proc.params)):
ar.declareItem(proc.params[i].var_node.value)
ar.setItem(proc.params[i].var_node.value, actualParamValues[i])
self.visit(proc.blockNode)
self.log("{}".format(self.call_stack))
self.call_stack.pop()
self.log("LEAVE: FUNCTION {}".format(name))
if ar.returnValue == None:
raise self.runtimeError(ErrorCode.MISSING_RETURN, proc.token)
return ar.returnValue
def visit_Condition(self, node):
if self.visit(node.condition) == True:
self.visit(node.then)
else:
if node.myElse:
self.visit(node.myElse)
def visit_Then(self, node):
self.visit(node.child)
def visit_MyElse(self, node):
self.visit(node.child)
def visit_While(self, node):
while self.visit(node.condition) == True:
try:
if self.visit(node.myDo) == True:
break
except BreakError:
break
except ContinueError:
continue
except Exception:
raise Exception
def visit_MyDo(self, node):
self.visit(node.child)
def visit_Continue(self, node):
raise ContinueError(node.token)
def visit_Break(self, node):
raise BreakError(node.token)
def interpret(self, tree):
self.visit(tree)
if self.programActivationRecord:
return self.programActivationRecord.members
def runtimeError(self, errorCode, token):
return RuntimeError(errorCode, token, "{} -> {}".format(errorCode, token))
def main():
parser = argparse.ArgumentParser(description="SPI - Simple Pascal Interpreter")
parser.add_argument("inputfile", help="Pascal source file")
parser.add_argument(
"--scope", help="Print scope information", action="store_true",
)
parser.add_argument(
"--stack", help="Print call stack", action="store_true",
)
args = parser.parse_args()
global _SHOULD_LOG_SCOPE, _SHOULD_LOG_STACK
_SHOULD_LOG_SCOPE, _SHOULD_LOG_STACK = args.scope, args.stack
text = open(args.inputfile, "r").read()
# print(text)
lexer = Lexer(text)
try:
parser = Parser(lexer)
tree = parser.parse()
except (LexerError, ParserError) as e:
print(e.message)
sys.exit(1)
semantic_analyzer = SemanticAnalyzer(_SHOULD_LOG_SCOPE)
try:
semantic_analyzer.visit(tree)
except SemanticError as e:
print(e.message)
sys.exit(1)
interpreter = Interpreter()
interpreter.interpret(tree)
if __name__ == "__main__":
main()