]> git.saurik.com Git - bison.git/blob - examples/variant.yy
Don't let maintainer-*-check targets force a version update.
[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 () << $$; }
52 <int> <::std::string> <::std::list<std::string>>;
53 %token END_OF_FILE 0;
54
55 %type <::std::string> item;
56 %type <::std::list<std::string>> list;
57
58 %%
59
60 result:
61 list { std::cout << $1 << std::endl; }
62 ;
63
64 list:
65 /* nothing */ { /* Generates an empty string list */ }
66 | list item { std::swap ($$, $1); $$.push_back ($2); }
67 ;
68
69 item:
70 TEXT { std::swap ($$, $1); }
71 | NUMBER { $$ = string_cast ($1); }
72 ;
73 %%
74
75 // The yylex function providing subsequent tokens:
76 // TEXT "I have three numbers for you:"
77 // NUMBER 1
78 // NUMBER 2
79 // NUMBER 3
80 // TEXT " and that's all!"
81 // END_OF_FILE
82
83 static
84 yy::parser::symbol_type
85 yylex ()
86 {
87 static int stage = -1;
88 switch (++stage)
89 {
90 case 0:
91 return yy::parser::make_TEXT ("I have three numbers for you.");
92 case 1:
93 case 2:
94 case 3:
95 return yy::parser::make_NUMBER (stage);
96 case 4:
97 return yy::parser::make_TEXT ("And that's all!");
98 default:
99 return yy::parser::make_END_OF_FILE ();
100 }
101 }
102
103 // Mandatory error function
104 void
105 yy::parser::error (const std::string& message)
106 {
107 std::cerr << message << std::endl;
108 }
109
110 int
111 main ()
112 {
113 yy::parser p;
114 p.set_debug_level (!!getenv ("YYDEBUG"));
115 return p.parse ();
116 }
117
118 // Local Variables:
119 // mode: C++
120 // End: