]> git.saurik.com Git - bison.git/blob - examples/variant.yy
stack::size instead of stack::height.
[bison.git] / examples / variant.yy
1 /* Test file for C++ parsers using variants.
2 Based on an example by Michiel De Wilde <mdewilde.agilent@gmail.com>. */
3 %language "C++"
4 %debug
5 %defines
6 %define variant
7
8 %code requires // *.hh
9 {
10 #include <string>
11 }
12
13 %code // *.cc
14 {
15 #include <algorithm>
16 #include <iostream>
17 #include <sstream>
18
19 static yy::parser::token_type yylex(yy::parser::semantic_type* yylval);
20 }
21
22 %token <std::string> TEXT
23 %token <int> NUMBER
24 %printer { debug_stream() << $$; } <int> <std::string>
25 %token END_OF_FILE 0
26
27 %type <std::string> text result
28
29 %%
30
31 result:
32 text { std::cout << $1 << std::endl; }
33 ;
34
35 text:
36 /* nothing */ { /* This will generate an empty string */ }
37 | text TEXT { std::swap($$,$1); $$.append($2); }
38 | text NUMBER {
39 std::swap($$,$1);
40 std::ostringstream o;
41 o << ' ' << $2;
42 $$.append(o.str());
43 }
44 ;
45 %%
46
47 // The yylex function providing subsequent tokens:
48 // TEXT "I have three numbers for you:"
49 // NUMBER 1
50 // NUMBER 2
51 // NUMBER 3
52 // TEXT " and that's all!"
53 // END_OF_FILE
54
55 static
56 yy::parser::token_type
57 yylex(yy::parser::semantic_type* yylval)
58 {
59 static int stage = 0;
60 yy::parser::token_type result;
61
62 switch (stage)
63 {
64 case 0:
65 yylval->build<std::string>();
66 yylval->as<std::string>() = std::string("I have three numbers for you:");
67 result = yy::parser::token::TEXT;
68 break;
69 case 1:
70 case 2:
71 case 3:
72 yylval->build<int>();
73 yylval->as<int>() = stage;
74 result = yy::parser::token::NUMBER;
75 break;
76 case 4:
77 yylval->build<std::string>();
78 yylval->as<std::string>() = std::string(" and that's all!");
79 result = yy::parser::token::TEXT;
80 break;
81 default:
82 result = yy::parser::token::END_OF_FILE;
83 break;
84 }
85
86 stage++;
87 return result;
88 }
89
90 // Mandatory error function
91 void
92 yy::parser::error(const yy::parser::location_type& yylloc,
93 const std::string& message)
94 {
95 std::cerr << yylloc << ": " << message << std::endl;
96 }
97
98 int
99 main(int argc, char *argv[])
100 {
101 yy::parser p;
102 p.set_debug_level(!!getenv("YYDEBUG"));
103 p.parse();
104 }
105
106 // Local Variables:
107 // mode: C++
108 // End: