-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.y
157 lines (126 loc) · 2.45 KB
/
parser.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
%{
#include <stdio.h>
int yylex(void);
void yyerror(char *);
extern FILE *yyin;
int yydebug=1;
extern int yylineno;
%}
%token id
%token STRING_LITERAL
%token INTEGER_LITERAL
%token op
%token FOR CLASS PUBLIC STATIC VOID MAIN STRING EXTENDS RETURN INT BOOLEAN IF ELSE WHILE PRINT LENGTH TRUE FALSE THIS NEW
%%
Program : MainClass ClassDeclList
;
ClassDeclList : ClassDeclList ClassDecl
|
;
MainClass : CLASS id '{' PUBLIC STATIC VOID MAIN '(' STRING '[' ']' id ')' '{' Statement '}' '}'
;
ClassDecl : CLASS id '{' VarDeclList MethodDeclList '}'
| CLASS id EXTENDS id '{' VarDeclList MethodDeclList '}'
;
VarDeclList : VarDeclList VarDecl
|
;
VarDecl : VDType id ';'
| id id ';'
;
VDType : VDTypePrime
| VDType '[' ']'
| id '[' ']'
;
VDTypePrime : INT
| BOOLEAN
;
MethodDeclList : MethodDeclList MethodDecl
|
;
MethodDecl : PUBLIC Type id '(' FormalList ')' '{' VarDeclList StatementList RETURN Exp ';' '}'
| PUBLIC Type id '(' FormalList ')' '{' VarDeclList RETURN Exp ';' '}'
;
FormalList : Type id FormalRestList
|
;
FormalRestList : FormalRestList FormalRest
|
;
FormalRest : ',' Type id
;
Type : PrimeType
| Type '[' ']'
;
PrimeType : INT
| BOOLEAN
| id
;
StatementList : StatementList Statement
| Statement
;
Statement : '{' StatementList '}'
| '{' '}'
| IF '(' Exp ')' Statement ELSE Statement
| WHILE '(' Exp ')' Statement
| PRINT '(' Exp ')' ';'
| PRINT '(' STRING_LITERAL ')' ';'
| id '=' Exp ';'
| id Index '=' Exp ';'
;
Index : '[' Exp ']'
| Index '[' Exp ']'
;
Exp : Exp op PrefixExp
| Exp '<' PrefixExp
| Exp '>' PrefixExp
| Exp '+' PrefixExp
| Exp '-' PrefixExp
| Exp '*' PrefixExp
| Exp '/' PrefixExp
| PrefixExp
;
PrefixExp : '!' PrimaryExp
| '-' PrimaryExp
| '+' PrimaryExp
| PrimaryExp
;
PrimaryExp : INTEGER_LITERAL
| TRUE
| FALSE
| Object
| '(' Exp ')'
| id '.' LENGTH
| id Index '.' LENGTH
| id '.' id '(' ExpList ')'
| ObjectPrime '.' id '(' ExpList ')'
;
Object : id
| THIS
| NEW id '(' ')'
| NEW PrimeType Index
;
ObjectPrime : THIS
| NEW id '(' ')'
| NEW PrimeType Index
;
ExpList : Exp ExpRestList
;
ExpRestList : ExpRestList ExpRest
|
;
ExpRest : ',' Exp
;
%%
void yyerror(char *s) {
fprintf(stderr, "Syntax errors in %d\n", yylineno);
}
int main(int argc, char **argv) {
++argv, --argc;
if (argc > 0)
yyin = fopen(argv[0], "r");
else
yyin = stdin;
yyparse();
return 0;
}