-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyacc.y
135 lines (106 loc) · 2.4 KB
/
yacc.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
%{
#include "xu.h"
#define YYSTYPE node
#include "yacc.tab.h"
int yyerror();
int yyerror(char* msg);
extern int yylex();
codelist* list;
%}
%token IF ELSE THEN
%token WHILE DO
%token RELOP
%token NUMBER ID
%token AND
%left AND
%left '+' '-'
%left '*' '/'
%right '='
%right ASSIGN
%%
S : IF E THEN M S
{
backpatch(list, $3.truelist, $$.instr);
$$.nextlist = merge($2.falselist, $5.nextlist);
}
|IF E THEN M S ELSE N M S
{
backpatch(list, $2.truelist, $4.instr);
backpatch(list, $2.falselist, $8.instr);
$5.nextlist = merge($5.nextlist, $7.nextlist);
$$.nextlist = merge($5.nextlist, $9.nextlist);
}
|WHILE M E DO M S
{
backpatch(list, $6.nextlist, $2.instr);
backpatch(list, $3.truelist, $5.instr);
$$.nextlist = $3.falselist;
gen_goto(list, $2.instr);
}
|OP ASSIGN E
{
copyaddr(&$1, $1.lexeme);
gen_assignment(list, $1, $3);
}
|L
{
$$.nextlist = $1.nextlist;
}
| {}
;
L : L ';' M S
{
backpatch(list, $1.nextlist, $3.instr);
$$.nextlist = $4.nextlist;
}
|S
{
$$.nextlist = $1.nextlist;
}
;
E : E AND M E
{
backpatch(list, $1.truelist, $3.instr);
$$.truelist = $4.truelist;
$$.falselist = merge($1.falselist, $4.falselist);
}
|OP RELOP OP
{
$$.truelist = new_instrlist(nextinstr(list));
$$.falselist = new_instrlist(nextinstr(list)+1);
gen_if(list, $1, $2.oper, $3);
gen_goto_blank(list);
}
|OP
{
copyaddr_fromnode(&$$, $1);
}
;
OP : OP '+' OP { new_temp(&$$, get_temp_index(list)); gen_3addr(list, $$, $1, "+", $3); }
|NUMBER {copyaddr(&$$, $1.lexeme);}
|ID {copyaddr(&$$, $1.lexeme);}
;
M : { $$.instr = nextinstr(list); }
;
N : {
$$.nextlist = new_instrlist(nextinstr(list));
gen_goto_blank(list);
}
;
%%
int yyerror(char* msg)
{
printf("\nERROR with message: %s\n", msg);
return 0;
}
int main()
{
list = newcodelist();
freopen("test.in", "rt+", stdin);
freopen("test.out", "wt+", stdout);
yyparse();
print(list);
fclose(stdin);
fclose(stdout);
return 0;
}