aboutsummaryrefslogtreecommitdiff
path: root/14
diff options
context:
space:
mode:
Diffstat (limited to '14')
-rw-r--r--14/main.l23
-rw-r--r--14/main.y86
2 files changed, 109 insertions, 0 deletions
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 @@
1%{
2#include <stdlib.h>
3extern int yylval;
4%}
5
6%%
7
8[0-9]+? {
9 yylval=yytext[0];
10 return NUM;
11};
12[a-zA-Z]+? {
13 yylval=yytext[0];
14 return IDENT;
15}
16. return yytext[0];
17\n return 0;
18%%
19
20int yywrap() {
21 return 1;
22}
23
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 @@
1%{
2#include<stdio.h>
3#include<string.h>
4#include<stdlib.h>
5#include<ctype.h>
6
7void three_address_code();
8char add_to_table(char ,char, char);
9int yyerror(char *);
10int yylex();
11
12int idx = 0;
13char tvar = '1';
14struct instruction {
15 char op1;
16 char op2;
17 char opr;
18};
19%}
20
21%token IDENT NUM
22%type expr
23%left '+'
24%left '*''/'
25%left '-'
26%%
27
28statement: IDENT '=' expr ';' { add_to_table((char)$1, (char)$3, '='); }
29 | expr ';'
30 ;
31
32expr: expr '+' expr {$$ = add_to_table((char)$1, (char)$3, '+');}
33 | expr '-' expr {$$ = add_to_table((char)$1, (char)$3, '-');}
34 | expr '*' expr {$$ = add_to_table((char)$1, (char)$3, '*');}
35 | expr '/' expr {$$ = add_to_table((char)$1, (char)$3, '/');}
36 | '(' expr ')' {$$ = (char)$2;}
37 | NUM {$$ = (char)$1;}
38 | IDENT {$$ = (char)$1;}
39 | '-' expr {$$ = add_to_table((char)$2, (char)'\t', '-');}
40 ;
41
42%%
43
44int yyerror(char *s) {
45 printf("ERROR: %s",s);
46 exit(0);
47}
48
49struct instruction ops[20];
50
51char add_to_table(char op1, char op2, char opr) {
52 ops[idx].op1 = op1;
53 ops[idx].op2 = op2;
54 ops[idx].opr = opr;
55 idx++;
56 return tvar++;
57}
58
59void three_address_code() {
60 int count = 0;
61 char temp = '1';
62 while(count < idx) {
63 if(ops[count].opr != '=') {
64 printf("t%c=", temp++);
65 }
66 if(isalpha(ops[count].op1)) {
67 printf("%c",ops[count].op1);
68 } else if(ops[count].op1 >='1' && ops[count].op1 <='9') {
69 printf("t%c",ops[count].op1);
70 }
71
72 printf("%c",ops[count].opr);
73
74 if(isalpha(ops[count].op2)) {
75 printf(" %c\n",ops[count].op2);
76 } else if(ops[count].op2 >='1' && ops[count].op2 <='9') {
77 printf("t%c\n",ops[count].op2);
78 }
79 count++;
80 }
81}
82
83int main() {
84 yyparse();
85 three_address_code();
86}