forked from mbbill/flexbison
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcppcalc.yy
121 lines (98 loc) · 2.21 KB
/
cppcalc.yy
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
/* C++ version of calculator */
/* Companion source code for "flex & bison", published by O'Reilly
* Media, ISBN 978-0-596-15597-1
* Copyright (c) 2009, Taughannock Networks. All rights reserved.
* See the README file for license conditions and contact info.
* $Header: /home/johnl/flnb/code/RCS/cppcalc.yy,v 2.1 2009/11/08 02:53:18 johnl Exp $
*/
%language "C++"
%defines
%locations
%define parser_class_name "cppcalc"
%{
#include <iostream>
using namespace std;
#include "cppcalc-ctx.hh"
%}
%parse-param { cppcalc_ctx &ctx }
%lex-param { cppcalc_ctx &ctx }
%union {
int ival;
};
/* declare tokens */
%token <ival> NUMBER
%token ADD SUB MUL DIV ABS
%token OP CP
%token EOL
%type <ival> exp factor term
%{
extern int yylex(yy::cppcalc::semantic_type *yylval,
yy::cppcalc::location_type* yylloc,
cppcalc_ctx &ctx);
void myout(int val, int radix);
%}
%initial-action {
// Filename for locations here
@$.begin.filename = @$.end.filename = new std::string("stdin");
}
%%
calclist: /* nothing */
| calclist exp EOL { cout << "= "; myout(ctx.getradix(), $2); cout << "\n> "; }
| calclist EOL { cout << "> "; } /* blank line or a comment */
;
exp: factor
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
| exp ABS factor { $$ = $1 | $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { if($3 == 0) {
error(@3, "zero divide");
YYABORT;
}
$$ = $1 / $3; }
;
term: NUMBER
| ABS term { $$ = $2 >= 0? $2 : - $2; }
| OP exp CP { $$ = $2; }
;
%%
main()
{
cppcalc_ctx ctx(8); // work in octal today
cout << "> ";
yy::cppcalc parser(ctx); // make a cppcalc parser
int v = parser.parse(); // and run it
return v;
}
// print an integer in given radix
void
myout(int radix, int val)
{
if(val < 0) {
cout << "-";
val = -val;
}
if(val > radix) {
myout(radix, val/radix);
val %= radix;
}
cout << val;
}
int
myatoi(int radix, char *s)
{
int v = 0;
while(*s) {
v = v*radix + *s++ - '0';
}
return v;
}
namespace yy {
void
cppcalc::error(location const &loc, const std::string& s)
{
std::cerr << "error at " << loc << ": " << s << std::endl;
}
}