This repository has been archived by the owner on May 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.y
106 lines (90 loc) · 1.65 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
/* 生成.output文件 */
%verbose
/* 用于调试 (yydebug) */
%define parse.trace
%code top {
int yylex (void);
void yyerror (char const *);
}
%code requires {
#include "asg.hpp"
}
%union {
Expr* Expr;
Number* Number;
UnaryOp* UnaryOp;
BinaryOp* BinaryOp;
ExprList* ExprList;
}
%nterm <ExprList> ExprList
%nterm <Expr> Expr;
%nterm <Expr> Expr3;
%nterm <Expr> Expr2;
%nterm <Expr> Expr1;
%nterm <Expr> Expr0;
%token <Number> NUMBER
%token ADD
%token SUB
%token MUL
%token DIV
%token L_PAREN
%token R_PAREN
%token SEMI
%start start
%%
start:
ExprList { gExprList = $1; }
| ExprList SEMI { gExprList = $1; }
;
ExprList:
%empty { $$ = Mgr::g.make<ExprList>(); }
| Expr { $$ = Mgr::g.make<ExprList>(), $$->push_back($1); }
| ExprList SEMI Expr { $$ = $1, $$->push_back($3); }
;
Expr:
Expr3
;
Expr3:
Expr2
| Expr2 MUL Expr2 {
auto p = Mgr::g.make<BinaryOp>();
p->op = BinaryOp::kMul, p->lft = $1, p->rht = $3;
$$ = p;
}
| Expr2 DIV Expr1 {
auto p = Mgr::g.make<BinaryOp>();
p->op = BinaryOp::kDiv, p->lft = $1, p->rht = $3;
$$ = p;
}
;
Expr2:
Expr1
| Expr1 ADD Expr1 {
auto p = Mgr::g.make<BinaryOp>();
p->op = BinaryOp::kAdd, p->lft = $1, p->rht = $3;
$$ = p;
}
| Expr1 SUB Expr1 {
auto p = Mgr::g.make<BinaryOp>();
p->op = BinaryOp::kSub, p->lft = $1, p->rht = $3;
$$ = p;
}
;
Expr1:
Expr0
| ADD Expr0 {
auto p = Mgr::g.make<UnaryOp>();
p->op = UnaryOp::kPos, p->sub = $2;
$$ = p;
}
| SUB Expr0 {
auto p = Mgr::g.make<UnaryOp>();
p->op = UnaryOp::kNeg, p->sub = $2;
$$ = p;
}
;
Expr0:
NUMBER { $$ = $1; }
| L_PAREN Expr R_PAREN { $$ = $2; }
;
%%