-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbison.yxx
68 lines (58 loc) · 1.23 KB
/
bison.yxx
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
/*
* @name bison.yy
* @description A Simple Tools of Expression Analysis
* @date 03/26/2020
* @author Lrq
*/
%language "C++"
%defines
%locations
%skeleton "lalr1.cc"
%code{
#include <iostream>
#include <unistd.h>
}
%code requires{
#include "ast.h"
#include "visitor.h"
}
%union{
Expression* e;
double d;
}
%parse-param {Expression** root }
/* declearation */
%token EOL
%token <d> NUMBER
%token ADD SUB MUL DIV OP CP
%type <e> exp factor term
%{
extern int yylex(yy::parser::semantic_type *yylval, yy::parser::location_type *yylloc);
%}
%%
calclist:
| calclist exp EOL{ printf("Recognized!\n"); *root = $2;}
| calclist EOL { printf("> "); }
;
exp: factor {$$ = $1;}
| exp ADD factor { $$ = new BinOp("Plus", $1, $3); }
| exp SUB factor { $$ = new BinOp("Sub", $1, $3); }
;
factor: term {$$ = $1;}
| factor MUL term { $$ = new BinOp("Mul", $1, $3);}
| factor DIV term { if (((Num*)$3)->val == 0){
error(@3, "Zero Divide!\n");
YYABORT;
}
$$ = new BinOp("Div", $1, $3);}
;
term: NUMBER { $$ = new Num("Num", $1); }
| OP exp CP { $$ = $2; }
;
%%
namespace yy{
void
parser::error(location const &loc, const std::string &s){
std::cerr << "error at " << loc << ": " << s << std::endl;
}
}