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 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ flake.nix | 1 + 3 files changed, 110 insertions(+) create mode 100644 14/main.l create mode 100644 14/main.y 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(); +} diff --git a/flake.nix b/flake.nix index fb2e2cb..a46e0ed 100644 --- a/flake.nix +++ b/flake.nix @@ -25,6 +25,7 @@ { name = "10"; yacc = true; } { name = "11"; yacc = true; } { name = "12"; yacc = true; } + { name = "14"; yacc = true; } ]; apps = builtins.listToAttrs (builtins.map (def: -- cgit v1.2.3