2 Copyright (C) 2008-2015, 2018-2021 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>.
21 %define api.token.constructor
22 %define api.value.type variant
23 %define api.value.automove
24 %define api.location.file none
28 %code requires // *.hh
30 #include <memory> // std::unique_ptr
34 using string_uptr = std::unique_ptr<std::string>;
35 using string_uptrs = std::vector<string_uptr>;
40 #include <climits> // INT_MIN, INT_MAX
46 // Prototype of the yylex function providing subsequent tokens.
47 static parser::symbol_type yylex ();
49 // Print a vector of strings.
51 operator<< (std::ostream& o, const string_uptrs& ss)
55 for (const auto& s: ss)
64 template <typename... Args>
66 make_string_uptr (Args&&... args)
68 // std::make_unique is C++14.
69 return string_uptr (new std::string{std::forward<Args> (args)...});
73 %token <string_uptr> TEXT;
75 %printer { yyo << '(' << &$$ << ") " << $$; } <*>;
76 %printer { yyo << *$$; } <string_uptr>;
79 %type <string_uptr> item;
80 %type <string_uptrs> list;
85 list { std::cout << $1 << '\n'; }
89 %empty { /* Generates an empty string list */ }
90 | list item { $$ = $1; $$.emplace_back ($2); }
95 | NUMBER { $$ = make_string_uptr (std::to_string ($1)); }
99 // The last number return by the scanner is max - 1.
104 // The yylex function providing subsequent tokens:
105 // TEXT "I have three numbers for you."
110 // TEXT "And that's all!"
117 static int count = 0;
118 const int stage = count;
120 auto loc = parser::location_type{nullptr, stage + 1, stage + 1};
122 return parser::make_TEXT (make_string_uptr ("I have numbers for you."), std::move (loc));
123 else if (stage < max)
124 return parser::make_NUMBER (stage, std::move (loc));
125 else if (stage == max)
126 return parser::make_TEXT (make_string_uptr ("And that's all!"), std::move (loc));
128 return parser::make_END_OF_FILE (std::move (loc));
131 // Mandatory error function
133 parser::error (const parser::location_type& loc, const std::string& msg)
135 std::cerr << loc << ": " << msg << '\n';
140 main (int argc, const char *argv[])
142 if (2 <= argc && isdigit (static_cast<unsigned char> (*argv[1])))
144 auto maxl = strtol (argv[1], nullptr, 10);
145 max = INT_MIN <= maxl && maxl <= INT_MAX ? int(maxl) : 4;
147 auto&& p = yy::parser{};
148 p.set_debug_level (!!getenv ("YYDEBUG"));