Skip to content

Commit fa7927e

Browse files
committedMay 2, 2017
several bugs corrected
1 parent a89b65f commit fa7927e

16 files changed

+4238
-1663
lines changed
 

‎Makefile

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ all: $(addprefix ${DIR}/src/, ${PROGS})
1010
@echo "Standalone Lexer: ./bin/cpp_lexer.py ./tests/test1.cpp"
1111
@echo "Parser: ./bin/cpp_parser.py ./tests/test1.cpp"
1212
@echo "Note: Parser will create 'parse_tree.jpeg' in this directory"
13+
@chmod +x runcpp
14+
@echo "RUN executable in the current directory using command : ./runcpp filename"
15+
@echo "Note: Python version should be at least 3.6.0 or use venv"
1316

1417

1518

‎aa

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/bin/bash
2+
3+
echo "xxwxw $0 $1"
4+
echo $1

‎bin/cpp_lexer.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
reserved = {
88
'asm': 'ASM', 'auto': 'AUTO', 'bool': 'BOOL', 'break': 'BREAK', 'case': 'CASE', 'catch': 'CATCH',
99
'char': 'CHAR', 'class': 'CLASS', 'const': 'CONST', 'const_cast': 'CONST_CAST', 'continue': 'CONTINUE',
10-
'default': 'DEFAULT', 'delete': 'DELETE', 'do': 'DO', 'double': 'DOUBLE', 'dynamic_cast': 'DYNAMIC_CAST',
10+
'cout':'COUT','default': 'DEFAULT', 'delete': 'DELETE', 'do': 'DO', 'double': 'DOUBLE', 'dynamic_cast': 'DYNAMIC_CAST',
1111
'else': 'ELSE', 'enum': 'ENUM', 'explicit': 'EXPLICIT', 'extern': 'EXTERN', 'false': 'FALSE',
1212
'float': 'FLOAT', 'for': 'FOR', 'friend': 'FRIEND', 'goto': 'GOTO', 'if': 'IF', 'inline': 'INLINE', 'int': 'INT',
1313
'long': 'LONG', 'mutable': 'MUTABLE', 'namespace': 'NAMESPACE', 'new': 'NEW', 'operator': 'OPERATOR', 'private': 'PRIVATE',
@@ -20,7 +20,7 @@
2020

2121

2222
class MyLexer(object):
23-
23+
2424
tokens = [
2525
'IDENTIFIER', 'INTEGER', 'FLOATING', 'CHARACTER' ,'STRING', 'ELLIPSIS', 'SCOPE', 'DOT_STAR', 'ASS_ADD',
2626
'ASS_SUB', 'ASS_MUL', 'ASS_DIV', 'ASS_MOD', 'ASS_XOR', 'ASS_AND', 'ASS_OR', 'ASS_SHR', 'ASS_SHL', 'SHL', 'SHR',
@@ -73,22 +73,26 @@ def t_STRING(self,t):
7373

7474
def t_comment(self,t):
7575
r'(/\*(.|\n)*?\*/)|//.*\n'
76+
t.lexer.lineno += t.value.count('\n')
7677
pass
7778

79+
def t_NEWLINE(self,t):
80+
r'\n+'
81+
t.lexer.lineno += t.value.count("\n")
82+
7883

7984
# Preprocessor directive (ignored)
8085
def t_preprocessor(self,t):
81-
'\#.*'
82-
pass
86+
'\#[^\n]*\n'
87+
pass
8388

8489
def t_IDENTIFIER(self,t):
8590
r'[a-zA-Z_]([a-zA-Z_0-9]|(\\u[0-9A-Fa-f]{3})|(\\U[0-9A-Fa-f]{6}))*'
86-
print(t.value)
8791
t.type = reserved.get(t.value,'IDENTIFIER') # Check for reserved words
8892
return t
8993

9094

91-
t_ignore = ' \t\n\r\f\v'
95+
t_ignore = ' \t\r\f\v'
9296

9397
#print(t_ignore)
9498

@@ -111,8 +115,8 @@ def t_IDENTIFIER(self,t):
111115
t_NE = r'\!='
112116
t_LE = r'<='
113117
t_GE = r'>='
114-
t_LOG_AND = r'&&'
115118
t_LOG_OR = r'\|\|'
119+
t_LOG_AND = r'&&'
116120
t_INC = r'\+\+'
117121
t_DEC = r'--'
118122
t_ARROW_STAR = r'->\*'
@@ -147,4 +151,4 @@ def test(self,data):
147151
data = a.read()
148152
cpp_scanner.test(data)
149153
else:
150-
lex.runmain(cpp_scanner.lexer)
154+
lex.runmain(cpp_scanner.lexer)

‎bin/cpp_parser.py

+3,356-1,579
Large diffs are not rendered by default.

‎bin/exe.s

+224
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
.text
2+
.globl main
3+
main:
4+
5+
lw $t3, x_main
6+
li $t3, 3
7+
sw $t3, x_main
8+
lw $t4, y_main
9+
li $t4, 3
10+
sw $t4, y_main
11+
lw $t5, _t1_main
12+
lw $t5, x_main
13+
sw $t5, _t1_main
14+
lw $t6, _t2_main
15+
lw $t6, y_main
16+
sw $t6, _t2_main
17+
addu $fp, $sp, $0
18+
addi $a0, $sp, -8
19+
lw $t7, _t1_main
20+
sw $t7, 0($a0)
21+
addi $a0, $a0, -4
22+
lw $t8, _t2_main
23+
sw $t8, 0($a0)
24+
addi $a0, $a0, -4
25+
addu $sp, $a0, $0
26+
jal ackermann
27+
addu $sp, $fp, $0
28+
lw $t9, _t3_main
29+
move $t9, $v1
30+
sw $t9, _t3_main
31+
lw $s0, output_main
32+
lw $s0, _t3_main
33+
sw $s0, output_main
34+
li $v0, 4
35+
la $a0, cout_59
36+
syscall
37+
li $v0, 1
38+
lw $a0, output_main
39+
syscall
40+
lw $ra, 0($sp)
41+
lw $fp, -4($sp)
42+
li $v0, 10
43+
syscall
44+
45+
46+
47+
ackermann:
48+
addi $sp, $sp, -36
49+
sw $ra, 0($sp)
50+
sw $fp, -4($sp)
51+
addu $fp, $0, $sp
52+
lw $t0, count_global
53+
addi $t0, $t0, 1
54+
sw $t0, count_global
55+
li $v0, 4
56+
la $a0, cout_3
57+
syscall
58+
li $v0, 1
59+
lw $a0, 44($sp)
60+
syscall
61+
li $v0, 4
62+
la $a0, cout_5
63+
syscall
64+
li $v0, 1
65+
lw $a0, 40($sp)
66+
syscall
67+
li $v0, 4
68+
la $a0, cout_7
69+
syscall
70+
li $v0, 1
71+
lw $a0, count_global
72+
syscall
73+
li $v0, 4
74+
la $a0, cout_9
75+
syscall
76+
lw $t1, 44($sp)
77+
blt $t1, 0, L_14
78+
b L_12
79+
L_12:
80+
lw $t2, 40($sp)
81+
blt $t2, 0, L_14
82+
b L_16
83+
L_14:
84+
lw $t3, 36($sp)
85+
li $t3, -1
86+
sw $t3, 36($sp)
87+
lw $t4, 36($sp)
88+
addu $v1, $t4, $0
89+
lw $ra, 0($sp)
90+
lw $fp, -4($sp)
91+
jr $ra
92+
L_16:
93+
lw $t5, 44($sp)
94+
beq $t5, 0, L_18
95+
b L_21
96+
L_18:
97+
lw $t6, 36($sp)
98+
lw $t7, 40($sp)
99+
addi $t6, $t7, 1
100+
sw $t6, 36($sp)
101+
lw $t8, 32($sp)
102+
lw $t8, 36($sp)
103+
sw $t8, 32($sp)
104+
lw $t9, 32($sp)
105+
addu $v1, $t9, $0
106+
lw $ra, 0($sp)
107+
lw $fp, -4($sp)
108+
jr $ra
109+
L_21:
110+
lw $s0, 40($sp)
111+
beq $s0, 0, L_23
112+
b L_32
113+
L_23:
114+
lw $s1, 36($sp)
115+
lw $s2, 44($sp)
116+
li $s3, 1
117+
sub $s1, $s2, $s3
118+
sw $s1, 36($sp)
119+
lw $s4, 32($sp)
120+
lw $s4, 36($sp)
121+
sw $s4, 32($sp)
122+
lw $s5, 28($sp)
123+
li $s5, 1
124+
sw $s5, 28($sp)
125+
addu $fp, $sp, $0
126+
addi $a0, $sp, -8
127+
lw $s6, 32($sp)
128+
sw $s6, 0($a0)
129+
addi $a0, $a0, -4
130+
lw $s7, 28($sp)
131+
sw $s7, 0($a0)
132+
addi $a0, $a0, -4
133+
addu $sp, $a0, $0
134+
jal ackermann
135+
addu $sp, $fp, $0
136+
lw $t0, 24($sp)
137+
move $t0, $v1
138+
sw $t0, 24($sp)
139+
lw $t1, 20($sp)
140+
lw $t1, 24($sp)
141+
sw $t1, 20($sp)
142+
lw $t2, 20($sp)
143+
addu $v1, $t2, $0
144+
lw $ra, 0($sp)
145+
lw $fp, -4($sp)
146+
jr $ra
147+
L_32:
148+
lw $t3, 36($sp)
149+
lw $t4, 44($sp)
150+
li $t5, 1
151+
sub $t3, $t4, $t5
152+
sw $t3, 36($sp)
153+
lw $t6, 32($sp)
154+
lw $t7, 40($sp)
155+
li $t8, 1
156+
sub $t6, $t7, $t8
157+
sw $t6, 32($sp)
158+
lw $t9, 28($sp)
159+
lw $t9, 44($sp)
160+
sw $t9, 28($sp)
161+
lw $s0, 24($sp)
162+
lw $s0, 32($sp)
163+
sw $s0, 24($sp)
164+
addu $fp, $sp, $0
165+
addi $a0, $sp, -8
166+
lw $s1, 28($sp)
167+
sw $s1, 0($a0)
168+
addi $a0, $a0, -4
169+
lw $s2, 24($sp)
170+
sw $s2, 0($a0)
171+
addi $a0, $a0, -4
172+
addu $sp, $a0, $0
173+
jal ackermann
174+
addu $sp, $fp, $0
175+
lw $s3, 20($sp)
176+
move $s3, $v1
177+
sw $s3, 20($sp)
178+
lw $s4, 16($sp)
179+
lw $s4, 36($sp)
180+
sw $s4, 16($sp)
181+
lw $s5, 12($sp)
182+
lw $s5, 20($sp)
183+
sw $s5, 12($sp)
184+
addu $fp, $sp, $0
185+
addi $a0, $sp, -8
186+
lw $s6, 16($sp)
187+
sw $s6, 0($a0)
188+
addi $a0, $a0, -4
189+
lw $s7, 12($sp)
190+
sw $s7, 0($a0)
191+
addi $a0, $a0, -4
192+
addu $sp, $a0, $0
193+
jal ackermann
194+
addu $sp, $fp, $0
195+
lw $t0, 8($sp)
196+
move $t0, $v1
197+
sw $t0, 8($sp)
198+
lw $t1, 4($sp)
199+
lw $t1, 8($sp)
200+
sw $t1, 4($sp)
201+
lw $t2, 4($sp)
202+
addu $v1, $t2, $0
203+
lw $ra, 0($sp)
204+
lw $fp, -4($sp)
205+
jr $ra
206+
lw $ra, 0($sp)
207+
lw $fp, -4($sp)
208+
jr $ra
209+
210+
211+
.data
212+
213+
count_global: .word 0
214+
cout_3: .asciiz "x: "
215+
cout_5: .asciiz "y: "
216+
cout_7: .asciiz "count: "
217+
cout_9: .asciiz "\n"
218+
cout_59: .asciiz "ackermann: "
219+
x_main: .word 0
220+
y_main: .word 0
221+
_t1_main: .word 0
222+
_t2_main: .word 0
223+
_t3_main: .word 0
224+
output_main: .word 0

‎runcpp

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#!/bin/bash
2+
3+
if [ "$#" -ne 1 ]; then
4+
echo "Usage: ./runcpp filename"
5+
exit
6+
fi
7+
8+
python ./src/cpp_parser.py $1
9+
spim -f ./bin/exe.s

‎src/c.s

+457
Large diffs are not rendered by default.

‎src/codegen.py

+23-21
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,10 @@ def get_local_ids(self, scope_name):
101101
if s != "NULL":
102102
if st.ScopeList[s].get("parent") == _scope:
103103
scope_q.append(str(s))
104-
size = 0
105-
for i in reversed(self.local_ids):
106-
size = self.local_ids[i]["offset"]
107-
break
104+
size = self.stack_space
105+
#for i in reversed(self.local_ids):
106+
# size = self.local_ids[i]["offset"]
107+
# break
108108
for j in self.local_ids:
109109
if self.local_ids[j]['location'] == "($sp)":
110110
if self.local_ids[j]["offset"] < 0:
@@ -270,6 +270,7 @@ def parse_tac(self):
270270
# print(self.general_regs)
271271
if quad[0] in ["function"]:
272272
inside_func = True
273+
self.stack_space = st.ScopeList[quad[1]]["offset"]
273274
self.get_local_ids(quad[1])
274275
#print(quad,self.local_ids)
275276
#print(quad,self.local_ids,"\n\n")
@@ -281,12 +282,12 @@ def parse_tac(self):
281282
else:
282283
code_list = self.functions # reference functions code list
283284
is_main = False
284-
size = 0
285-
for j in reversed(self.local_ids):
286-
size = self.local_ids[j]["offset"]
287-
break
285+
#size = 0
286+
#for j in reversed(self.local_ids):
287+
# size = self.local_ids[j]["offset"]
288+
# break
288289
code_list.append([quad[1] + ":"])
289-
self.callee_seq(size,code_list)
290+
self.callee_seq(self.stack_space,code_list)
290291

291292
else:
292293
if not inside_func: # TAC of Global scope
@@ -296,10 +297,10 @@ def parse_tac(self):
296297
code_list.append([self.label + str(i) + ":"])
297298
if quad[0] in ["end"]:
298299
inside_func = False
299-
size = 0
300-
for i in reversed(self.local_ids):
301-
size = self.local_ids[i]["offset"]
302-
break
300+
#size = 0
301+
#for i in reversed(self.local_ids):
302+
# size = self.local_ids[i]["offset"]
303+
# break
303304
self.return_seq(code_list)
304305
if is_main:
305306
is_main = False
@@ -343,12 +344,13 @@ def parse_tac(self):
343344
pass
344345

345346
elif quad[0] == "ret":
346-
qtype = self.local_ids[quad[1]]["type"] if quad[1] in self.local_ids else self.global_ids[quad[1]]["type"]
347-
reg = self.get_register(quad[1], qtype, code_list)
348-
if qtype in ["float", "double"]:
349-
code_list.append(["mov.s", "$f0" + ",", reg]) #Update frame pointer
350-
else:
351-
code_list.append(["addu", "$v1" + ",", reg + ",","$0"]) #Update frame pointer
347+
if quad[1] != "":
348+
qtype = self.local_ids[quad[1]]["type"] if quad[1] in self.local_ids else self.global_ids[quad[1]]["type"]
349+
reg = self.get_register(quad[1], qtype, code_list)
350+
if qtype in ["float", "double"]:
351+
code_list.append(["mov.s", "$f0" + ",", reg]) #Update frame pointer
352+
else:
353+
code_list.append(["addu", "$v1" + ",", reg + ",","$0"]) #Update frame pointer
352354
self.return_seq(code_list)
353355
if is_main:
354356
code_list.append(["li", "$v0" + ",", self.syscall["exit"]])
@@ -357,7 +359,7 @@ def parse_tac(self):
357359
code_list.append(["jr", "$ra"])
358360

359361
elif quad[0] == "cout":
360-
print("COUT: ", quad)
362+
#print("COUT: ", quad)
361363
self.print_stdout(quad[1], quad[2], code_list)
362364
elif quad[0] == "if":
363365
self.op_codes(self.label + str(quad[5]), None, quad[1], quad[2], quad[3], code_list)
@@ -897,7 +899,7 @@ def gen_data_section(self):
897899

898900
def print_sections(self):
899901
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n")
900-
with open('c1.asm', 'w') as fi:
902+
with open('./bin/exe.s', 'w') as fi:
901903
print(".text", file=fi)
902904
print(".globl main", file=fi)
903905
print("main:\n", file=fi)

‎src/cpp_parser.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ def add_children(n,name):
5151
children = orphan_children[-n:]
5252
for child in children:
5353
if child == None:
54-
print("Error")
54+
#print("Error")
55+
pass
5556
graph.add_edge(pydot.Edge(node_a, child))
5657
orphan_children.remove(child)
5758
orphan_children.append(node_a)
@@ -289,7 +290,7 @@ def p_nested_id2(p):
289290
st.print_error(p.lineno(1), {}, 40, p[0]["name"], "namespace", "::".join(st.scope_transitions[1:] + [p[1]["name"]]))
290291
st.is_ns_member = False
291292
st.currentScope = st.scope_transitions.pop()
292-
print("[PARSER] popped scope: ", st.currentScope, st.scope_transitions)
293+
#print("[PARSER] popped scope: ", st.currentScope, st.scope_transitions)
293294
pass
294295

295296
def p_scoped_id1(p):
@@ -2026,7 +2027,7 @@ def p_compound_statement1(p):
20262027
stack_space = st.ScopeList[st.currentScope]["offset"]
20272028
SymbolTable.endScope()
20282029
try:
2029-
print("[PARSER] popped function : %s" % st.function_list[0]["name"])
2030+
#print("[PARSER] popped function : %s" % st.function_list[0]["name"])
20302031
SymbolTable.updateIDAttr(st.function_list[-1]["name"], "offset", stack_space)
20312032
st.function_list.pop()
20322033
except:
@@ -2331,6 +2332,8 @@ def p_jump_statement3(p):
23312332
if p[2] is None:
23322333
if ' '. join(func["type"]) != "void":
23332334
st.print_error(p.lineno(1), {}, 36, func["name"], ' '. join(func["type"]))
2335+
if not st.Error:
2336+
st.ScopeList[st.currentScope]["tac"].emit(["ret", ""])
23342337
return
23352338
if type(p[2]) is list:
23362339
expr = p[2][-1]
@@ -2381,7 +2384,7 @@ def p_compound_declaration1(p):
23812384
st.currentScope = st.previous_scope
23822385
st.previous_scope = ""
23832386
try:
2384-
print("[PARSER] popped namespace : %s" % st.namespace_list[-1]["name"])
2387+
#print("[PARSER] popped namespace : %s" % st.namespace_list[-1]["name"])
23852388
st.namespace_list.pop()
23862389
except:
23872390
pass
@@ -4373,7 +4376,7 @@ def p_marker_F(p):
43734376
"marker_F : empty"
43744377
if not st.Error :
43754378
func = st.function_list[-1]
4376-
print(func)
4379+
#print(func)
43774380
st.ScopeList[st.currentScope]["tac"].emit(["function", func["name"], ":" ] )
43784381
#for param in func["parameters"]:
43794382
# st.ScopeList[st.currentScope]["tac"].emit(["param", st.simple_type_specifier[" ".join(param["type"])]["equiv_type"],str(param["name"]) + "_" + str(func["name"])])
@@ -4416,7 +4419,7 @@ def p_error(p):
44164419
#graph.write_dot('parse_tree.dot')
44174420
f = open("parse_tree.dat","w")
44184421
f.write(graph.to_string())
4419-
print("================================================================================================\n\n")
4422+
print("==========================================TAC CODE========================================\n\n")
44204423
if not st.Error :
44214424
st.print_table()
44224425
asm = cg.CodeGen(st.ScopeList["global"]["tac"])

‎src/symtable.py

+37-27
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,8 @@ def insertID(self, lineno, name, id_type, types=None, specifiers=[], num=1, valu
164164
currtable = ScopeList[currentScope]["table"]
165165
#print("[Symbol Table]", currtable.symtab)
166166
if currtable.lookup(str(name)): # No need to check again
167-
print("[Symbol Table] Entry already exists")
167+
#print("[Symbol Table] Entry already exists")
168+
pass
168169
else:
169170
currtable.symtab[str(name)] = {
170171
"name" : str(name),
@@ -191,19 +192,26 @@ def insertID(self, lineno, name, id_type, types=None, specifiers=[], num=1, valu
191192
check_specifier(lineno, currtable.symtab[str(name)]["specifier"], name)
192193
if types is None:
193194
warning = "(warning: Type is None)"
194-
print("[Symbol Table] ", warning, " Inserting new identifier: ", name, " type: ", types, "specifier: ", specifiers)
195+
#print("[Symbol Table] ", warning, " Inserting new identifier: ", name, " type: ", types, "specifier: ", specifiers)
195196
#ScopeList[-1]["table"].numVar += 1
196197

197198
def insertTemp(self, name, id_type, scope_name, types):
198199
if simple_type_specifier[' '.join(types)]["equiv_type"] in ["bool"]:
199200
types = ["int"]
200201
currtable = ScopeList[scope_name]["table"]
201202
if currtable.lookup(str(name)): # No need to check again
202-
print("[Symbol Table] Entry already exists")
203+
#print("[Symbol Table] Entry already exists")
204+
pass
203205
else:
204206
size = 4
205-
ScopeList[scope_name]["offset"] += size
206-
offset = ScopeList[scope_name]["offset"]
207+
if ScopeList[currentScope]["scope_type"] not in ["global", "namespace_scope", "class_scope"]:
208+
#ScopeList[scope_name]["offset"] += size
209+
#offset = ScopeList[scope_name]["offset"]
210+
ScopeList[currentScope]["offset"] += size
211+
offset = ScopeList[currentScope]["offset"]
212+
else:
213+
offset = 0
214+
207215
if (types is None) or (len(types) == 0):
208216
print("Something is Wrong!!")
209217
currtable.symtab[str(name)] = {
@@ -239,13 +247,13 @@ def addIDAttr(name, attribute, value):
239247
currtable.symtab[str(name)].update({attribute : value})
240248
if attribute not in AttrList:
241249
AttrList.append(attribute)
242-
print("[Symbol Table] Adding attribute of identifier: ", name, " attribute: ", attribute, "value: ", value)
250+
#print("[Symbol Table] Adding attribute of identifier: ", name, " attribute: ", attribute, "value: ", value)
243251

244252
@staticmethod
245253
def updateIDAttr(name, attribute, value):
246254
currtable = ScopeList[currentScope]["table"]
247255
currtable.symtab[str(name)].update({attribute : value})
248-
print("[Symbol Table] Updating attribute of identifier: ", name, " attribute: ", attribute, "value: ", value)
256+
#print("[Symbol Table] Updating attribute of identifier: ", name, " attribute: ", attribute, "value: ", value)
249257

250258
def addScopeAttr(self,attribute,value):
251259
self.scope.update({attribute:value})
@@ -264,7 +272,7 @@ def addScope(self, name, scope_type):
264272
#new_scope["tac"].startquad = ScopeList[currentScope]["tac"].nextquad
265273
currentScope = str(name)
266274
SymTab()
267-
print("[Symbol Table](addScope) Adding New Scope: ", name)
275+
#print("[Symbol Table](addScope) Adding New Scope: ", name)
268276

269277
def changeScope(self, name):
270278
global currentScope
@@ -275,19 +283,20 @@ def endScope(self):
275283
Changes current scope to parent scope when '}' is received
276284
"""
277285
global currentScope
278-
print("[Symbol Table](endScope) End Scope of: ", currentScope, end='')
286+
#print("[Symbol Table](endScope) End Scope of: ", currentScope, end='')
279287
#print("The scope",currentScope,"nextquad was ", ScopeList[currentScope]["tac"].nextquad )
280288
# print(ScopeList[currentScope]["tac"].code)
281289

282290
ScopeList[ScopeList[currentScope]["parent"]]["tac"].code += ScopeList[currentScope]["tac"].code
283291
ScopeList[ScopeList[currentScope]["parent"]]["tac"].nextquad = ScopeList[currentScope]["tac"].nextquad
284292
ScopeList[ScopeList[currentScope]["parent"]]["tac"].temp_count = 0
285-
if ScopeList[currentScope]["parent"] not in ["global", "namespace", "class"]:
293+
if ScopeList[ScopeList[currentScope]["parent"]]["scope_type"] not in ["global", "namespace", "class"]:
286294
ScopeList[ScopeList[currentScope]["parent"]]["offset"] = ScopeList[currentScope]["offset"]
295+
287296
currentScope = ScopeList[currentScope]["parent"]
288297
#print("The scope",currentScope,"nextquad is ", ScopeList[currentScope]["tac"].nextquad )
289298

290-
print(" Current Scope: ", currentScope)
299+
#print(" Current Scope: ", currentScope)
291300
if ScopeList[currentScope] is None:
292301
print("[Symbol Table] Error: This line should not be printed")
293302

@@ -313,15 +322,16 @@ def check_datatype(lineno, types, name, id_type):
313322
if id_type not in ["function", "class"]:
314323
size = simple_type_specifier[input_type]["size"]
315324
if currtable.symtab[str(name)]["star"] > 0:
316-
size = 8
325+
size = 4
317326
SymTab.addIDAttr(name,"size", size * currtable.symtab[str(name)]["num"])
318-
if is_parameter:
319-
#parameter_offset -= (size * currtable.symtab[str(name)]["num"])
320-
parameter_offset -= 4
321-
SymTab.updateIDAttr(name, "offset", parameter_offset)
322-
else:
323-
ScopeList[currentScope]["offset"] += (size * currtable.symtab[str(name)]["num"])
324-
SymTab.updateIDAttr(name, "offset", ScopeList[currentScope]["offset"])
327+
if ScopeList[currentScope]["scope_type"] not in ["global", "namespace_scope", "class_scope"]:
328+
if is_parameter:
329+
#parameter_offset -= (size * currtable.symtab[str(name)]["num"])
330+
parameter_offset -= 4
331+
SymTab.updateIDAttr(name, "offset", parameter_offset)
332+
else:
333+
ScopeList[currentScope]["offset"] += (size * currtable.symtab[str(name)]["num"])
334+
SymTab.updateIDAttr(name, "offset", ScopeList[currentScope]["offset"])
325335
return True
326336
else :
327337
print_error(lineno, {}, 46)
@@ -619,9 +629,8 @@ def print_error(lineno, id1, errno, *args):
619629
print(color.cline, lineno, color.cerror + " invalid conversion from \'const char*\' to \'%s\'" % args[0])
620630
pass
621631

622-
def print_table():
632+
def print_table(show=False):
623633
pp = pprint.PrettyPrinter(indent=4)
624-
print(AttrList)
625634
with open("symtab.csv", 'w') as outf:
626635
writer = csv.DictWriter(outf, AttrList)
627636
writer.writeheader()
@@ -630,12 +639,13 @@ def print_table():
630639
if ScopeList[scope]["table"].symtab:
631640
for k in ScopeList[scope]["table"].symtab.keys():
632641
writer.writerows([dict(ScopeList[scope]["table"].symtab[k])])
633-
for scope in ScopeList.keys():
634-
if scope != "NULL":
635-
print("Scope Name:", scope, ", ", "Scope Type:", ScopeList[scope]["scope_type"])
636-
if ScopeList[scope]["table"].symtab:
637-
pp.pprint(ScopeList[scope]["table"].symtab)
638-
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
642+
if show:
643+
for scope in ScopeList.keys():
644+
if scope != "NULL":
645+
print("Scope Name:", scope, ", ", "Scope Type:", ScopeList[scope]["scope_type"])
646+
if ScopeList[scope]["table"].symtab:
647+
pp.pprint(ScopeList[scope]["table"].symtab)
648+
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
639649

640650
def print_tac():
641651
ScopeList["global"]["tac"].print_code()

‎tests/binary_tree.cpp

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#include<stdio.h>
2+
3+
void printInorder(int start,int end);
4+
void printPostorder(int start,int end);
5+
void printPreorder(int start,int end);
6+
7+
8+
int arr[7] = {4, 2, 6, 1, 3, 5, 7};
9+
int arr_size = 7;
10+
11+
int main()
12+
{
13+
cout<<"The PreOrder Traversal is:\n";
14+
//printf("The InOrder Traversal is: \n");
15+
printPreorder(0, arr_size-1);
16+
17+
cout << "\n";
18+
19+
cout<<"The InOrder Traversal is:\n";
20+
//printf("The InOrder Traversal is: \n");
21+
printInorder(0, arr_size-1);
22+
23+
cout << "\n";
24+
25+
cout<<"The PostOrder Traversal is:\n";
26+
//printf("The InOrder Traversal is: \n");
27+
printPostorder(0, arr_size-1);
28+
return 0;
29+
}
30+
31+
void printInorder(int start,int end)
32+
{
33+
if(start > end){
34+
return;
35+
}
36+
int val;
37+
/*Printing the left subtree*/
38+
printInorder(start*2+1,end);
39+
40+
/*printing present value*/
41+
val = arr[start];
42+
cout << val << " ";
43+
//printf("%d ", a[start]);
44+
/*Printing the right subtree*/
45+
printInorder(start*2+2,end);
46+
}
47+
48+
void printPostorder(int start,int end)
49+
{
50+
if(start > end){
51+
return;
52+
}
53+
int val;
54+
/*Printing the left subtree*/
55+
printInorder(start*2+1,end);
56+
/*Printing the right subtree*/
57+
printInorder(start*2+2,end);
58+
59+
/*printing present value*/
60+
val = arr[start];
61+
cout << val << " ";
62+
//printf("%d ", a[start]);
63+
}
64+
65+
void printPreorder(int start,int end)
66+
{
67+
if(start > end){
68+
return;
69+
}
70+
int val;
71+
/*printing present value*/
72+
val = arr[start];
73+
cout << val << " ";
74+
//printf("%d ", a[start]);
75+
76+
/*Printing the left subtree*/
77+
printInorder(start*2+1,end);
78+
/*Printing the right subtree*/
79+
printInorder(start*2+2,end);
80+
}

‎tests/fibonacci.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ int main(){
22
int a = 0;
33
int b = 1;
44
int c, i;
5-
int n = 1;
5+
int n = 5;
66
for (i = 2; i <= n; i++)
77
{
88
c = a + b;
99
a = b;
1010
b = c;
1111
}
1212
cout << c;
13-
}
13+
}

‎tests/mutual_recursion.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ int odd(int n){
2424

2525
int main(){
2626
int n = 1001;
27+
cout << "N: " << n;
28+
cout << "\n";
2729
int output;
2830
output = even(n);
2931
cout << "even: " << output;

‎tests/quicksort.cpp

+10-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#include <stdio.h>
2-
//int a[10] = {23, 5, 3, 56, 77, 37, 47, 10, 88, 1};
3-
int a[2] = {45,78};
2+
int a[10] = {23, 5, 3, 56, 77, 37, 47, 10, 88, 1};
3+
//int a[2] = {45,78};
44
void swap(int i,int j){
55
int c=a[i];
66
a[i]=a[j];
@@ -13,8 +13,10 @@ int partition(int pivot,int l,int r){ //Partition the array such that all value
1313
int start=l;
1414
int end=r;
1515
int x=pivot;
16-
int ste = a[start];
17-
int ene = a[end];
16+
int ste;
17+
ste = a[start];
18+
int ene;
19+
ene = a[end];
1820

1921
//cout << "l: " << l;
2022

@@ -47,25 +49,21 @@ int partition(int pivot,int l,int r){ //Partition the array such that all value
4749

4850
void quick_sort(int l,int r){
4951
if(l<r){
50-
cout << "quick_sort";
51-
cout << "l: " << l;
52-
cout << "r: " << r;
53-
//cout << "\n";
52+
int t;
53+
t = a[l];
5454
int i = partition(a[l],l,r);
55-
cout << "quick_sort_partiton";
56-
cout << "i: " << i;
5755
quick_sort(l,i-1);
5856
quick_sort(i+1,r);
5957
}
6058
}
6159

6260
int main(){
63-
int n = 2;
61+
int n = 10;
6462
int t;
6563
cout << "n: " << n;
6664
cout << "\n";
6765
quick_sort(0, n-1);
68-
//cout << "Sorted Array: ";
66+
cout << "Sorted Array: ";
6967
for (int i = 0; i < n; i++){
7068
t = a[i];
7169
//printf("%d ", t);

‎tests/raphson.cpp

+4-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ void newtonRaphson(float x)
2222

2323
float h = func(x) / derivFunc(x);
2424
//cout << "h1: " << h;
25-
printf("The h is : %f ",h);
25+
//printf("The h is : %f ",h);
2626

2727
if (h < 0.0){
2828
h = h*(-1.0);
@@ -31,13 +31,13 @@ void newtonRaphson(float x)
3131
{
3232
h = func(x)/derivFunc(x);
3333
//cout << "h2: " << h;
34-
printf("The h2 : %f ",h);
34+
//printf("The h2 : %f ",h);
3535

3636
x = x - h;
3737
}
3838

39-
printf("The value of the root is : %f ",x);
40-
//cout << "The value of the root is : " << x;
39+
//printf("The value of the root is : %f ",x);
40+
cout << "The value of the root is : " << x;
4141
}
4242

4343
int main()

‎tests/sample_test.cpp

+6-4
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,11 @@ int main()
9090
//int i = 2;
9191
//int [1] = {1};
9292
int sum = 9;
93-
94-
//sum = test(3);
95-
int *y;
93+
int a[2] = {33, 55};
94+
int l =1;
95+
sum = test(a[l]);
96+
cout << "sum: " << sum;
97+
/*int *y;
9698
int **x;
9799
y = &sum;
98100
x = &y;
@@ -106,7 +108,7 @@ int main()
106108
int a[3] = {1,2,3};
107109
int pp;
108110
pp = a[2];
109-
cout << "pp: " << pp;
111+
cout << "pp: " << pp;*/
110112
return 0;
111113
}
112114

0 commit comments

Comments
 (0)
Please sign in to comment.