From e3c610a06bdad5c68ac59f5f4d42cc30b1e2b10f Mon Sep 17 00:00:00 2001 From: Akshay Date: Fri, 11 Jun 2021 09:49:05 +0530 Subject: add prog 14 --- 14/main.l | 23 +++++++++++++++++ 14/main.y | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 14/main.l create mode 100644 14/main.y (limited to '14') diff --git a/14/main.l b/14/main.l new file mode 100644 index 0000000..ffcb97e --- /dev/null +++ b/14/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/14/main.y b/14/main.y new file mode 100644 index 0000000..8d10b32 --- /dev/null +++ b/14/main.y @@ -0,0 +1,86 @@ +%{ +#include +#include +#include +#include + +void three_address_code(); +char add_to_table(char ,char, char); +int yyerror(char *); +int yylex(); + +int idx = 0; +char tvar = '1'; +struct instruction { + char op1; + char op2; + char opr; +}; +%} + +%token IDENT NUM +%type expr +%left '+' +%left '*''/' +%left '-' +%% + +statement: IDENT '=' expr ';' { add_to_table((char)$1, (char)$3, '='); } + | expr ';' + ; + +expr: expr '+' expr {$$ = add_to_table((char)$1, (char)$3, '+');} + | expr '-' expr {$$ = add_to_table((char)$1, (char)$3, '-');} + | expr '*' expr {$$ = add_to_table((char)$1, (char)$3, '*');} + | expr '/' expr {$$ = add_to_table((char)$1, (char)$3, '/');} + | '(' expr ')' {$$ = (char)$2;} + | NUM {$$ = (char)$1;} + | IDENT {$$ = (char)$1;} + | '-' expr {$$ = add_to_table((char)$2, (char)'\t', '-');} + ; + +%% + +int yyerror(char *s) { + printf("ERROR: %s",s); + exit(0); +} + +struct instruction ops[20]; + +char add_to_table(char op1, char op2, char opr) { + ops[idx].op1 = op1; + ops[idx].op2 = op2; + ops[idx].opr = opr; + idx++; + return tvar++; +} + +void three_address_code() { + int count = 0; + char temp = '1'; + while(count < idx) { + if(ops[count].opr != '=') { + printf("t%c=", temp++); + } + if(isalpha(ops[count].op1)) { + printf("%c",ops[count].op1); + } else if(ops[count].op1 >='1' && ops[count].op1 <='9') { + printf("t%c",ops[count].op1); + } + + printf("%c",ops[count].opr); + + if(isalpha(ops[count].op2)) { + printf(" %c\n",ops[count].op2); + } else if(ops[count].op2 >='1' && ops[count].op2 <='9') { + printf("t%c\n",ops[count].op2); + } + count++; + } +} + +int main() { + yyparse(); + three_address_code(); +} -- cgit v1.2.3