]> git.saurik.com Git - bison.git/blob - examples/calc++/calc++-parser.yy
672814349b9c489aec7bd171773d845e03bbe003
[bison.git] / examples / calc++ / calc++-parser.yy
1 %skeleton "lalr1.cc" /* -*- C++ -*- */
2 %define "parser_class_name" "calcxx_parser"
3 %defines
4 %{
5 # include <string>
6 # include "calc++-driver.hh"
7 %}
8
9 %error-verbose
10
11 // The parsing context.
12 %parse-param { calcxx_driver& driver }
13 %lex-param { calcxx_driver& driver }
14
15 %locations
16 %initial-action
17 {
18 // Initialize the initial location.
19 @$.begin.filename = @$.end.filename = &driver.file;
20 };
21
22 // Define yydebug.
23 %debug
24
25 // Symbols.
26
27 %union
28 {
29 /// Value of a numeric literal.
30 int ival;
31 /// Name of a variable.
32 std::string *sval;
33 };
34
35 %token YYEOF 0 "end of file"
36 %token TOKEN_ASSIGN ":="
37 %token <sval> TOKEN_IDENTIFIER "identifier"
38 %token <ival> TOKEN_NUMBER "number"
39 %type <ival> exp "expression"
40
41 %printer { debug_stream () << *$$; } "identifier"
42 %destructor { delete $$; } "identifier"
43
44 %printer { debug_stream () << $$; } "number" "expression"
45
46 %%
47 %start unit;
48 unit: assignments exp { driver.result = $2; };
49
50 assignments: assignments assignment {}
51 | /* Nothing. */ {};
52
53 assignment: TOKEN_IDENTIFIER ":=" exp { driver.variables[*$1] = $3; };
54
55 %left '+' '-';
56 %left '*' '/';
57 exp: exp '+' exp { $$ = $1 + $3; }
58 | exp '-' exp { $$ = $1 - $3; }
59 | exp '*' exp { $$ = $1 * $3; }
60 | exp '/' exp { $$ = $1 / $3; }
61 | TOKEN_IDENTIFIER { $$ = driver.variables[*$1]; }
62 | TOKEN_NUMBER { $$ = $1; };
63 %%
64 void
65 yy::calcxx_parser::error (const location& l, const std::string& m)
66 {
67 driver.error (l, m);
68 }