aboutsummaryrefslogtreecommitdiff
path: root/15
diff options
context:
space:
mode:
Diffstat (limited to '15')
-rw-r--r--15/main.l23
-rw-r--r--15/main.y73
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>
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/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
7void apply(char);
8void load_num(char);
9void load_var(char);
10void store_var(char);
11
12int yyerror(char *);
13int yylex();
14int reg_count=0;
15struct 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
29statement: IDENT '=' expr ';' { store_var((char)$1); }
30 ;
31
32expr: 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
41void 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
54void load_num(char num) {
55 printf("LD R%d, #%c\n", reg_count++, num);
56}
57
58void load_var(char var) {
59 printf("LD R%d, %c\n", reg_count++, var);
60}
61
62void store_var(char var) {
63 printf("ST %c, R%d\n", var, reg_count-1);
64}
65
66int yyerror(char *s) {
67 printf("ERROR: %s",s);
68 exit(0);
69}
70
71int main() {
72 yyparse();
73}