Skip to content

Commit

Permalink
final commit 💚
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-chauhan committed May 13, 2021
2 parents cc6cf69 + 50301f6 commit 2d9d046
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 47 deletions.
50 changes: 34 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,47 @@ $ pip install --ignore-installed -r ./requirements.txt
```
### For building executable
```bash
$ make
$ make clean # For removing the build
$ make
```

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

# 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
```bash
./bin/gcc_lite [-o outfile] tests/helloworld.c
```


### For more informations
```
$ ./bin/parser -h
### For more informations about usage
```bash
usage: gcc_lite [-h] [-d] [-o OUT] [-l] [-D] [-p] [-I] [--sym] [-S] [-R] input

Compiler for C programs

positional arguments:
input C program file to compile

optional arguments:
-h, --help show this help message and exit
-d, --debug Generate assembly with extra information (for debugging purposes)
-o OUT, --out OUT File name to store generated executable
-l, --lex Store output of lexer
-D, --dot Generate AST graph as DOT format
-p, --png Generate AST graph as png format
-I, --ir Dump the generated Intermediate representation
--sym Dump the symbol table
-S, --asm Store the generated assembly file
-R, --exec Execute the generated program
```

## Features

### Basic
### Basic Features
- Native data types: Int, Char, Float
- Variables and Expressions
- Conditional: if, if-else, switch-case
- Loops: for, while, do-while
- Break, Continue
- Switch Case
- Arrays: Single and multidimensional
- Input,output
- Functions, recursion
Expand All @@ -56,9 +69,14 @@ $ ./bin/parser -h
- Typedef

### Advanced Features
- Dynamic memory allocation:
- Register allocation optimization
-
- Dynamic memory allocation (malloc, free)
- Register allocation optimization using conditional spilling
- File Handling
- Fork and exec system calls
- Storage Optimization for Char and string
- Nested Struct and Array Initializers
- Multidimensional arrays as function parameters
- Short circuit expression evaluation

## Members
- [Dev Chauhan](https://github.com/dev-chauhan)
Expand Down
2 changes: 1 addition & 1 deletion src/codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ def gen_instr(self, code):
self.add(f'pushl ${func.ret_type.get_size()}')
self.add(f'pushl %eax')
self.add(f'pushl {hex(scope.lookup_info("ret@")["offset"])}(%ebp)')
self.add(f'call memcpy')
self.add(f'call bufcpy')
self.add(f'addl $12, %esp')
self.add(f'movl {hex(scope.lookup_info("ret@")["offset"])}(%ebp), %eax')

Expand Down
30 changes: 15 additions & 15 deletions src/gcc_lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ def arg_parser():
argparser = ArgumentParser(prog='gcc_lite',
description='Compiler for C programs')

argparser.add_argument('--input', type=str,
help='C program file to parse', default='../test/helloworld.c')
argparser.add_argument('input', type=str,
help='C program file to compile')

argparser.add_argument('-d', '--debug', action="store_true",
help='Generate assembly with extra information (for debugging purposes)')
Expand Down Expand Up @@ -101,12 +101,12 @@ def arg_parser():
graph.write_png(png_file)

# try generating IR and symbol table
# try:
syntax_tree.gen()
# except:
# print(bcolors.BOLD+f'{lexer.filename}:0:0'+bcolors.ENDC,end='')
# print(bcolors.FAIL+' IR Error'+bcolors.ENDC)
# exit(1)
try:
syntax_tree.gen()
except:
print(bcolors.BOLD+f'{lexer.filename}:0:0'+bcolors.ENDC,end='')
print(bcolors.FAIL+' IR Error'+bcolors.ENDC)
exit(1)

if args.sym:
sym_file = ofile + '.csv'
Expand All @@ -116,13 +116,13 @@ def arg_parser():
tac.dump_code(ir_file)

# try generating assembly from IR
# try:
asm = AssemblyGen(tac.func_code, debug=args.debug)
asm.gen_assembly()
# except:
# print(bcolors.BOLD+f'{lexer.filename}:0:0'+bcolors.ENDC,end='')
# print(bcolors.FAIL+' Code Generation Error'+bcolors.ENDC)
# exit(1)
try:
asm = AssemblyGen(tac.func_code, debug=args.debug)
asm.gen_assembly()
except:
print(bcolors.BOLD+f'{lexer.filename}:0:0'+bcolors.ENDC,end='')
print(bcolors.FAIL+' Code Generation Error'+bcolors.ENDC)
exit(1)

# dump the assembly!

Expand Down
11 changes: 6 additions & 5 deletions src/lib.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
stdlib = '''
int printf(char *s);
int scanf(char *s);
void strcpy(char *d, char *s);
void* memcpy(void* d, void* s, int cnt);
void strcpy(char *d, char *s);
int strlen(char *s);
int open(char* filename, int flags);
int close(int fd);
int read(int fd, char* buf, int size);
Expand All @@ -21,10 +24,8 @@
float sqrt(float x);
float pow(float base, float power);
// TODO: add malloc, free and math function
// Extra functions
void* malloc(int size);
void free(void *ptr);
void prints(char* s){
printf("%s", s);
Expand Down
7 changes: 5 additions & 2 deletions src/parser_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,8 +502,11 @@ def gen(self, lvalue = False):
# store starting addr of struct/array
self.place = tac.newtmp()
symtable.add_var(self.place, self.expr_type)
if self.expr_type.is_param and not lvalue:
tac.emit(f"{self.place} = {self.name}")
if self.expr_type.is_param:
if lvalue:
tac.emit(f"{self.place} = & {self.name}")
else:
tac.emit(f"{self.place} = {self.name}")
else:
tac.emit(f"{self.place} = & {self.name}")
elif self.expr_type.is_struct_type():
Expand Down
18 changes: 10 additions & 8 deletions tests/final/test18_fileio.c
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
int main()
{
int fd_out, x;
char file_name[10] = "a.txt";
char msg[20] = "hello world";

fd_out = open(file_name, 2);
x = write(fd_out, msg , strlen(msg)+1);

close(fd_out);
int O_CREAT = 64;
int O_RDWD = 2;
int O_RDONLY = 0;
int O_WRONLY = 1;

int fd, x;
char msg[20] = "hello world";
fd = open("fileio.txt", O_CREAT | O_RDWD);
x = write(fd, msg , strlen(msg)+1);
printf("length of buffer: %d", strlen(msg)+1);
close(fd);
}
35 changes: 35 additions & 0 deletions tests/final/test22_newtonraphson.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
float f(float x)
{
return x*log(x)/log(10) - 1.2;
}
float df (float x)
{
return log(x)/log(10) + 0.43429;
}
float abs(float x)
{
if(x > 0)
return x;
return -x;
}
int main()
{
int itr, maxmitr;
float h, x0, x1, allerr;
printf("\nEnter x0, allowed error and maximum iterations\n");
scanf("%f %f %d", &x0, &allerr, &maxmitr);
for (itr=1; itr<=maxmitr; itr++)
{
h=f(x0)/df(x0);
x1=x0-h;
printf(" At Iteration no. %3d, x = %9.6f\n", itr, x1);
if (abs(h) < allerr)
{
printf("After %3d iterations, root = %8.6f\n", itr, x1);
return 0;
}
x0=x1;
}
printf(" The required solution does not converge or iterations are insufficient\n");
return 1;
}

0 comments on commit 2d9d046

Please sign in to comment.