From f9f62e75f3b234b5daf3bc25e995f9f0f56ca0a2 Mon Sep 17 00:00:00 2001 From: Akshay Date: Fri, 11 Jun 2021 10:34:27 +0530 Subject: add prog 15 --- 15/main.l | 23 ++++++++++++++++++++ 15/main.y | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 15/main.l create mode 100644 15/main.y (limited to '15') diff --git a/15/main.l b/15/main.l new file mode 100644 index 0000000..ffcb97e --- /dev/null +++ b/15/main.l @@ -0,0 +1,23 @@ +%{ +#include +extern int yylval; +%} + +%% + +[0-9]+? { + yylval=yytext[0]; + return NUM; +}; +[a-zA-Z]+? { + yylval=yytext[0]; + return IDENT; +} +. return yytext[0]; +\n return 0; +%% + +int yywrap() { + return 1; +} + diff --git a/15/main.y b/15/main.y new file mode 100644 index 0000000..46075c2 --- /dev/null +++ b/15/main.y @@ -0,0 +1,73 @@ +%{ +#include +#include +#include +#include + +void apply(char); +void load_num(char); +void load_var(char); +void store_var(char); + +int yyerror(char *); +int yylex(); +int reg_count=0; +struct instruction { + char op1; + char op2; + char opr; +}; +%} + +%token IDENT NUM +%type expr +%left '+' +%left '*''/' +%left '-' +%% + +statement: IDENT '=' expr ';' { store_var((char)$1); } + ; + +expr: expr '+' expr {apply('+');} + | expr '-' expr {apply('-');} + | expr '*' expr {apply('*');} + | NUM {load_num((char)$1); $$=(char)$1;} + | IDENT {load_var((char)$1); $$=(char)$1;} + ; + +%% + +void apply(char opr) { + switch(opr) { + case '+': + printf("ADD "); + break; + case '-': + printf("SUB "); + break; + case '*': printf("MUL "); + } + printf("R%d, R%d, R%d\n", reg_count-2, reg_count-2, reg_count-1); +} + +void load_num(char num) { + printf("LD R%d, #%c\n", reg_count++, num); +} + +void load_var(char var) { + printf("LD R%d, %c\n", reg_count++, var); +} + +void store_var(char var) { + printf("ST %c, R%d\n", var, reg_count-1); +} + +int yyerror(char *s) { + printf("ERROR: %s",s); + exit(0); +} + +int main() { + yyparse(); +} -- cgit v1.2.3