-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpretador.py
More file actions
475 lines (414 loc) · 16.3 KB
/
interpretador.py
File metadata and controls
475 lines (414 loc) · 16.3 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
program = {
"nt": "program",
"global_vars": [
{
"nt": "vardecl",
"modifier": "val",
"name": "final_number",
"type": "int",
"initializer": {
"nt": "int",
"value": "16"
}
}
],
"functions": [
{
"nt": "functiondecl",
"name": "fizzBuzz",
"parameters": [
{
"modifier": "val",
"name": "number",
"type": "int"
}
],
"type": "None",
"body": [
{
"nt": "vardecl",
"modifier": "var",
"name": "temp",
"type": "int",
"initializer": {
"nt": "int",
"value": "1"
}
},
{
"nt": "while",
"condition": {
"nt": "expression",
"operator": "<=",
"left": "temp",
"right": "number"
},
"body": [
{
"nt": "if",
"condition": {
"nt": "expression",
"operator": "&&",
"left": {
"nt": "expression",
"operator": "=",
"left": {
"nt": "expression",
"operator": "%",
"left": "temp",
"right": {
"nt": "int",
"value": "3"
}
},
"right": {
"nt": "int",
"value": "0"
}
},
"right": {
"nt": "expression",
"operator": "=",
"left": {
"nt": "expression",
"operator": "%",
"left": "temp",
"right": {
"nt": "int",
"value": "5"
}
},
"right": {
"nt": "int",
"value": "0"
}
}
},
"if": [
{
"nt": "print",
"type": "string",
"value": {
"nt": "string",
"value": "\"FizzBuzz\""
}
}
],
"else": [
{
"nt": "if",
"condition": {
"nt": "expression",
"operator": "=",
"left": {
"nt": "expression",
"operator": "%",
"left": "temp",
"right": {
"nt": "int",
"value": "3"
}
},
"right": {
"nt": "int",
"value": "0"
}
},
"if": [
{
"nt": "print",
"type": "string",
"value": {
"nt": "string",
"value": "\"Fizz\""
}
}
],
"else": [
{
"nt": "if",
"condition": {
"nt": "expression",
"operator": "=",
"left": {
"nt": "expression",
"operator": "%",
"left": "temp",
"right": {
"nt": "int",
"value": "5"
}
},
"right": {
"nt": "int",
"value": "0"
}
},
"if": [
{
"nt": "print",
"type": "string",
"value": {
"nt": "string",
"value": "\"Buzz\""
}
}
],
"else": [
{
"nt": "print",
"type": "int",
"value": "temp"
}
]
}
]
}
]
},
{
"nt": "assignment",
"name": "temp",
"expression": {
"nt": "expression",
"operator": "+",
"left": "temp",
"right": {
"nt": "int",
"value": "1"
}
}
}
]
}
]
},
{
"nt": "functiondecl",
"name": "main",
"parameters": [
{
"modifier": "val",
"name": "args",
"type": "arraystring"
}
],
"type": "None",
"body": [
{
"nt": "functioncallinline",
"name": "fizzBuzz",
"parameter_list": [
"final_number"
]
}
]
}
]
}
class Context:
def __init__(self):
self.globals = {}
self.locals = []
self.functions = {}
self.return_value = None
def enter_function(self):
self.locals.append({})
def exit_function(self):
self.locals.pop()
def set_variable(self, name, value, is_global=False):
if is_global or not self.locals:
self.globals[name] = value
else:
self.locals[-1][name] = value
def get_variable(self, name):
for scope in reversed(self.locals):
if name in scope:
return scope[name]
if name in self.globals:
return self.globals[name]
raise KeyError(f"Variable '{name}' not found")
def define_function(self, name, func):
self.functions[name] = func
def get_function(self, name):
if name in self.functions:
return self.functions[name]
else:
raise KeyError(f"Function '{name}' not found")
def set_return_value(self, value):
self.return_value = value
def get_return_value(self):
return self.return_value
def enter_scope(self):
self.locals.append({})
def exit_scope(self):
self.locals.pop()
def is_global_variable(self, name):
return name in self.globals
def get_locals(self):
return self.locals
def interpretador(ctx, node):
node_type = node["nt"]
print(f"Entering node type: {node_type}")
##############################################
if node_type == "program":
# Interpretar as declarações de variáveis globais
for decl in node["global_vars"]:
if decl["nt"] == "vardecl":
name = decl["name"]
initializer = decl["initializer"]
ctx.set_variable(name, interpretador(ctx, initializer), is_global=True)
elif decl["nt"] == "functiondecl":
name = decl["name"]
ctx.define_function(name, decl)
# Armazenar as declarações de funções no contexto
for func in node["functions"]:
name = func["name"]
ctx.define_function(name, func)
# Chamar a função 'main' se ela estiver definida
if "main" in ctx.functions:
main_func = ctx.get_function("main")
ctx.enter_function()
for stmt in main_func["body"]:
interpretador(ctx, stmt)
ctx.exit_function()
print(str(ctx.get_return_value()))
##############################################
elif node_type == "functiondecl":
# Preparação para executar a função
ctx.enter_function()
# Executar o corpo da função
for stmt in node["body"]:
interpretador(ctx, stmt)
ctx.exit_function()
##############################################
elif node_type == "vardecl":
name = node["name"]
print("locals " + str(ctx.get_locals()))
value = interpretador(ctx, node["initializer"])
is_global = ctx.is_global_variable(name)
ctx.set_variable(name, value, is_global)
##############################################
elif node_type == "while":
print("Starting while loop...")
ctx.enter_scope()
while interpretador(ctx, node["condition"]):
for expr in node["body"]:
interpretador(ctx, expr)
ctx.exit_scope()
print("Exiting while loop.")
##############################################
elif node_type == "if":
condition = node["condition"]
if_true = node["if"]
if_false = node["else"]
condition_result = interpretador(ctx, condition)
if condition_result: # Se a condição é verdadeira
ctx.enter_scope()
for stmt in if_true:
interpretador(ctx, stmt
)
ctx.exit_scope()
elif isinstance(if_false, list): # Se a condição é falsa e existe um bloco else válido
ctx.enter_scope()
for stmt in if_false:
interpretador(ctx, stmt)
ctx.exit_scope()
##############################################
elif node_type == "print":
if isinstance(node["value"], dict) and "nt" in node["value"]:
value = interpretador(ctx, node["value"])
else:
value = ctx.get_variable(node["value"])
print(f"Print statement: {value}")
##############################################
elif node_type == "expression":
operator = node["operator"]
if isinstance(node["left"], dict) and "nt" in node["left"]:
left = interpretador(ctx, node["left"])
else:
left = ctx.get_variable(node["left"])
if isinstance(node["right"], dict) and "nt" in node["right"]:
right = interpretador(ctx, node["right"])
else:
right = ctx.get_variable(node["right"])
if operator == "^":
return left ** right
elif operator == ">":
return left > right
elif operator == "<":
return left < right
elif operator == ">=":
return left >= right
elif operator == "<=":
return left <= right
elif operator == "=":
return left == right
elif operator == "!=":
return left != right
elif operator == "&&":
return left and right
elif operator == "||":
return left or right
elif operator == "!":
return not left
elif operator == "+":
return left + right
elif operator == "-":
return left - right
elif operator == "*":
return left * right
elif operator == "/":
return left / right
elif operator == "%":
return left % right
else:
raise ValueError(f"Operador desconhecido: {operator}")
##############################################
elif node_type == "assignment":
name = node["name"]
if isinstance(node["expression"], dict) and "nt" in node["expression"]:
new_value = interpretador(ctx, node["expression"])
else:
new_value = ctx.get_variable(node["expression"])
if name in ctx.functions:
ctx.set_return_value(new_value)
else:
is_global = ctx.is_global_variable(name)
ctx.set_variable(name, new_value, is_global)
##############################################
elif node_type == "functioncallinline":
fun = ctx.get_function(node["name"])
ctx.enter_function()
params = fun["parameters"]
args = node.get("parameter_list", [])
for param, arg in zip(params, args):
arg_value = ctx.get_variable(arg)
print(f"Setting function parameter {param['name']} to {arg_value}")
ctx.set_variable(param["name"], arg_value)
for stmt in fun["body"]:
interpretador(ctx, stmt)
returnValue = ctx.get_return_value()
ctx.exit_function()
return returnValue
##############################################
elif node_type == "int":
return int(node["value"])
elif node_type == "float":
return float(node["value"])
elif node_type == "string":
return node["value"]
elif node_type == "float":
return float(node["value"])
elif node_type == "arrayint":
return node["value"]
elif node_type == "arrayint2":
return node["value"]
elif node_type == "void":
return node["value"]
elif node_type == "boolean":
return node["value"]
else:
raise Exception("Oops, not implemented yet: {}".format(node_type))
print(f"Exiting node type: {node_type}")
interpretador(Context(), program)