Skip to content

Commit

Permalink
Final commit for submission
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-chauhan committed Apr 8, 2021
1 parent 03a162f commit 587fc91
Show file tree
Hide file tree
Showing 18 changed files with 81 additions and 50 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ src/parser.out
*.png
*.dot
*.ps
*.out
*.out
*.csv
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ all:
$(PYTHON) -m py_compile $(SRC)/lexer.py $(SRC)/parser.py
$(PYTHON) $(SRC)/parser.py

ln -sf $(PWD)/$(SRC)/parser_dot.py $(BIN)/parser
ln -sf $(PWD)/$(SRC)/parse.py $(BIN)/parser
chmod u+x $(BIN)/parser

dep:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ $ make
$ make clean # For removing the build
```

### For generating dot file (parser)
### For generating dot file (parser) and dump of symbol table in `csv` format
```bash
$ ./bin/parser -o myAST.dot /tests/helloworld.c

# For generates a postscript program containing the drawing of the tree
$ dot -Tps myAST.dot -o myAST.ps
# Alternatively, for generating .png file
$ ./bin/parser -o myAST.dot -png /tests/helloworld.c
$ ./bin/parser -o myAST.dot --png /tests/helloworld.c
```


Expand Down
13 changes: 5 additions & 8 deletions src/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@

import sys, argparse, pydot
from argparse import ArgumentParser
from parser import parser, lexer, symtable


def arg_parser():

argparser = ArgumentParser(prog='gcc_lite',
description='Parser for C programs')
description='Parser and Semantic checker for C programs')

argparser.add_argument('input', type=str,
help='C program file to parse')

argparser.add_argument('-v', '--verbose', action="store_true",
help='Force output on stdout')

argparser.add_argument('-d', '--debug', action="store_true",
help='Generate complete syntax tree for debugging purpose')
# argparser.add_argument('-d', '--debug', action="store_true",
# help='Generate complete syntax tree for debugging purpose')

argparser.add_argument('-o', '--out', type=str,
help='File to store generated DOT file')
Expand All @@ -42,17 +43,13 @@ def arg_parser():
with open(args.input, 'r') as f:
ifile = f.read()

if args.debug:
from parser_debug import parser, lexer
else:
from parser import parser, lexer, symtable, compilation_err

lexer.filename = args.input
lexer.lines = ifile.split("\n")

syntax_tree = parser.parse(ifile)

if syntax_tree is None:
if syntax_tree is None or parser.compilation_err:
exit(1)

graph = pydot.Dot('gcc_lite: Abstract Syntax Tree', graph_type='digraph')
Expand Down
35 changes: 28 additions & 7 deletions src/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ def p_type_specifier_typedef(p):
''' type_specifier : TYPE_NAME
'''
p[0] = p[1]
# print(p[1], symtable.cur_scope().aliases)
lookup_alias = symtable.lookup_alias(p[1])
p.type = lookup_alias._type

Expand Down Expand Up @@ -708,6 +709,8 @@ def p_selection_statement(p):
'''
if len(p)==6:
p[0] = SelectionStmt(p[1], p[3], p[5])
elif len(p) == 7:
p[0] = SelectionStmt(p[1], p[3], p[6])
else:
p[0] = SelectionStmt(p[1], p[3], p[5], p[7])

Expand Down Expand Up @@ -879,7 +882,7 @@ def _get_size(self):
raise Exception('TODO')

class Function(_BASENODE):
def __init__(self, ret_type, name, args, is_ellipsis=False, is_defined=False):
def __init__(self, ret_type, name, args, is_ellipsis=False, is_declared=False):
super().__init__()
self.ret_type = ret_type # should be VarType
self.name = name # str
Expand Down Expand Up @@ -1145,6 +1148,8 @@ def get_type(self):

class UnaryExpr(OpExpr):
def __init__(self, ops, rhs):
self.ops_type['++'] = ['int', 'char', 'float']
self.ops_type['--'] = ['int', 'char', 'float']
super().__init__(None, ops, rhs)
self.get_type()

Expand Down Expand Up @@ -1586,6 +1591,7 @@ def __init__(
self.name = name
self.param_list = param_list
self.is_ellipsis = is_ellipsis
self.arr_offset = None

class Declaration(_BaseDecl):
def __init__(
Expand Down Expand Up @@ -1995,8 +2001,14 @@ def lookup_struct(self, name):
scope = scope.parent
return None

def lookup_alias(self, id):
return self.cur_scope().lookup_alias(id)
def lookup_alias(self, name):
scope = self.cur_scope()
while scope:
if scope.lookup_alias(name):
return scope.aliases[name]
scope = scope.parent
return None
# return self.cur_scope().lookup_alias(id)

def lookup_func(self, name):
if name in self.function:
Expand All @@ -2010,7 +2022,7 @@ def add_var(self, name, vtype, is_static = False):
scope = self.global_scope if is_static else self.cur_scope()
if scope.lookup_var(name):
compilation_err.append('Redeclaration of variable named {}'.format(name))
# parser.error = compilation_err[-1]
parser.error = compilation_err[-1]
parser_error()
return

Expand All @@ -2019,7 +2031,7 @@ def add_var(self, name, vtype, is_static = False):
def add_struct(self, name, struct_type):
if self.cur_scope().lookup_struct(name):
compilation_err.append('Redeclaration of struct named {}'.format(name))
# parser.error = compilation_err[-1]
parser.error = compilation_err[-1]
parser_error()
return

Expand All @@ -2034,13 +2046,16 @@ def add_typedef(self, alias, actual):
pass
else:
compilation_err.append('Redeclaration of type/alias named {}'.format(alias))
# parser.error = compilation_err[-1]
parser.error = compilation_err[-1]
parser_error()

def add_func(self, func) -> None:
if func.name in self.function:
func_ = self.function[func.name]
if func_.ret_type == func.ret_type and func_.args == func.args and func_.is_ellipsis == func.is_ellipsis:
return
compilation_err.append('Redeclaration of function named {}'.format(func.name))
# parser.error = compilation_err[-1]
parser.error = compilation_err[-1]
parser_error()
return

Expand All @@ -2050,6 +2065,8 @@ def dump_csv(self, filename):
with open(filename, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Table Id', 'Parent Id', 'Table Type', 'Symbol Id', 'Symbol Name', 'Symbol Type', 'Symbol Other Information'])
writer.writerow(['======','======','======','======','======','======','======'])

scope_id = 0
parent_id = 'null'
idx = 0
Expand Down Expand Up @@ -2079,6 +2096,10 @@ def dump_csv(self, filename):
if scope_id != len(self.all_scope):
parent_id = self.all_scope[scope_id].parent.scope_id
idx = 0
if scope_id != len(self.all_scope):
# writer.writerow(['','','','','','',''])
writer.writerow(['======','======','======','======','======','======','======'])
# writer.writerow(['','','','','','',''])

symtable = SymbolTable()
compilation_err = []
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
17 changes: 11 additions & 6 deletions tests/helloworld.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
int main(){
int x;
int y = 2+5;
char s[15] = "Hello World";
char a = -1;
return 0;
int f(int a, int b)
{
return f(a, b);
}

int main()
{
int *x;
typedef int xyz;
xyz d = 1;
return 0 ;
}
2 changes: 1 addition & 1 deletion tests/semantic/test10_scope.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ void main(){
{
case 1:
if(b == 0)
printf("%d",&c);
// printf("%d",&c);
case 2:
if(b==1) a = 10;
case 3:
Expand Down
4 changes: 2 additions & 2 deletions tests/semantic/test11_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ int main()
// strcpy(record.name, "Raju");
record.percentage = 86.5;

printf(" Id is: %d \n", (record.id));
// printf(" Id is: %d \n", (record.id));
// printf(" Name is: %s \n", &record.name);
printf(" Percentage is: %f \n", (record.percentage));
// printf(" Percentage is: %f \n", (record.percentage));
return 0;
}
12 changes: 7 additions & 5 deletions tests/semantic/test13_fn.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,19 @@ int main()
// T = scanf();
while (1)
{
T = T-1;
int n;
T = T-1;
// n = scanf();
printf("odd: ");
printf(odd(n));
printf("even: ");
printf(even(n));
// printf("odd: ");
// printf(odd(n));
// printf("even: ");
// printf(even(n));
}
return 0;
}

int odd(int number);

int even(int number) {
if (number == 0)
return 1;
Expand Down
16 changes: 9 additions & 7 deletions tests/semantic/test15_fn.c
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
int f ()
{
int k = 0;
return k++;
}

int x = 10;
static int y = 5;
int main ()
{
int p,q;
p = 5;
q = 5;
printf("%d%d\n", p,q);
printf("%d\n", f());
// printf("%d%d\n", p,q);
// printf("%d\n", f());
f();
}

/* Module 2: */
int a[10];
int f ()
{
int k = 0;
return k++;
}
1 change: 1 addition & 0 deletions tests/semantic/test16_typedef.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
typedef int a;
typedef a b;

int main()
{
b c;
Expand Down
4 changes: 2 additions & 2 deletions tests/semantic/test17_op.c
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
int main() {
int x,y,z;
float b;
char *a;
x=5;
y=6;
z= x+y*y+x*(y+y);
float b;
char *a;
if(a<b){;}
if(a<x){;}
}
6 changes: 3 additions & 3 deletions tests/semantic/test18_multidim_array.c
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
int main( unsigned float a,int b){
int main(float a,int b){
int k=1.0;
char j[10];
char * i;
// unsigned b = -1;
int h[3][4];
if(i==b){;}
int x = a?b:i;
if(i==b){;}
{ int y=1;
++y;
int* f ;
++y;
// int m = h[1][2][3];
//int u =h[1];
//int f = h[1][1];
Expand Down
10 changes: 6 additions & 4 deletions tests/semantic/test19_fn.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ int g(int b,int c){
int main(){
int a=10;
int b=4;
b--;
int k =(int) a;
int df = g(a,b);
int q[10];
{
int a = k<2 ? 4: 6 ;
}
b--;

f();
int f = g(a,b);
int q[10];
q[1] = a;
int a = k<2 ? 4: 6 ;

}
2 changes: 1 addition & 1 deletion tests/semantic/test9_matmul.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ for(i=0;i<3;i++){
k++;
}//end of k loop
}//end of j loop
printf("\n");
// printf("\n");
}
return 0;
}

0 comments on commit 587fc91

Please sign in to comment.