]> git.saurik.com Git - bison.git/blob - tests/c++.at
doc: fixes in the C++ part
[bison.git] / tests / c++.at
1 # Checking the C++ Features. -*- Autotest -*-
2
3 # Copyright (C) 2004-2005, 2007-2015 Free Software Foundation, Inc.
4
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 AT_BANNER([[C++ Features.]])
19
20
21 ## --------------- ##
22 ## C++ Locations. ##
23 ## --------------- ##
24
25 AT_SETUP([C++ Locations])
26
27 AT_BISON_OPTION_PUSHDEFS([%locations %skeleton "lalr1.cc"])
28 AT_DATA_GRAMMAR([[input.y]],
29 [[%code {#include <sstream>}
30 %locations
31 %debug
32 %skeleton "lalr1.cc"
33 %code
34 {
35 ]AT_YYERROR_DECLARE[
36 ]AT_YYLEX_DECLARE[
37 }
38 %%
39 exp: %empty;
40 %%
41 ]AT_YYERROR_DEFINE[
42 ]AT_YYLEX_DEFINE[
43
44 template <typename T>
45 bool
46 check (const T& in, const std::string& s)
47 {
48 std::stringstream os;
49 os << in;
50 if (os.str () != s)
51 {
52 std::cerr << "fail: " << os.str () << ", expected: " << s << std::endl;
53 return false;
54 }
55 return true;
56 }
57
58 int
59 main (void)
60 {
61 int fail = 0;
62 ]AT_YYLTYPE[ loc; fail += check (loc, "1.1");
63 fail += check (loc + 10, "1.1-10");
64 loc += 10; fail += check (loc, "1.1-10");
65 loc += -5; fail += check (loc, "1.1-5");
66 fail += check (loc - 5, "1.1");
67 loc -= 5; fail += check (loc, "1.1");
68 // Check that we don't go below.
69 // http://lists.gnu.org/archive/html/bug-bison/2013-02/msg00000.html
70 loc -= 10; fail += check (loc, "1.1");
71
72 loc.columns (10); loc.lines (10); fail += check (loc, "1.1-11.0");
73 loc.lines (-2); fail += check (loc, "1.1-9.0");
74 loc.lines (-10); fail += check (loc, "1.1");
75
76 ]AT_YYLTYPE[ loc2 (YY_NULLPTR, 5, 10);
77 fail += check (loc2, "5.10");
78 fail += check (loc + loc2, "1.1-5.9");
79 loc += loc2; fail += check (loc, "1.1-5.9");
80 return !fail;
81 }
82 ]])
83
84 AT_FULL_COMPILE([input])
85 AT_PARSER_CHECK([./input], 0)
86 AT_BISON_OPTION_POPDEFS
87 AT_CLEANUP
88
89
90 ## --------------------------- ##
91 ## C++ Variant-based Symbols. ##
92 ## --------------------------- ##
93
94 AT_SETUP([C++ Variant-based Symbols])
95
96 AT_KEYWORDS([variant])
97
98 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc" %debug $1])
99 # Store strings and integers in a vector of strings.
100 AT_DATA_GRAMMAR([list.y],
101 [[%skeleton "lalr1.cc"
102 %define api.value.type variant
103 %define parse.assert
104 %debug
105
106 %code top
107 {
108 // Get access to stack_symbol_type for the tests.
109 # define private public
110 }
111 %code provides
112 {
113 ]AT_YYLEX_DECLARE[
114 }
115
116 %token <int> INT "int"
117 %type < std::vector<int> > exp
118
119 %printer { yyo << $$; } <int>
120 %printer
121 {
122 for (std::vector<int>::const_iterator i = $$.begin (); i != $$.end (); ++i)
123 {
124 if (i != $$.begin ())
125 yyo << ", ";
126 yyo << *i;
127 }
128 } < std::vector<int> >
129
130 %code requires { #include <vector> }
131 %code { int yylex (yy::parser::semantic_type* yylval); }
132
133 %%
134 exp: "int" { $$.push_back ($1); }
135 %%
136 ]AT_YYERROR_DEFINE[
137 ]AT_YYLEX_DEFINE[
138
139 int main()
140 {
141 {
142 yy::parser::symbol_type s = yy::parser::make_INT(12);
143 std::cerr << s.value.as<int>() << std::endl;
144 }
145
146 {
147 yy::parser::symbol_type s = yy::parser::make_INT(123);
148 yy::parser::stack_symbol_type ss(1, s);
149 std::cerr << ss.value.as<int>() << std::endl;
150 }
151
152 {
153 yy::parser::stack_type st;
154 for (int i = 0; i < 100; ++i)
155 {
156 yy::parser::symbol_type s(yy::parser::make_INT(i));
157 yy::parser::stack_symbol_type ss(1, s);
158 st.push(ss);
159 }
160 }
161 }
162 ]])
163
164 AT_FULL_COMPILE([list])
165 AT_PARSER_CHECK([./list], 0, [],
166 [12
167 123
168 ])
169
170 AT_BISON_OPTION_POPDEFS
171 AT_CLEANUP
172
173
174 ## ---------- ##
175 ## Variants. ##
176 ## ---------- ##
177
178 # Check that the variants are properly supported, including in error
179 # recovery.
180
181 # AT_TEST([DIRECTIVES])
182 # ---------------------
183 # Check the support of variants in C++, with the additional DIRECTIVES.
184 m4_pushdef([AT_TEST],
185 [AT_SETUP([Variants $1])
186
187 AT_BISON_OPTION_PUSHDEFS([%debug $1])
188 # Store strings and integers in a vector of strings.
189 AT_DATA_GRAMMAR([list.y],
190 [[%debug
191 %define api.value.type variant
192 ]m4_bpatsubst([$1], [\\n], [
193 ])[
194
195 %code requires // code for the .hh file
196 {
197 #include <vector>
198 #include <string>
199 typedef std::vector<std::string> strings_type;
200 }
201
202 %code top // code for the .cc file.
203 {
204 #include <cstdlib> // abort, getenv
205 #include <iostream>
206 #include <vector>
207 #include <sstream>
208 #include <string>
209
210
211 typedef std::vector<std::string> strings_type;
212
213 namespace yy
214 {
215 // Must be available early, as is used in %destructor.
216 std::ostream&
217 operator<<(std::ostream& o, const strings_type& s)
218 {
219 o << '(';
220 for (strings_type::const_iterator i = s.begin (); i != s.end (); ++i)
221 {
222 if (i != s.begin ())
223 o << ", ";
224 o << *i;
225 }
226 return o << ')';
227 }
228 }
229 }
230
231 %code // code for the .cc file.
232 {
233 namespace yy
234 {
235 static]AT_TOKEN_CTOR_IF([[
236 parser::symbol_type yylex ()]], [[
237 parser::token_type yylex (parser::semantic_type* yylval]AT_LOCATION_IF([,
238 parser::location_type* yylloc])[)]])[;
239
240 // Conversion to string.
241 template <typename T>
242 inline
243 std::string
244 to_string (const T& t)
245 {
246 std::ostringstream o;
247 o << t;
248 return o.str ();
249 }
250 }
251 }
252
253 %token <::std::string> TEXT;
254 %token <int> NUMBER;
255 %token END_OF_FILE 0;
256 %token COMMA ","
257
258 %type <::std::string> item;
259 // Using the template type to exercize its parsing.
260 // Starting with :: to ensure we don't output "<::" which starts by the
261 // digraph for the left square bracket.
262 %type <::std::vector<std::string>> list;
263
264 %printer { yyo << $$; }
265 <int> <::std::string> <::std::vector<std::string>>;
266 %destructor { std::cerr << "Destroy: " << $$ << '\n'; } <*>;
267 %destructor { std::cerr << "Destroy: \"" << $$ << "\"\n"; } <::std::string>;
268 %%
269
270 result:
271 list { std::cout << $][1 << std::endl; }
272 ;
273
274 list:
275 item { $$.push_back ($][1); }
276 | list "," item { std::swap ($$, $][1); $$.push_back ($][3); }
277 | list error { std::swap ($$, $][1); }
278 ;
279
280 item:
281 TEXT { std::swap ($$, $][1); }
282 | NUMBER { if ($][1 == 3) YYERROR; else $$ = to_string ($][1); }
283 ;
284 %%
285 ]AT_TOKEN_CTOR_IF([],
286 [[#ifdef TWO_STAGE_BUILD
287 # define BUILD(Type, Value) build<Type> () = Value
288 #else
289 # define BUILD(Type, Value) build (Value)
290 #endif
291 ]])[
292 #define STAGE_MAX 5
293 namespace yy
294 {
295 static]AT_TOKEN_CTOR_IF([[
296 parser::symbol_type yylex ()]], [[
297 parser::token_type yylex (parser::semantic_type* yylval]AT_LOCATION_IF([,
298 parser::location_type* yylloc])[)]])[
299 {]AT_LOCATION_IF([
300 typedef parser::location_type location;])[
301 // The 5 is a syntax error whose recovery requires that we discard
302 // the lookahead. This tests a regression, see
303 // <http://savannah.gnu.org/support/?108481>.
304 static char const *input = "0,1,2,3,45,6";
305 switch (int stage = *input++)
306 {
307 case 0:]AT_TOKEN_CTOR_IF([[
308 return parser::make_END_OF_FILE (]AT_LOCATION_IF([location ()])[);]],
309 [AT_LOCATION_IF([
310 *yylloc = location ();])[
311 return parser::token::END_OF_FILE;]])[
312
313 case ',':
314 ]AT_TOKEN_CTOR_IF([[
315 return parser::make_COMMA (]AT_LOCATION_IF([location ()])[);]], [[
316 ]AT_LOCATION_IF([
317 *yylloc = location ();])[
318 return parser::token::COMMA;]])[
319
320 default:
321 stage = stage - '0';
322 if (stage % 2)
323 {]AT_TOKEN_CTOR_IF([[
324 return parser::make_NUMBER (stage]AT_LOCATION_IF([, location ()])[);]], [[
325 yylval->BUILD (int, stage);]AT_LOCATION_IF([
326 *yylloc = location ();])[
327 return parser::token::NUMBER;]])[
328 }
329 else
330 {]AT_TOKEN_CTOR_IF([[
331 return parser::make_TEXT (to_string (stage)]AT_LOCATION_IF([, location ()])[);]], [[
332 yylval->BUILD (std::string, to_string (stage));]AT_LOCATION_IF([
333 *yylloc = location ();])[
334 return parser::token::TEXT;]])[
335 }
336 }
337
338 abort ();
339 }
340 }
341
342 ]AT_YYERROR_DEFINE[
343 ]AT_MAIN_DEFINE[
344 ]])
345
346 AT_FULL_COMPILE([list])
347 AT_PARSER_CHECK([./list], 0,
348 [[(0, 1, 2, 4, 6)
349 ]],
350 [[Destroy: ""
351 Destroy: "0"
352 Destroy: 1
353 Destroy: "1"
354 Destroy: ()
355 Destroy: ""
356 Destroy: "2"
357 Destroy: ()
358 Destroy: ""
359 Destroy: 3
360 Destroy: ()
361 Destroy: ""
362 Destroy: "4"
363 Destroy: ()
364 Destroy: ()
365 Destroy: 5
366 Destroy: ()
367 Destroy: ""
368 Destroy: "6"
369 Destroy: ()
370 Destroy: (0, 1, 2, 4, 6)
371 ]])
372
373 AT_BISON_OPTION_POPDEFS
374 AT_CLEANUP
375 ])
376
377 AT_TEST([[%skeleton "lalr1.cc" ]])
378 AT_TEST([[%skeleton "lalr1.cc" %define parse.assert]])
379 AT_TEST([[%skeleton "lalr1.cc" %define parse.assert %locations]])
380 AT_TEST([[%skeleton "lalr1.cc" %define parse.assert %code {\n#define TWO_STAGE_BUILD\n}]])
381 AT_TEST([[%skeleton "lalr1.cc" %define parse.assert %define api.token.constructor]])
382 AT_TEST([[%skeleton "lalr1.cc" %define parse.assert %define api.token.constructor %define api.token.prefix {TOK_}]])
383 AT_TEST([[%skeleton "lalr1.cc" %define parse.assert %define api.token.constructor %define api.token.prefix {TOK_} %locations]])
384
385 m4_popdef([AT_TEST])
386
387
388 ## ----------------------- ##
389 ## Doxygen Documentation. ##
390 ## ----------------------- ##
391
392 m4_define([AT_CHECK_DOXYGEN],
393 [m4_case([$1],
394 [Public], [m4_pushdef([AT_DOXYGEN_PRIVATE], [NO])],
395 [Private], [m4_pushdef([AT_DOXYGEN_PRIVATE], [YES])],
396 [m4_fatal([invalid argument: $1])])
397 AT_SETUP([Doxygen $1 Documentation])
398
399 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
400 AT_DATA([input.yy],
401 [[%skeleton "lalr1.cc"
402 %locations
403 %defines
404 %debug
405 %%
406 exp: /* empty */;
407 %%
408 ]AT_YYERROR_DEFINE[
409 ]])
410
411 AT_BISON_CHECK([-o input.cc input.yy])
412
413 AT_DATA([Doxyfile],
414 [# The PROJECT_NAME tag is a single word (or a sequence of words
415 # surrounded by quotes) that should identify the project.
416 PROJECT_NAME = "Bison C++ Parser"
417
418 # The QUIET tag can be used to turn on/off the messages that are
419 # generated by doxygen. Possible values are YES and NO. If left blank
420 # NO is used.
421 QUIET = YES
422
423 # The WARNINGS tag can be used to turn on/off the warning messages
424 # that are generated by doxygen. Possible values are YES and NO. If
425 # left blank NO is used.
426 WARNINGS = YES
427 # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate
428 # warnings for undocumented members. If EXTRACT_ALL is set to YES then
429 # this flag will automatically be disabled.
430 WARN_IF_UNDOCUMENTED = YES
431 # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings
432 # for potential errors in the documentation, such as not documenting
433 # some parameters in a documented function, or documenting parameters
434 # that don't exist or using markup commands wrongly.
435 WARN_IF_DOC_ERROR = YES
436 # The WARN_FORMAT tag determines the format of the warning messages
437 # that doxygen can produce. The string should contain the $file,
438 # $line, and $text tags, which will be replaced by the file and line
439 # number from which the warning originated and the warning text.
440 WARN_FORMAT = "$file:$line: $text"
441
442 # If the EXTRACT_ALL tag is set to YES doxygen will assume all
443 # entities in documentation are documented, even if no documentation
444 # was available. Private class members and static file members will
445 # be hidden unless the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set
446 # to YES
447 EXTRACT_ALL = YES
448
449 # If the EXTRACT_PRIVATE tag is set to YES all private members of a
450 # class will be included in the documentation.
451 EXTRACT_PRIVATE = AT_DOXYGEN_PRIVATE
452
453 # If the EXTRACT_STATIC tag is set to YES all static members of a file
454 # will be included in the documentation.
455 EXTRACT_STATIC = AT_DOXYGEN_PRIVATE
456 ])
457
458 AT_CHECK([doxygen --version || exit 77], 0, ignore)
459 AT_CHECK([doxygen], 0, [], [ignore])
460
461 AT_BISON_OPTION_POPDEFS
462 AT_CLEANUP
463
464 m4_popdef([AT_DOXYGEN_PRIVATE])
465 ])# AT_CHECK_DOXYGEN
466
467 AT_CHECK_DOXYGEN([Public])
468 AT_CHECK_DOXYGEN([Private])
469
470
471 ## ------------ ##
472 ## Namespaces. ##
473 ## ------------ ##
474
475 # AT_TEST(NAMESPACE-DECL, [COMPILE-ERROR])
476 # ----------------------------------------
477 # See if Bison can handle %define namespace "NAMESPACE-DECL". If COMPILE-ERROR
478 # is specified, then Bison should accept the input, but compilation will fail,
479 # so don't check compilation.
480 m4_pushdef([AT_TEST],
481 [AT_BISON_OPTION_PUSHDEFS([%language "C++" %define api.namespace {$1}])
482 AT_DATA_GRAMMAR([[input.yy]],
483 [[%language "C++"
484 %define api.namespace {]$1[}
485 %union { int i; }
486 %define global_tokens_and_yystype
487 %locations
488
489 %code {
490 // YYSTYPE contains a namespace reference.
491 int yylex (YYSTYPE *lval, const ]$1[::parser::location_type*) {
492 lval->i = 3;
493 return 0;
494 }
495 }
496
497 %%
498
499 start: ;
500
501 %%
502
503 void
504 ]$1[::parser::error (const ]$1[::parser::location_type &loc,
505 const std::string &msg)
506 {
507 std::cerr << "At " << loc << ": " << msg << std::endl;
508 }
509
510 ]AT_MAIN_DEFINE[
511 ]])
512
513
514 AT_BISON_CHECK([[-o input.cc input.yy]])
515
516 m4_if([$#], [1],
517 [AT_COMPILE_CXX([[input]])
518 AT_PARSER_CHECK([[./input]])])
519 AT_BISON_OPTION_POPDEFS
520 ])
521
522 AT_SETUP([[Relative namespace references]])
523 AT_TEST([[foo]])
524 AT_TEST([[foo::bar]])
525 AT_TEST([[foo::bar::baz]])
526 AT_CLEANUP
527
528 AT_SETUP([[Absolute namespace references]])
529 AT_TEST([[::foo]])
530 AT_TEST([[::foo::bar]])
531 AT_TEST([[::foo::bar::baz]])
532 AT_TEST([[@tb@::foo]])
533 AT_TEST([[ @tb@ ::foo::bar]])
534 AT_TEST([[ ::foo::bar::baz]])
535 AT_CLEANUP
536
537 AT_SETUP([[Syntactically invalid namespace references]])
538 AT_TEST([[:foo:bar]], [[-]])
539 AT_TEST([[foo: :bar]], [[-]])
540 # This one is interesting because '[3]' is encoded as '@<:@3@:>@', which
541 # contains single occurrences of ':'.
542 AT_TEST([[foo[3]::bar::baz]], [[-]])
543 AT_TEST([[foo::bar,baz]], [[-]])
544 AT_TEST([[foo::bar::(baz /* Pacify Emacs ) */]], [[-]])
545 AT_CLEANUP
546
547 m4_popdef([AT_TEST])
548
549 ## -------------------------------------- ##
550 ## Syntax error discarding no lookahead. ##
551 ## -------------------------------------- ##
552
553 # After a syntax error, lalr1.cc used to not check whether there
554 # actually is a lookahead before discarding the lookahead. As a result,
555 # it mistakenly invoked the destructor for the previous lookahead.
556
557 AT_SETUP([[Syntax error discarding no lookahead]])
558
559 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
560
561 AT_DATA_GRAMMAR([[input.y]],
562 [[%skeleton "lalr1.cc"
563
564 %code {
565 #include <string>
566 int yylex (yy::parser::semantic_type *);
567 #define USE(Args)
568 }
569
570 %define parse.error verbose
571
572 %nonassoc 'a' ;
573
574 %destructor {
575 std::cerr << "Discarding 'a'." << std::endl;
576 } 'a'
577
578 %%
579
580 start: error-reduce consistent-error 'a' { USE ($3); };
581
582 error-reduce:
583 'a' 'a' consistent-error 'a' { USE (($1, $2, $4)); }
584 | 'a' error { std::cerr << "Reducing 'a'." << std::endl; USE ($1); }
585 ;
586
587 consistent-error:
588 'a'
589 | /*empty*/ %prec 'a'
590 ;
591
592 // Provide another context in which all rules are useful so that this
593 // test case looks a little more realistic.
594 start: 'b' consistent-error ;
595
596 %%
597
598 int
599 yylex (yy::parser::semantic_type *)
600 {
601 static char const *input = "aa";
602 return *input++;
603 }
604
605 void
606 yy::parser::error (const std::string &m)
607 {
608 std::cerr << m << std::endl;
609 }
610
611 ]AT_MAIN_DEFINE[
612 ]])
613
614 AT_FULL_COMPILE([[input]])
615 # This used to print "Discarding 'a'." again at the end.
616 AT_PARSER_CHECK([[./input]], [[1]], [[]],
617 [[syntax error
618 Discarding 'a'.
619 Reducing 'a'.
620 ]])
621
622 AT_BISON_OPTION_POPDEFS
623 AT_CLEANUP
624
625
626 ## --------------------------- ##
627 ## Syntax error as exception. ##
628 ## --------------------------- ##
629
630 AT_SETUP([[Syntax error as exception]])
631
632 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
633
634 AT_DATA_GRAMMAR([[input.y]],
635 [[%skeleton "lalr1.cc"
636
637 %code
638 {
639 #include <cstdlib>
640 int yylex (yy::parser::semantic_type *);
641 }
642
643 %define api.value.type variant
644 %define parse.error verbose
645 %define parse.trace
646 %%
647
648 start:
649 thing
650 | start thing
651 ;
652
653 thing:
654 error { std::cerr << "caught error" << std::endl; }
655 | item
656 ;
657
658 item:
659 'a'
660 | 's'
661 {
662 throw yy::parser::syntax_error ("invalid expression");
663 }
664
665 %%
666
667 int
668 yylex (yy::parser::semantic_type *)
669 {
670 // 's': syntax error, 'l': lexical error.
671 static char const *input = "asal";
672 switch (int res = *input++)
673 {
674 case 'l':
675 throw yy::parser::syntax_error ("invalid character");
676 default:
677 return res;
678 }
679 }
680
681 void
682 yy::parser::error (const std::string &m)
683 {
684 std::cerr << "error: " << m << std::endl;
685 }
686 ]AT_MAIN_DEFINE[
687 ]])
688
689 AT_FULL_COMPILE([[input]])
690
691 AT_PARSER_CHECK([[./input]], [[0]], [[]],
692 [[error: invalid expression
693 caught error
694 error: invalid character
695 caught error
696 ]])
697
698 AT_BISON_OPTION_POPDEFS
699 AT_CLEANUP
700
701
702 ## ------------------ ##
703 ## Exception safety. ##
704 ## ------------------ ##
705
706 # AT_TEST([BISON-DIRECTIVES = ''], [WITH-RECOVERY = "with"])
707 # ----------------------------------------------------------
708 # Check that no object is leaked when exceptions are thrown.
709 # WITH-RECOVERY = "with" or "without".
710 m4_pushdef([AT_TEST],
711 [AT_SETUP([[Exception safety $2 error recovery $1]])
712
713 AT_SKIP_IF_EXCEPTION_SUPPORT_IS_POOR
714
715 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc" $1])
716
717 AT_DATA_GRAMMAR([[input.yy]],
718 [[%skeleton "lalr1.cc"
719 %debug
720 %error-verbose
721 $1
722 %code requires
723 {
724 #include <cassert>
725 #include <cstdlib> // size_t and getenv.
726 #include <iostream>
727 #include <set>
728 #include <string>
729
730 bool debug = false;
731
732 /// A class that tracks its instances.
733 struct Object
734 {
735 char val;
736
737 Object ()
738 : val ('?')
739 {
740 log (this, "Object::Object");
741 Object::instances.insert (this);
742 }
743
744 Object (const Object& that)
745 : val (that.val)
746 {
747 log (this, "Object::Object");
748 Object::instances.insert (this);
749 }
750
751 Object (char v)
752 : val (v)
753 {
754 log (this, "Object::Object");
755 Object::instances.insert (this);
756 }
757
758 ~Object ()
759 {
760 log (this, "Object::~Object");
761 objects::iterator i = instances.find (this);
762 // Make sure this object is alive.
763 assert (i != instances.end ());
764 Object::instances.erase (i);
765 }
766
767 Object& operator= (char v)
768 {
769 val = v;
770 return *this;
771 }
772
773 // Static part.
774 typedef std::set<const Object*> objects;
775 static objects instances;
776
777 static bool
778 empty ()
779 {
780 return instances.empty ();
781 }
782
783 static void
784 log (Object const *o, const std::string& msg)
785 {
786 if (debug)
787 {
788 if (o)
789 std::cerr << o << "->";
790 std::cerr << msg << " {";
791 const char* sep = " ";
792 for (objects::const_iterator i = instances.begin(),
793 i_end = instances.end();
794 i != i_end;
795 ++i)
796 {
797 std::cerr << sep << *i;
798 sep = ", ";
799 }
800 std::cerr << " }" << std::endl;
801 }
802 }
803 };
804 }
805
806 %code
807 {
808 #include <cassert>
809 #include <cstring> // strchr
810 #include <stdexcept>
811 int yylex (yy::parser::semantic_type *);
812 Object::objects Object::instances;
813 static char const *input;
814 }
815
816 ]AT_VARIANT_IF([[
817 %printer
818 {
819 yyo << &$$ << " '" << $$.val << '\'';
820 if ($$.val == 'p')
821 throw std::runtime_error ("printer");
822 } <Object>;
823
824 %token <Object> 'a' 'E' 'e' 'p' 'R' 's' 'T'
825 %type <Object> list item
826 ]], [[
827 %union
828 {
829 Object *obj;
830 }
831 %destructor { delete $$; } <obj>;
832 %printer
833 {
834 yyo << $$ << " '" << $$->val << '\'';
835 if ($$->val == 'p')
836 throw std::runtime_error ("printer");
837 } <obj>;
838
839 %token <obj> 'a' 'E' 'e' 'p' 'R' 's' 'T'
840 %type <obj> list item
841 ]])[
842
843 %initial-action
844 {
845 if (strchr (input, 'i'))
846 throw std::runtime_error ("initial-action");
847 }
848
849 %%
850
851 start: list {]AT_VARIANT_IF([], [ delete $][1]; )[};
852
853 list:
854 item { $$ = $][1; }
855 // Right recursion to load the stack.
856 | item list { $$ = $][1; ]AT_VARIANT_IF([], [delete $][2]; )[}
857 ;
858
859 item:
860 'a' { $$ = $][1; }
861 | 'e' { YYUSE ($$); YYUSE ($][1); error ("syntax error"); }
862 // Not just 'E', otherwise we reduce when 'E' is the lookahead, and
863 // then the stack is emptied, defeating the point of the test.
864 | 'E' 'a' { YYUSE ($][1); $$ = $][2; }
865 | 'R' { ]AT_VARIANT_IF([], [$$ = YY_NULLPTR; delete $][1]; )[YYERROR; }
866 | 'p' { $$ = $][1; }
867 | 's' { $$ = $][1; throw std::runtime_error ("reduction"); }
868 | 'T' { ]AT_VARIANT_IF([], [$$ = YY_NULLPTR; delete $][1]; )[YYABORT; }
869 ]m4_if([$2], [with],
870 [[| error { $$ = ]AT_VARIANT_IF([], [new ])[Object ('R'); yyerrok; }]])[
871 ;
872 %%
873
874 int
875 yylex (yy::parser::semantic_type *lvalp)
876 {
877 // 'a': no error.
878 // 'e': user action calls error.
879 // 'E': syntax error, with yyerror that throws.
880 // 'i': initial action throws.
881 // 'l': yylex throws.
882 // 'R': call YYERROR in the action
883 // 's': reduction throws.
884 // 'T': call YYABORT in the action
885 switch (int res = *input++)
886 {
887 case 'l':
888 throw std::runtime_error ("yylex");
889 default:
890 lvalp->]AT_VARIANT_IF([build (Object (res))],
891 [obj = new Object (res)])[;
892 // Fall through.
893 case 0:
894 return res;
895 }
896 }
897
898 /* A C++ error reporting function. */
899 void
900 yy::parser::error (const std::string& m)
901 {
902 throw std::runtime_error (m);
903 }
904
905 int
906 main (int argc, const char *argv[])
907 {
908 switch (argc)
909 {
910 case 2:
911 input = argv[1];
912 break;
913 case 3:
914 assert (std::string(argv[1]) == "--debug");
915 debug = 1;
916 input = argv[2];
917 break;
918 default:
919 abort ();
920 }
921
922 yy::parser parser;
923 debug |= !!getenv ("YYDEBUG");
924 parser.set_debug_level (debug);
925 int res = 2;
926 try
927 {
928 res = parser.parse ();
929 }
930 catch (const std::exception& e)
931 {
932 std::cerr << "exception caught: " << e.what () << std::endl;
933 }
934 catch (...)
935 {
936 std::cerr << "unknown exception caught" << std::endl;
937 }
938 Object::log (YY_NULLPTR, "end");
939 assert (Object::empty());
940 return res;
941 }
942 ]])
943 AT_BISON_CHECK([[-o input.cc --report=all input.yy]])
944 AT_COMPILE_CXX([[input]])
945
946 AT_PARSER_CHECK([[./input aaaas]], [[2]], [[]],
947 [[exception caught: reduction
948 ]])
949
950 AT_PARSER_CHECK([[./input aaaal]], [[2]], [[]],
951 [[exception caught: yylex
952 ]])
953
954 AT_PARSER_CHECK([[./input i]], [[2]], [[]],
955 [[exception caught: initial-action
956 ]])
957
958 AT_PARSER_CHECK([[./input aaaap]])
959
960 AT_PARSER_CHECK([[./input --debug aaaap]], [[2]], [[]], [[stderr]])
961 AT_CHECK([[grep '^exception caught: printer$' stderr]], [], [ignore])
962
963 AT_PARSER_CHECK([[./input aaaae]], [[2]], [[]],
964 [[exception caught: syntax error
965 ]])
966
967 AT_PARSER_CHECK([[./input aaaaE]], [[2]], [[]],
968 [[exception caught: syntax error, unexpected $end, expecting 'a'
969 ]])
970
971 AT_PARSER_CHECK([[./input aaaaT]], [[1]])
972
973 AT_PARSER_CHECK([[./input aaaaR]], [m4_if([$2], [with], [0], [1])])
974
975 AT_BISON_OPTION_POPDEFS
976
977 AT_CLEANUP
978 ])
979
980 AT_TEST([], [with])
981 AT_TEST([], [without])
982 AT_TEST([%define api.value.type variant], [with])
983 AT_TEST([%define api.value.type variant], [without])
984
985 m4_popdef([AT_TEST])
986
987 ## ------------------------------------- ##
988 ## C++ GLR parser identifier shadowing. ##
989 ## ------------------------------------- ##
990
991 AT_SETUP([[C++ GLR parser identifier shadowing]])
992
993 AT_DATA_GRAMMAR([input.yy], [
994 %skeleton "glr.cc"
995
996 %union
997 {
998 int ival;
999 }
1000
1001 %token <ival> ZERO;
1002
1003 %code
1004 {
1005 int yylex (yy::parser::semantic_type *yylval);
1006 }
1007
1008 %%
1009 exp: ZERO
1010
1011 %%
1012
1013 int yylex (yy::parser::semantic_type *yylval)
1014 {
1015 // Note: this argument is unused, but named on purpose. There used to be a
1016 // bug with a macro that erroneously expanded this identifier to
1017 // yystackp->yyval.
1018 YYUSE (yylval);
1019 return yy::parser::token::ZERO;
1020 }
1021
1022 void yy::parser::error (std::string const&)
1023 {}
1024
1025 int main ()
1026 {}
1027 ])
1028
1029 AT_BISON_CHECK([[-o input.cc input.yy]])
1030 AT_COMPILE_CXX([[input]])
1031
1032 AT_CLEANUP