diff options
author | Akshay <[email protected]> | 2021-06-11 06:04:27 +0100 |
---|---|---|
committer | Akshay <[email protected]> | 2021-06-11 06:08:19 +0100 |
commit | f9f62e75f3b234b5daf3bc25e995f9f0f56ca0a2 (patch) | |
tree | aa3920ebfd44f98ceaec6ef501cd445c59bfaead /15 | |
parent | e3c610a06bdad5c68ac59f5f4d42cc30b1e2b10f (diff) |
add prog 15
Diffstat (limited to '15')
-rw-r--r-- | 15/main.l | 23 | ||||
-rw-r--r-- | 15/main.y | 73 |
2 files changed, 96 insertions, 0 deletions
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 @@ | |||
1 | %{ | ||
2 | #include <stdlib.h> | ||
3 | extern 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 | |||
20 | int yywrap() { | ||
21 | return 1; | ||
22 | } | ||
23 | |||
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 @@ | |||
1 | %{ | ||
2 | #include<stdio.h> | ||
3 | #include<string.h> | ||
4 | #include<stdlib.h> | ||
5 | #include<ctype.h> | ||
6 | |||
7 | void apply(char); | ||
8 | void load_num(char); | ||
9 | void load_var(char); | ||
10 | void store_var(char); | ||
11 | |||
12 | int yyerror(char *); | ||
13 | int yylex(); | ||
14 | int reg_count=0; | ||
15 | struct instruction { | ||
16 | char op1; | ||
17 | char op2; | ||
18 | char opr; | ||
19 | }; | ||
20 | %} | ||
21 | |||
22 | %token IDENT NUM | ||
23 | %type expr | ||
24 | %left '+' | ||
25 | %left '*''/' | ||
26 | %left '-' | ||
27 | %% | ||
28 | |||
29 | statement: IDENT '=' expr ';' { store_var((char)$1); } | ||
30 | ; | ||
31 | |||
32 | expr: expr '+' expr {apply('+');} | ||
33 | | expr '-' expr {apply('-');} | ||
34 | | expr '*' expr {apply('*');} | ||
35 | | NUM {load_num((char)$1); $$=(char)$1;} | ||
36 | | IDENT {load_var((char)$1); $$=(char)$1;} | ||
37 | ; | ||
38 | |||
39 | %% | ||
40 | |||
41 | void apply(char opr) { | ||
42 | switch(opr) { | ||
43 | case '+': | ||
44 | printf("ADD "); | ||
45 | break; | ||
46 | case '-': | ||
47 | printf("SUB "); | ||
48 | break; | ||
49 | case '*': printf("MUL "); | ||
50 | } | ||
51 | printf("R%d, R%d, R%d\n", reg_count-2, reg_count-2, reg_count-1); | ||
52 | } | ||
53 | |||
54 | void load_num(char num) { | ||
55 | printf("LD R%d, #%c\n", reg_count++, num); | ||
56 | } | ||
57 | |||
58 | void load_var(char var) { | ||
59 | printf("LD R%d, %c\n", reg_count++, var); | ||
60 | } | ||
61 | |||
62 | void store_var(char var) { | ||
63 | printf("ST %c, R%d\n", var, reg_count-1); | ||
64 | } | ||
65 | |||
66 | int yyerror(char *s) { | ||
67 | printf("ERROR: %s",s); | ||
68 | exit(0); | ||
69 | } | ||
70 | |||
71 | int main() { | ||
72 | yyparse(); | ||
73 | } | ||