]> git.saurik.com Git - bison.git/blob - examples/variant.yy
016c4b2ad07d3c4a6a20d5fd138a3cb30cc04b86
[bison.git] / examples / variant.yy
1 %debug
2 %skeleton "lalr1.cc"
3 %defines
4 %define variant
5 %define lex_symbol
6
7 %code requires // *.hh
8 {
9 #include <list>
10 #include <string>
11 typedef std::list<std::string> strings_type;
12 }
13
14 %code // *.cc
15 {
16 #include <algorithm>
17 #include <iostream>
18 #include <iterator>
19 #include <sstream>
20
21 // Prototype of the yylex function providing subsequent tokens.
22 static yy::parser::symbol_type yylex ();
23
24 // Printing a list of strings.
25 // Koening look up will look into std, since that's an std::list.
26 namespace std
27 {
28 std::ostream&
29 operator<< (std::ostream& o, const strings_type& s)
30 {
31 std::copy (s.begin (), s.end (),
32 std::ostream_iterator<strings_type::value_type> (o, "\n"));
33 return o;
34 }
35 }
36
37 // Conversion to string.
38 template <typename T>
39 inline
40 std::string
41 string_cast (const T& t)
42 {
43 std::ostringstream o;
44 o << t;
45 return o.str ();
46 }
47 }
48
49 %token <std::string> TEXT;
50 %token <int> NUMBER;
51 %printer { debug_stream () << $$; } <int> <std::string> <strings_type>;
52 %token END_OF_FILE 0;
53
54 %type <std::string> item;
55 %type <strings_type> list;
56
57 %%
58
59 result:
60 list { std::cout << $1 << std::endl; }
61 ;
62
63 list:
64 /* nothing */ { /* Generates an empty string list */ }
65 | list item { std::swap ($$, $1); $$.push_back ($2); }
66 ;
67
68 item:
69 TEXT { std::swap ($$, $1); }
70 | NUMBER { $$ = string_cast ($1); }
71 ;
72 %%
73
74 // The yylex function providing subsequent tokens:
75 // TEXT "I have three numbers for you:"
76 // NUMBER 1
77 // NUMBER 2
78 // NUMBER 3
79 // TEXT " and that's all!"
80 // END_OF_FILE
81
82 static
83 yy::parser::symbol_type
84 yylex ()
85 {
86 static int stage = -1;
87 switch (++stage)
88 {
89 case 0:
90 return yy::parser::make_TEXT ("I have three numbers for you.");
91 case 1:
92 case 2:
93 case 3:
94 return yy::parser::make_NUMBER (stage);
95 case 4:
96 return yy::parser::make_TEXT ("And that's all!");
97 default:
98 return yy::parser::make_END_OF_FILE ();
99 }
100 }
101
102 // Mandatory error function
103 void
104 yy::parser::error (const std::string& message)
105 {
106 std::cerr << message << std::endl;
107 }
108
109 int
110 main ()
111 {
112 yy::parser p;
113 p.set_debug_level (!!getenv ("YYDEBUG"));
114 return p.parse ();
115 }
116
117 // Local Variables:
118 // mode: C++
119 // End: