1/* Simple variant-based parser. -*- C++ -*- 2 3 Copyright (C) 2018-2021 Free Software Foundation, Inc. 4 5 This file is part of Bison, the GNU Compiler Compiler. 6 7 This program is free software: you can redistribute it and/or modify 8 it under the terms of the GNU General Public License as published by 9 the Free Software Foundation, either version 3 of the License, or 10 (at your option) any later version. 11 12 This program is distributed in the hope that it will be useful, 13 but WITHOUT ANY WARRANTY; without even the implied warranty of 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License 18 along with this program. If not, see <https://www.gnu.org/licenses/>. */ 19 20%require "3.2" 21%language "c++" 22 23%define api.value.type variant 24 25%code 26{ 27 // Print a list of strings. 28 auto 29 operator<< (std::ostream& o, const std::vector<std::string>& ss) 30 -> std::ostream& 31 { 32 o << '{'; 33 const char *sep = ""; 34 for (const auto& s: ss) 35 { 36 o << sep << s; 37 sep = ", "; 38 } 39 return o << '}'; 40 } 41} 42 43%define api.token.constructor 44 45%code 46{ 47 namespace yy 48 { 49 // Return the next token. 50 auto yylex () -> parser::symbol_type 51 { 52 static int count = 0; 53 switch (int stage = count++) 54 { 55 case 0: 56 return parser::make_TEXT ("I have three numbers for you."); 57 case 1: case 2: case 3: 58 return parser::make_NUMBER (stage); 59 case 4: 60 return parser::make_TEXT ("And that's all!"); 61 default: 62 return parser::make_YYEOF (); 63 } 64 } 65 } 66} 67%% 68result: 69 list { std::cout << $1 << '\n'; } 70; 71 72%nterm <std::vector<std::string>> list; 73list: 74 %empty { /* Generates an empty string list */ } 75| list item { $$ = $1; $$.push_back ($2); } 76; 77 78%nterm <std::string> item; 79%token <std::string> TEXT; 80%token <int> NUMBER; 81item: 82 TEXT 83| NUMBER { $$ = std::to_string ($1); } 84; 85%% 86namespace yy 87{ 88 // Report an error to the user. 89 auto parser::error (const std::string& msg) -> void 90 { 91 std::cerr << msg << '\n'; 92 } 93} 94 95int main () 96{ 97 yy::parser parse; 98 return parse (); 99} 100