-
Notifications
You must be signed in to change notification settings - Fork 0
/
code_generator.py
522 lines (487 loc) · 21.3 KB
/
code_generator.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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import re
class code_generator:
def __init__(self, st):
self.symbol_table = st
self.scope_stack = list()
self.ss = list()
self.pb = dict()
self.i = 0
self.data_pointer = 504
self.temporary_pointer = 1000
self.terminals = ["break", "continue", "def", "else", "if", "return", "while", "global", "[", "]", "(", ")",
"ID", "=", ";", ",", ":", "==", "<", "+", "-", "*", "**", "NUM", "$"]
self.incomplete_funcs = list()
self.return_scope = list()
self.current_func = None
self.scope = 0
self.while_scope_continue = list()
self.while_scope_break = list()
self.semantic_errors = list()
self.inside_while_loop = False
self.expecting_return = False
self.func_def_stack = list()
self.no_more_global_variable = False
self.previous_input = None
pass
def find_id(self, id):
'''
used in get_symbol_table_row()
:param id: lexeme
:return: row(if exists) and False (if does not)
'''
ans = False
max_scope = -1
for row in self.symbol_table:
if self.symbol_table[row]['lexeme'] == id:
if 'scope' in self.symbol_table[row]:
if self.symbol_table[row]['scope'] > max_scope:
ans = self.symbol_table[row]
max_scope = ans['scope']
else:
self.symbol_table[row]['scope'] = self.scope
ans = self.symbol_table[row]
max_scope = ans['scope']
return ans
def gettemp(self):
value = "{}".format(self.temporary_pointer)
self.temporary_pointer += 4
return value
def get_row_by_address(self, address):
for row in self.symbol_table:
if self.symbol_table[row]['address'] == address:
# todo: does it always have a scope?
if self.symbol_table[row]['scope'] != -1:
return row
return -1
def get_symbol_table_row(self, input):
'''
searches symbol table for input. if no lexeme with that name exists, or one exists without an address, it will
assign an address to it and return its row with format: ({'lexeme': 'x', 'address': '500'})
'''
row = self.find_id(input)
if row == False:
row = {'lexeme': input, 'address': self.data_pointer, 'scope': self.scope}
self.symbol_table[len(self.symbol_table) + 1] = row
self.data_pointer += 4
elif 'address' not in row:
row = {'lexeme': input, 'address': self.data_pointer, 'scope': self.scope}
self.symbol_table[len(self.symbol_table)] = row
self.data_pointer += 4
return row
def is_address(self, input):
if isinstance(input, int): return True
return re.search("^[\d#@]", input) is not None
def codegen(self, input, action, line_number):
print("codegen executed with input: {} and action: {}".format(input, action))
if action == "\\pid":
if input in self.terminals:
return
row = self.find_id(input)
if not row:
self.ss.append(input)
else: self.ss.append(row['address'])
elif action == "\\install":
row = self.get_symbol_table_row(self.ss.pop())
self.ss.append(row['address'])
elif action == "\\add":
t = self.gettemp()
arg1, arg2 = self.ss.pop(), self.ss.pop()
if arg1 == "NULL" or arg2 == "NULL":
self.semantic_errors.append("#{}\t:Semantic Error! Void type in operands.".format(line_number))
self.pb[self.i] = ("ADD", arg1, arg2, t)
self.i += 1
self.ss.append(t)
pass
elif action == "\\mult":
t = self.gettemp()
arg1, arg2 = self.ss.pop(), self.ss.pop()
if arg1 == "NULL" or arg2 == "NULL":
self.semantic_errors.append("#{}\t:Semantic Error! Void type in operands.".format(line_number))
self.pb[self.i] = ("MULT", arg1, arg2, t)
self.i += 1
self.ss.append(t)
pass
elif action == "\\sub":
t = self.gettemp()
rhs = self.ss.pop()
lhs = self.ss.pop()
if rhs == "NULL" or lhs == "NULL":
self.semantic_errors.append("#{}\t:Semantic Error! Void type in operands.".format(line_number))
self.pb[self.i] = ("SUB", lhs, rhs, t)
self.i += 1
self.ss.append(t)
pass
elif action == "\\pow":
exponent = self.ss.pop()
base = self.ss.pop()
if exponent == "NULL" or base == "NULL":
self.semantic_errors.append("#{}\t:Semantic Error! Void type in operands.".format(line_number))
t = self.gettemp()
t2 = self.gettemp()
self.pb[self.i] = ("ASSIGN", "#1", t)
self.pb[self.i + 1] = ("ASSIGN", exponent, t2)
self.pb[self.i + 2] = ("JPF", t2, self.i + 6)
self.pb[self.i + 3] = ("MULT", t, base, t)
self.pb[self.i + 4] = ("SUB", t2, "#1", t2)
self.pb[self.i + 5] = ("JP", self.i + 2)
self.i += 6
self.ss.append(t)
elif action == "\\pnum":
self.ss.append("#" + input)
# temp = self.gettemp()
# self.pb[self.i] = ("ASSIGN", "#" + input, temp)
# self.ss.append(temp)
# self.i += 1
elif action == "\\assign": # R -> A
R = self.ss.pop()
A = self.ss.pop()
row = self.get_row_by_address(A)
row = self.symbol_table[row]
if self.scope != row['scope']:
self.symbol_table[len(self.symbol_table)] =\
{'lexeme': row['lexeme'], "scope": self.scope, 'address': self.data_pointer}
# self.data_pointer += 4
A = self.get_symbol_table_row(row['lexeme'])['address']
self.pb[self.i] = ("ASSIGN", R, A)
self.i += 1
elif action == "\\assignArr":
# arr id -> index -> new value
new_value = self.ss.pop()
index = self.ss.pop()
arr_id = self.ss.pop()
t = self.gettemp()
t2 = self.gettemp()
if not self.is_address(new_value):
self.semantic_errors.append("#{}\t:Semantic Error! '{}' is not defined appropriately."
.format(line_number, new_value))
self.pb[self.i] = ("MULT", index, "#4", t)
self.pb[self.i + 1] = ("ADD", t, arr_id, t2)
self.pb[self.i + 2] = ("ASSIGN", new_value, "@{}".format(t2))
self.i += 3
pass
# elif action == "\\funcRes":
# print('\033[91m' + "semantic action not implemented: :{}".format(action) + '\033[0m')
# pass
elif action == "\\lRelop":
temp = self.gettemp()
value = self.ss.pop()
self.pb[self.i] = ("ASSIGN", value, temp)
self.i += 1
self.ss.append(temp)
self.ss.append(1)
elif action == "\\eRelop":
temp = self.gettemp()
value = self.ss.pop()
self.pb[self.i] = ("ASSIGN", value, temp)
self.i += 1
self.ss.append(temp)
self.ss.append(0)
elif action == "\\relationalExpression":
op2 = self.ss.pop()
op = self.ss.pop()
op1 = self.ss.pop()
if op1 == "NULL" or op2 == "NULL":
self.semantic_errors.append("#{}\t:Semantic Error! Void type in operands.".format(line_number))
if op == 0:
op = "EQ"
elif op == 1:
op = "LT"
dest = self.gettemp()
self.pb[self.i] = (op, op1, op2, dest)
self.i += 1
self.ss.append(dest)
elif action == "\\param":
self.pb[self.i] = ("ASSIGN", "#0", self.data_pointer)
row = self.get_symbol_table_row(input)
row2 = self.get_symbol_table_row(self.current_func)
row2['num'] += 1
self.i += 1
self.func_def_stack[-1]["arguments"] += 1
elif action == "\\return":
'''return value is at the top of the stack.
we also have the address of our method at the return_scope
we need to assign value to return value (address + 4) and jump to where
return address (address + 8) shows'''
function_pointer = int(self.return_scope[-1])
value = self.ss.pop()
return_value_address = "{}".format(function_pointer + 4)
return_address_pointer = "@{}".format(function_pointer + 8)
self.pb[self.i] = ("ASSIGN", value, return_value_address)
self.pb[self.i + 1] = ("JP", return_address_pointer)
self.i += 2
self.func_def_stack[-1]["returns"] = True
elif action == "\\return_zero":
function_pointer = int(self.return_scope[-1])
return_address_pointer = "@{}".format(function_pointer + 8)
self.pb[self.i] = ("JP", return_address_pointer)
self.i += 1
elif action == "\\save":
boolean_result = self.ss[-1]
self.pb[self.i] = ("JPF", boolean_result, "X")
self.ss.append(self.i)
self.i += 1
elif action == "\\jpf_save":
address = self.ss.pop()
address2 = self.ss.pop()
self.pb[address] = ("JPF", address2, self.i + 1)
self.ss.append(self.i)
self.i += 1
elif action == "\\jp":
self.pb[self.ss.pop()] = ("JP", self.i)
elif action == "\\jpf":
address = self.ss.pop()
address2 = self.ss.pop()
self.pb[address] = ("JPF", address2, self.i)
elif action == "\\func_def":
self.no_more_global_variable = True
self.pb[self.i] = ("ASSIGN", "#0", self.data_pointer)
row = {'lexeme': input, 'address': self.data_pointer, 'type': 'func', 'num': 0, 'scope': self.scope}
self.current_func = input
self.symbol_table[len(self.symbol_table)+1] = row
self.return_scope.append(row['address'])
self.data_pointer += 4
self.func_def_stack.append({"id": len(self.symbol_table), "name": input, "returns": False, "arguments": 0})
if input != "main":
self.pb[self.i + 1] = ("JP",)
self.pb[self.i + 2] = ("ASSIGN", "#0", self.data_pointer) # return value.
self.pb[self.i + 3] = ("ASSIGN", "#0", self.data_pointer + 4) # return address.
self.incomplete_funcs.append(self.i + 1)
self.i += 3
self.data_pointer += 8
else:
# fill all the previous JPs
while (len(self.incomplete_funcs) > 0):
JP_address = self.incomplete_funcs.pop()
self.pb[JP_address] = ("JP", self.i + 1)
pass
self.scope += 1
self.i += 1
elif action == "\\start_list":
# self.ss.append(self.i)
# self.i += 1
pass
elif action == "\\append":
num = self.ss.pop()
self.pb[self.i] = ("ASSIGN", num, self.data_pointer)
self.data_pointer += 4
self.i += 1
elif action == "\\endList":
define_address = self.ss.pop()
first_element_address = define_address + 4
start_address = "#{}".format(first_element_address)
self.ss.append(define_address)
self.ss.append(start_address)
# self.data_pointer += 4
elif action == "\\while_label":
self.ss.append(self.i)
elif action == "\\calculate_primary":
'''
this will calculate an array's element location
var1 = arr[arr[1] - 1];
will result in
('MULT', '#4', '#1', '1000')
('ADD', '1000', 500, '1000')
('SUB', '@1000', '#1', '1004')
('MULT', '#4', '1004', '1008')
('ADD', '1008', 500, '1008')
('ASSIGN', '@1008', 516)
'''
t = self.gettemp()
index = self.ss.pop()
arr = self.ss.pop()
self.pb[self.i] = ("MULT", "#4", index, t)
self.pb[self.i + 1] = ("ADD", t, arr, t)
self.ss.append("@{}".format(t))
self.i += 2
pass
elif action == "\\while_save":
self.ss.append(self.i)
self.i = self.i + 1
elif action == "\\end_while":
self.pb[self.ss[-1]] = ("JPF", self.ss[-2], self.i + 1)
self.pb[self.i] = ("JP", self.ss[-3])
i = self.i + 1
self.ss.pop()
self.ss.pop()
self.ss.pop()
elif action == "\\end_func":
function_pointer = int(self.return_scope.pop())
for row in self.symbol_table:
if 'scope' in self.symbol_table[row]:
if self.symbol_table[row]['scope'] == self.scope:
self.symbol_table[row]['scope'] = -1
self.scope -= 1
func_info = self.func_def_stack.pop()
self.symbol_table[func_info["id"]]["returns"] = func_info["returns"]
self.symbol_table[func_info["id"]]["arguments"] = func_info["arguments"]
if func_info['name'] != 'main':
return_address_pointer = "@{}".format(function_pointer + 8)
self.pb[self.i] = ("JP", return_address_pointer)
self.i += 1
elif action == "\\while":
a = self.ss.pop()
b = self.ss.pop()
c = self.ss.pop()
self.pb[a] = ("JPF", b, self.i + 1)
self.pb[self.i] = ("JP", c)
self.inside_while_loop = False
break_list = self.while_scope_break.pop()
for break_address in break_list:
self.pb[break_address] = ("JP", self.i + 1)
continue_list = self.while_scope_continue.pop()
for continue_address in continue_list:
self.pb[continue_address] = ("JP", c)
self.i += 1
pass
elif action == "\\label":
self.ss.append(self.i)
self.while_scope_continue.append(list())
self.while_scope_break.append(list())
self.inside_while_loop = True
pass
elif action == "\\func_line":
func_row = self.get_symbol_table_row(self.current_func)
func_row['start_line'] = self.i
self.current_func = None
elif action == "\\arguments_count":
self.ss.append(0)
pass
elif action == "\\argument":
argument = self.ss[-1]
arguments_count = self.ss[-2]
func_name = self.ss[-3]
self.ss.pop()
self.ss.pop()
self.ss.pop()
if not self.is_address(argument):
self.semantic_errors.append("#{}\t:Semantic Error! '{}' is not defined appropriately."
.format(line_number, argument))
self.ss.append("NULL")
else: self.ss.append(argument)
self.ss.append(func_name)
self.ss.append(arguments_count+1)
elif action == "\\func_call":
arguments_count = self.ss.pop()
func_address = self.ss.pop()
if not self.is_address(func_address):
self.semantic_errors.append("#{}\t:Semantic Error! '{}' is not defined appropriately."
.format(line_number, func_address))
return
func_row = self.get_row_by_address(func_address)
#problematic
func_row = self.symbol_table[func_row]
if arguments_count != func_row['num']:
self.semantic_errors.append("#{}\t:Semantic Error! Mismatch in numbers of arguments of {}."
.format(line_number, func_row['lexeme']))
return
if func_row['lexeme'] == 'output':
self.pb[self.i] = ("PRINT", self.ss.pop())
self.i += 1
return
arg_address = func_address + 8 + func_row['num'] * 4
for _ in range(func_row['num']):
self.pb[self.i] = ("ASSIGN", self.ss.pop(), arg_address)
arg_address -= 4
self.i += 1
self.pb[self.i] = ("ASSIGN", "#{}".format(self.i + 2), func_address + 8)
self.i += 1
self.pb[self.i] = ("JP", func_row['start_line'])
self.i += 1
# self.ss.append("{}".format(func_address + 4))
elif action == "\\func_call_primary":
arguments_count = self.ss.pop()
func_address = self.ss.pop()
func_row = self.get_row_by_address(func_address)
if func_row == -1:
self.semantic_errors.append("#{}\t:Semantic Error! '{}' is not defined appropriately."
.format(line_number, func_address))
return
func_row = self.symbol_table[func_row]
if func_row['lexeme'] == 'output':
self.pb[self.i] = ("PRINT", self.ss.pop())
self.i += 1
return
if 'num' not in func_row:
self.semantic_errors.append("#{}\t:Semantic Error! '{}' is not defined appropriately."
.format(line_number, func_row['lexeme']))
return
elif arguments_count != func_row['num']:
self.semantic_errors.append("#{}\t:Semantic Error! Mismatch in numbers of arguments of {}."
.format(line_number, func_row['lexeme']))
return
arg_address = func_address + 8 + func_row['num'] * 4
for _ in range(func_row['num']):
self.pb[self.i] = ("ASSIGN", self.ss.pop(), arg_address)
arg_address -= 4
self.i += 1
self.pb[self.i] = ("ASSIGN", "#{}".format(self.i + 2), func_address + 8)
self.i += 1
self.pb[self.i] = ("JP", func_row['start_line'])
self.i += 1
if func_row["returns"]:
self.ss.append("{}".format(func_address + 4))
else:
self.ss.append("NULL")
elif action == "\\break":
if not self.inside_while_loop:
self.semantic_errors.append("#{}\t:Semantic Error! No 'while' found for 'break'."
.format(line_number, input))
return
self.while_scope_break[len(self.while_scope_break) - 1].append(self.i)
self.i += 1
elif action == "\\continue":
if len(self.while_scope_continue) == 0 or not self.inside_while_loop:
self.semantic_errors.append("#{}\t:Semantic Error! No 'while' found for 'continue'."
.format(line_number, input))
return
self.while_scope_continue[len(self.while_scope_continue) - 1].append(self.i)
self.i += 1
pass
elif action == "\\sem_main":
for key in self.symbol_table:
entry = self.symbol_table[key]
if entry['lexeme'] == 'main' and entry['scope'] == 0 and entry['type'] == "func":
break
else:
self.semantic_errors.append("#{}\t:Semantic Error! main function not found.".format(line_number))
elif action == "\\pidGlobal":
if self.no_more_global_variable:
self.semantic_errors.append("#{}\t:Semantic Error! {} is not defined appropriately."
.format(line_number, input))
self.previous_input = input
# else:
# print('\033[91m' + "unknown semantic action: :{}".format(action) + '\033[0m')
def dump(self):
'''
outputs program into output.txt
needs slight modification for final submition but works for now.
:return: None
'''
output = open('output.txt', 'w')
semantic_errors_output = open('semantic_errors.txt', 'w')
if len(self.semantic_errors) > 0:
output.write("The output code has not been generated")
output.close()
for error in self.semantic_errors:
semantic_errors_output.write(error + '\n')
return
else :
semantic_errors_output.write("The input program is semantically correct")
semantic_errors_output.close()
for key in range(len(self.pb)):
output.write("{}\t(".format(key))
counter = 0
for element in self.pb[key]:
output.write("{}".format(element))
counter += 1
if counter != 4:
output.write(", ")
while counter < 3:
output.write(", ")
counter += 1
output.write(")\n")
output.close()
'''
symbol table:
lexeme| address|
'''