-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinterpreterv2.py
336 lines (301 loc) · 13.3 KB
/
interpreterv2.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
# document that we won't have a return inside the init/update of a for loop
import copy
from enum import Enum
from brewparse import parse_program
from env_v2 import EnvironmentManager
from intbase import InterpreterBase, ErrorType
from type_valuev2 import Type, Value, create_value, get_printable
class ExecStatus(Enum):
CONTINUE = 1
RETURN = 2
# Main interpreter class
class Interpreter(InterpreterBase):
# constants
NIL_VALUE = create_value(InterpreterBase.NIL_DEF)
TRUE_VALUE = create_value(InterpreterBase.TRUE_DEF)
BIN_OPS = {"+", "-", "*", "/", "==", "!=", ">", ">=", "<", "<=", "||", "&&"}
# methods
def __init__(self, console_output=True, inp=None, trace_output=False):
super().__init__(console_output, inp)
self.trace_output = trace_output
self.__setup_ops()
# run a program that's provided in a string
# usese the provided Parser found in brewparse.py to parse the program
# into an abstract syntax tree (ast)
def run(self, program):
ast = parse_program(program)
self.__set_up_function_table(ast)
self.env = EnvironmentManager()
self.__call_func_aux("main", [])
def __set_up_function_table(self, ast):
self.func_name_to_ast = {}
for func_def in ast.get("functions"):
func_name = func_def.get("name")
num_params = len(func_def.get("args"))
if func_name not in self.func_name_to_ast:
self.func_name_to_ast[func_name] = {}
self.func_name_to_ast[func_name][num_params] = func_def
def __get_func_by_name(self, name, num_params):
if name not in self.func_name_to_ast:
super().error(ErrorType.NAME_ERROR, f"Function {name} not found")
candidate_funcs = self.func_name_to_ast[name]
if num_params not in candidate_funcs:
super().error(
ErrorType.NAME_ERROR,
f"Function {name} taking {num_params} params not found",
)
return candidate_funcs[num_params]
def __run_statements(self, statements):
self.env.push_block()
for statement in statements:
if self.trace_output:
print(statement)
status, return_val = self.__run_statement(statement)
if status == ExecStatus.RETURN:
self.env.pop_block()
return (status, return_val)
self.env.pop_block()
return (ExecStatus.CONTINUE, Interpreter.NIL_VALUE)
def __run_statement(self, statement):
status = ExecStatus.CONTINUE
return_val = None
if statement.elem_type == InterpreterBase.FCALL_NODE:
self.__call_func(statement)
elif statement.elem_type == "=":
self.__assign(statement)
elif statement.elem_type == InterpreterBase.VAR_DEF_NODE:
self.__var_def(statement)
elif statement.elem_type == InterpreterBase.RETURN_NODE:
status, return_val = self.__do_return(statement)
elif statement.elem_type == Interpreter.IF_NODE:
status, return_val = self.__do_if(statement)
elif statement.elem_type == Interpreter.FOR_NODE:
status, return_val = self.__do_for(statement)
return (status, return_val)
def __call_func(self, call_node):
func_name = call_node.get("name")
actual_args = call_node.get("args")
return self.__call_func_aux(func_name, actual_args)
def __call_func_aux(self, func_name, actual_args):
if func_name == "print":
return self.__call_print(actual_args)
if func_name == "inputi" or func_name == "inputs":
return self.__call_input(func_name, actual_args)
func_ast = self.__get_func_by_name(func_name, len(actual_args))
formal_args = func_ast.get("args")
if len(actual_args) != len(formal_args):
super().error(
ErrorType.NAME_ERROR,
f"Function {func_ast.get('name')} with {len(actual_args)} args not found",
)
# first evaluate all of the actual parameters and associate them with the formal parameter names
args = {}
for formal_ast, actual_ast in zip(formal_args, actual_args):
result = copy.copy(self.__eval_expr(actual_ast))
arg_name = formal_ast.get("name")
args[arg_name] = result
# then create the new activation record
self.env.push_func()
# and add the formal arguments to the activation record
for arg_name, value in args.items():
self.env.create(arg_name, value)
_, return_val = self.__run_statements(func_ast.get("statements"))
self.env.pop_func()
return return_val
def __call_print(self, args):
output = ""
for arg in args:
result = self.__eval_expr(arg) # result is a Value object
output = output + get_printable(result)
super().output(output)
return Interpreter.NIL_VALUE
def __call_input(self, name, args):
if args is not None and len(args) == 1:
result = self.__eval_expr(args[0])
super().output(get_printable(result))
elif args is not None and len(args) > 1:
super().error(
ErrorType.NAME_ERROR, "No inputi() function that takes > 1 parameter"
)
inp = super().get_input()
if name == "inputi":
return Value(Type.INT, int(inp))
if name == "inputs":
return Value(Type.STRING, inp)
def __assign(self, assign_ast):
var_name = assign_ast.get("name")
value_obj = self.__eval_expr(assign_ast.get("expression"))
if not self.env.set(var_name, value_obj):
super().error(
ErrorType.NAME_ERROR, f"Undefined variable {var_name} in assignment"
)
def __var_def(self, var_ast):
var_name = var_ast.get("name")
if not self.env.create(var_name, Interpreter.NIL_VALUE):
super().error(
ErrorType.NAME_ERROR, f"Duplicate definition for variable {var_name}"
)
def __eval_expr(self, expr_ast):
if expr_ast.elem_type == InterpreterBase.NIL_NODE:
return Interpreter.NIL_VALUE
if expr_ast.elem_type == InterpreterBase.INT_NODE:
return Value(Type.INT, expr_ast.get("val"))
if expr_ast.elem_type == InterpreterBase.STRING_NODE:
return Value(Type.STRING, expr_ast.get("val"))
if expr_ast.elem_type == InterpreterBase.BOOL_NODE:
return Value(Type.BOOL, expr_ast.get("val"))
if expr_ast.elem_type == InterpreterBase.VAR_NODE:
var_name = expr_ast.get("name")
val = self.env.get(var_name)
if val is None:
super().error(ErrorType.NAME_ERROR, f"Variable {var_name} not found")
return val
if expr_ast.elem_type == InterpreterBase.FCALL_NODE:
return self.__call_func(expr_ast)
if expr_ast.elem_type in Interpreter.BIN_OPS:
return self.__eval_op(expr_ast)
if expr_ast.elem_type == Interpreter.NEG_NODE:
return self.__eval_unary(expr_ast, Type.INT, lambda x: -1 * x)
if expr_ast.elem_type == Interpreter.NOT_NODE:
return self.__eval_unary(expr_ast, Type.BOOL, lambda x: not x)
def __eval_op(self, arith_ast):
left_value_obj = self.__eval_expr(arith_ast.get("op1"))
right_value_obj = self.__eval_expr(arith_ast.get("op2"))
if not self.__compatible_types(
arith_ast.elem_type, left_value_obj, right_value_obj
):
super().error(
ErrorType.TYPE_ERROR,
f"Incompatible types for {arith_ast.elem_type} operation",
)
if arith_ast.elem_type not in self.op_to_lambda[left_value_obj.type()]:
super().error(
ErrorType.TYPE_ERROR,
f"Incompatible operator {arith_ast.elem_type} for type {left_value_obj.type()}",
)
f = self.op_to_lambda[left_value_obj.type()][arith_ast.elem_type]
return f(left_value_obj, right_value_obj)
def __compatible_types(self, oper, obj1, obj2):
# DOCUMENT: allow comparisons ==/!= of anything against anything
if oper in ["==", "!="]:
return True
return obj1.type() == obj2.type()
def __eval_unary(self, arith_ast, t, f):
value_obj = self.__eval_expr(arith_ast.get("op1"))
if value_obj.type() != t:
super().error(
ErrorType.TYPE_ERROR,
f"Incompatible type for {arith_ast.elem_type} operation",
)
return Value(t, f(value_obj.value()))
def __setup_ops(self):
self.op_to_lambda = {}
# set up operations on integers
self.op_to_lambda[Type.INT] = {}
self.op_to_lambda[Type.INT]["+"] = lambda x, y: Value(
x.type(), x.value() + y.value()
)
self.op_to_lambda[Type.INT]["-"] = lambda x, y: Value(
x.type(), x.value() - y.value()
)
self.op_to_lambda[Type.INT]["*"] = lambda x, y: Value(
x.type(), x.value() * y.value()
)
self.op_to_lambda[Type.INT]["/"] = lambda x, y: Value(
x.type(), x.value() // y.value()
)
self.op_to_lambda[Type.INT]["=="] = lambda x, y: Value(
Type.BOOL, x.type() == y.type() and x.value() == y.value()
)
self.op_to_lambda[Type.INT]["!="] = lambda x, y: Value(
Type.BOOL, x.type() != y.type() or x.value() != y.value()
)
self.op_to_lambda[Type.INT]["<"] = lambda x, y: Value(
Type.BOOL, x.value() < y.value()
)
self.op_to_lambda[Type.INT]["<="] = lambda x, y: Value(
Type.BOOL, x.value() <= y.value()
)
self.op_to_lambda[Type.INT][">"] = lambda x, y: Value(
Type.BOOL, x.value() > y.value()
)
self.op_to_lambda[Type.INT][">="] = lambda x, y: Value(
Type.BOOL, x.value() >= y.value()
)
# set up operations on strings
self.op_to_lambda[Type.STRING] = {}
self.op_to_lambda[Type.STRING]["+"] = lambda x, y: Value(
x.type(), x.value() + y.value()
)
self.op_to_lambda[Type.STRING]["=="] = lambda x, y: Value(
Type.BOOL, x.value() == y.value()
)
self.op_to_lambda[Type.STRING]["!="] = lambda x, y: Value(
Type.BOOL, x.value() != y.value()
)
# set up operations on bools
self.op_to_lambda[Type.BOOL] = {}
self.op_to_lambda[Type.BOOL]["&&"] = lambda x, y: Value(
x.type(), x.value() and y.value()
)
self.op_to_lambda[Type.BOOL]["||"] = lambda x, y: Value(
x.type(), x.value() or y.value()
)
self.op_to_lambda[Type.BOOL]["=="] = lambda x, y: Value(
Type.BOOL, x.type() == y.type() and x.value() == y.value()
)
self.op_to_lambda[Type.BOOL]["!="] = lambda x, y: Value(
Type.BOOL, x.type() != y.type() or x.value() != y.value()
)
# set up operations on nil
self.op_to_lambda[Type.NIL] = {}
self.op_to_lambda[Type.NIL]["=="] = lambda x, y: Value(
Type.BOOL, x.type() == y.type() and x.value() == y.value()
)
self.op_to_lambda[Type.NIL]["!="] = lambda x, y: Value(
Type.BOOL, x.type() != y.type() or x.value() != y.value()
)
def __do_if(self, if_ast):
cond_ast = if_ast.get("condition")
result = self.__eval_expr(cond_ast)
if result.type() != Type.BOOL:
super().error(
ErrorType.TYPE_ERROR,
"Incompatible type for if condition",
)
if result.value():
statements = if_ast.get("statements")
status, return_val = self.__run_statements(statements)
return (status, return_val)
else:
else_statements = if_ast.get("else_statements")
if else_statements is not None:
status, return_val = self.__run_statements(else_statements)
return (status, return_val)
return (ExecStatus.CONTINUE, Interpreter.NIL_VALUE)
def __do_for(self, for_ast):
init_ast = for_ast.get("init")
cond_ast = for_ast.get("condition")
update_ast = for_ast.get("update")
self.__run_statement(init_ast) # initialize counter variable
run_for = Interpreter.TRUE_VALUE
while run_for.value():
run_for = self.__eval_expr(cond_ast) # check for-loop condition
if run_for.type() != Type.BOOL:
super().error(
ErrorType.TYPE_ERROR,
"Incompatible type for for condition",
)
if run_for.value():
statements = for_ast.get("statements")
status, return_val = self.__run_statements(statements)
if status == ExecStatus.RETURN:
return status, return_val
self.__run_statement(update_ast) # update counter variable
return (ExecStatus.CONTINUE, Interpreter.NIL_VALUE)
def __do_return(self, return_ast):
expr_ast = return_ast.get("expression")
if expr_ast is None:
return (ExecStatus.RETURN, Interpreter.NIL_VALUE)
value_obj = copy.copy(self.__eval_expr(expr_ast))
return (ExecStatus.RETURN, value_obj)