1 /* Test file for C++ parsers using variants.
2 Based on an example by Michiel De Wilde <mdewilde.agilent@gmail.com>. */
12 typedef std::list<std::string> strings_type;
22 // Prototype of the yylex function providing subsequent tokens.
23 static yy::parser::token_type yylex(yy::parser::semantic_type* yylval);
25 // Printing a list of strings.
26 // Koening look up will look into std, since that's an std::list.
30 operator<<(std::ostream& o, const strings_type& s)
32 std::copy(s.begin(), s.end(),
33 std::ostream_iterator<strings_type::value_type>(o, "\n"));
38 // Conversion to string.
42 string_cast (const T& t)
50 %token <std::string> TEXT;
52 %printer { debug_stream () << $$; } <int> <std::string> <strings_type>;
55 %type <std::string> item;
56 %type <strings_type> list;
61 list { std::cout << $1 << std::endl; }
65 /* nothing */ { /* Generates an empty string list */ }
66 | list item { std::swap ($$, $1); $$.push_back ($2); }
70 TEXT { std::swap ($$, $1); }
71 | NUMBER { $$ = string_cast ($1); }
75 // The yylex function providing subsequent tokens:
76 // TEXT "I have three numbers for you:"
80 // TEXT " and that's all!"
84 yy::parser::token_type
85 yylex (yy::parser::semantic_type* yylval)
88 yy::parser::token_type result;
93 yylval->build<std::string> () =
94 std::string ("I have three numbers for you.");
95 result = yy::parser::token::TEXT;
100 yylval->build<int> () = stage;
101 result = yy::parser::token::NUMBER;
104 yylval->build<std::string> () = std::string ("And that's all!");
105 result = yy::parser::token::TEXT;
108 result = yy::parser::token::END_OF_FILE;
116 // Mandatory error function
118 yy::parser::error (const yy::parser::location_type& yylloc,
119 const std::string& message)
121 std::cerr << yylloc << ": " << message << std::endl;
125 main (int argc, char *argv[])
128 p.set_debug_level (!!getenv ("YYDEBUG"));