]> git.saurik.com Git - bison.git/blob - tests/c++.at
tests: improve factoring of the main function
[bison.git] / tests / c++.at
1 # Checking the C++ Features. -*- Autotest -*-
2
3 # Copyright (C) 2004-2005, 2007-2013 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 ## Variants. ##
23 ## ---------- ##
24
25 # AT_TEST([DIRECTIVES])
26 # ---------------------
27 # Check the support of variants in C++, with the additional DIRECTIVES.
28 m4_pushdef([AT_TEST],
29 [AT_SETUP([Variants $1])
30
31 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc" $1])
32 # Store strings and integers in a list of strings.
33 AT_DATA_GRAMMAR([list.yy],
34 [[%debug
35 %skeleton "lalr1.cc"
36 %defines
37 %define api.value.type variant
38 ]m4_bpatsubst([$1], [\\n], [
39 ])[
40
41 %code requires // code for the .hh file
42 {
43 #include <list>
44 #include <string>
45 typedef std::list<std::string> strings_type;
46 }
47
48 %code // code for the .cc file
49 {
50 #include <cstdlib> // abort, getenv
51 #include <iostream>
52 #include <sstream>
53
54 namespace yy
55 {
56 static]AT_TOKEN_CTOR_IF([[
57 parser::symbol_type yylex ()]], [[
58 parser::token_type yylex (parser::semantic_type* yylval]AT_LOCATION_IF([,
59 parser::location_type* yylloc])[)]])[;
60 }
61
62 // Printing a list of strings (for %printer).
63 // Koening look up will look into std, since that's an std::list.
64 namespace std
65 {
66 std::ostream&
67 operator<<(std::ostream& o, const strings_type& s)
68 {
69 o << '(';
70 for (strings_type::const_iterator i = s.begin (); i != s.end (); ++i)
71 {
72 if (i != s.begin ())
73 o << ", ";
74 o << *i;
75 }
76 return o << ')';
77 }
78 }
79
80 // Conversion to string.
81 template <typename T>
82 inline
83 std::string
84 string_cast (const T& t)
85 {
86 std::ostringstream o;
87 o << t;
88 return o.str ();
89 }
90 }
91
92 %token <::std::string> TEXT;
93 %token <int> NUMBER;
94 %token END_OF_FILE 0;
95
96 %type <::std::string> item;
97 // Using the template type to exercize its parsing.
98 // Starting with :: to ensure we don't output "<::" which starts by the
99 // digraph for the left square bracket.
100 %type <::std::list<std::string>> list result;
101
102 %printer { yyo << $][$; }
103 <int> <::std::string> <::std::list<std::string>>;
104 %%
105
106 result:
107 list { std::cout << $][1 << std::endl; }
108 ;
109
110 list:
111 /* nothing */ { /* Generates an empty string list */ }
112 | list item { std::swap ($][$,$][1); $$.push_back ($][2); }
113 | list error { std::swap ($][$,$][1); }
114 ;
115
116 item:
117 TEXT { std::swap ($][$,$][1); }
118 | NUMBER { if ($][1 == 3) YYERROR; else $][$ = string_cast ($][1); }
119 ;
120 %%
121
122 #ifdef TWO_STAGE_BUILD
123 # define BUILD(Type, Value) build<Type> () = Value
124 #else
125 # define BUILD(Type, Value) build (Value)
126 #endif
127
128 #define STAGE_MAX 5
129 namespace yy
130 {
131 static]AT_TOKEN_CTOR_IF([[
132 parser::symbol_type yylex ()]], [[
133 parser::token_type yylex (parser::semantic_type* yylval]AT_LOCATION_IF([,
134 parser::location_type* yylloc])[)]])[
135 {]AT_LOCATION_IF([
136 typedef parser::location_type location;])[
137 static int stage = -1;
138 ++stage;
139 if (stage == STAGE_MAX)
140 {]AT_TOKEN_CTOR_IF([[
141 return parser::make_END_OF_FILE (]AT_LOCATION_IF([location ()])[);]],
142 [AT_LOCATION_IF([
143 *yylloc = location ();])[
144 return parser::token::END_OF_FILE;]])[
145 }
146 else if (stage % 2)
147 {]AT_TOKEN_CTOR_IF([[
148 return parser::make_NUMBER (stage]AT_LOCATION_IF([, location ()])[);]],
149 [[
150 yylval->BUILD (int, stage);]AT_LOCATION_IF([
151 *yylloc = location ();])[
152 return parser::token::NUMBER;]])[
153 }
154 else
155 {]AT_TOKEN_CTOR_IF([[
156 return parser::make_TEXT (string_cast (stage)]AT_LOCATION_IF([, location ()])[);]], [[
157 yylval->BUILD (std::string, string_cast (stage));]AT_LOCATION_IF([
158 *yylloc = location ();])[
159 return parser::token::TEXT;]])[
160 }
161 abort ();
162 }
163 }
164
165 ]AT_YYERROR_DEFINE[
166 ]AT_MAIN_DEFINE[
167 ]])
168
169 AT_BISON_CHECK([-o list.cc list.yy])
170 AT_COMPILE_CXX([list], [$NO_STRICT_ALIAS_CXXFLAGS list.cc])
171 AT_PARSER_CHECK([./list], 0,
172 [(0, 1, 2, 4)
173 ])
174
175 AT_BISON_OPTION_POPDEFS
176 AT_CLEANUP
177 ])
178
179 AT_TEST([])
180 AT_TEST([%define parse.assert])
181 AT_TEST([%locations %define parse.assert])
182 AT_TEST([[%define parse.assert %code {\n#define TWO_STAGE_BUILD\n}]])
183 AT_TEST([[%define parse.assert %define api.token.constructor]])
184 AT_TEST([[%define parse.assert %define api.token.constructor %define api.token.prefix "TOK_"]])
185 AT_TEST([[%locations %define parse.assert %define api.token.constructor %define api.token.prefix "TOK_"]])
186
187 m4_popdef([AT_TEST])
188
189
190 ## ----------------------- ##
191 ## Doxygen Documentation. ##
192 ## ----------------------- ##
193
194 m4_define([AT_CHECK_DOXYGEN],
195 [m4_case([$1],
196 [Public], [m4_pushdef([AT_DOXYGEN_PRIVATE], [NO])],
197 [Private], [m4_pushdef([AT_DOXYGEN_PRIVATE], [YES])],
198 [m4_fatal([invalid argument: $1])])
199 AT_SETUP([Doxygen $1 Documentation])
200
201 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
202 AT_DATA([input.yy],
203 [[%skeleton "lalr1.cc"
204 %locations
205 %debug
206 %defines
207 %%
208 exp:;
209 %%
210 ]AT_YYERROR_DEFINE[
211 ]])
212
213 AT_BISON_CHECK([-o input.cc input.yy], 0)
214
215 AT_DATA([Doxyfile],
216 [# The PROJECT_NAME tag is a single word (or a sequence of words
217 # surrounded by quotes) that should identify the project.
218 PROJECT_NAME = "Bison C++ Parser"
219
220 # The QUIET tag can be used to turn on/off the messages that are
221 # generated by doxygen. Possible values are YES and NO. If left blank
222 # NO is used.
223 QUIET = YES
224
225 # The WARNINGS tag can be used to turn on/off the warning messages
226 # that are generated by doxygen. Possible values are YES and NO. If
227 # left blank NO is used.
228 WARNINGS = YES
229 # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate
230 # warnings for undocumented members. If EXTRACT_ALL is set to YES then
231 # this flag will automatically be disabled.
232 WARN_IF_UNDOCUMENTED = YES
233 # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings
234 # for potential errors in the documentation, such as not documenting
235 # some parameters in a documented function, or documenting parameters
236 # that don't exist or using markup commands wrongly.
237 WARN_IF_DOC_ERROR = YES
238 # The WARN_FORMAT tag determines the format of the warning messages
239 # that doxygen can produce. The string should contain the $file,
240 # $line, and $text tags, which will be replaced by the file and line
241 # number from which the warning originated and the warning text.
242 WARN_FORMAT = "$file:$line: $text"
243
244 # If the EXTRACT_ALL tag is set to YES doxygen will assume all
245 # entities in documentation are documented, even if no documentation
246 # was available. Private class members and static file members will
247 # be hidden unless the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set
248 # to YES
249 EXTRACT_ALL = YES
250
251 # If the EXTRACT_PRIVATE tag is set to YES all private members of a
252 # class will be included in the documentation.
253 EXTRACT_PRIVATE = AT_DOXYGEN_PRIVATE
254
255 # If the EXTRACT_STATIC tag is set to YES all static members of a file
256 # will be included in the documentation.
257 EXTRACT_STATIC = AT_DOXYGEN_PRIVATE
258 ])
259
260 AT_CHECK([doxygen --version || exit 77], 0, ignore)
261 AT_CHECK([doxygen], 0, [], [ignore])
262
263 AT_BISON_OPTION_POPDEFS
264 AT_CLEANUP
265
266 m4_popdef([AT_DOXYGEN_PRIVATE])
267 ])# AT_CHECK_DOXYGEN
268
269 AT_CHECK_DOXYGEN([Public])
270 AT_CHECK_DOXYGEN([Private])
271
272
273 ## ------------ ##
274 ## Namespaces. ##
275 ## ------------ ##
276
277 # AT_CHECK_NAMESPACE(NAMESPACE-DECL, [COMPILE-ERROR])
278 # ---------------------------------------------------
279 # See if Bison can handle %define namespace "NAMESPACE-DECL". If COMPILE-ERROR
280 # is specified, then Bison should accept the input, but compilation will fail,
281 # so don't check compilation.
282 m4_define([AT_CHECK_NAMESPACE],
283 [
284
285 AT_DATA_GRAMMAR([[input.y]],
286 [[%language "C++"
287 %defines
288 %define api.namespace "]$1["
289 %union { int i; }
290 %define global_tokens_and_yystype
291 %locations
292
293 %code {
294 // YYSTYPE contains a namespace reference.
295 int yylex (YYSTYPE *lval, const ]$1[::parser::location_type*) {
296 lval->i = 3;
297 return 0;
298 }
299 }
300
301 %%
302
303 start: ;
304
305 %%
306
307 void
308 ]$1[::parser::error (const ]$1[::parser::location_type &loc,
309 const std::string &msg)
310 {
311 std::cerr << "At " << loc << ": " << msg << std::endl;
312 }
313
314 int
315 main ()
316 {
317 ]$1[::parser p;
318 return p.parse ();
319 }
320 ]])
321
322 AT_BISON_CHECK([[-o input.cc input.y]])
323
324 m4_if([$#], [1],
325 [AT_COMPILE_CXX([[input]], [[input.cc]])
326 AT_PARSER_CHECK([[./input]])])
327
328 ])
329
330 AT_SETUP([[Relative namespace references]])
331 AT_CHECK_NAMESPACE([[foo]])
332 AT_CHECK_NAMESPACE([[foo::bar]])
333 AT_CHECK_NAMESPACE([[foo::bar::baz]])
334 AT_CLEANUP
335
336 AT_SETUP([[Absolute namespace references]])
337 AT_CHECK_NAMESPACE([[::foo]])
338 AT_CHECK_NAMESPACE([[::foo::bar]])
339 AT_CHECK_NAMESPACE([[::foo::bar::baz]])
340 AT_CHECK_NAMESPACE([[ ::foo]])
341 AT_CHECK_NAMESPACE([[ ::foo::bar]])
342 AT_CHECK_NAMESPACE([[ ::foo::bar::baz]])
343 AT_CLEANUP
344
345 AT_SETUP([[Syntactically invalid namespace references]])
346 AT_CHECK_NAMESPACE([[:foo:bar]], [[-]])
347 AT_CHECK_NAMESPACE([[foo: :bar]], [[-]])
348 # This one is interesting because `[3]' is encoded as `@<:@3@:>@', which
349 # contains single occurrences of `:'.
350 AT_CHECK_NAMESPACE([[foo[3]::bar::baz]], [[-]])
351 AT_CHECK_NAMESPACE([[foo::bar,baz]], [[-]])
352 AT_CHECK_NAMESPACE([[foo::bar::(baz /* Pacify Emacs ) */]], [[-]])
353 AT_CLEANUP
354
355
356 ## -------------------------------------- ##
357 ## Syntax error discarding no lookahead. ##
358 ## -------------------------------------- ##
359
360 # After a syntax error, lalr1.cc used to not check whether there
361 # actually is a lookahead before discarding the lookahead. As a result,
362 # it mistakenly invoked the destructor for the previous lookahead.
363
364 AT_SETUP([[Syntax error discarding no lookahead]])
365
366 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
367
368 AT_DATA_GRAMMAR([[input.yy]],
369 [[%skeleton "lalr1.cc"
370
371 %code {
372 #include <string>
373 int yylex (yy::parser::semantic_type *);
374 #define USE(Args)
375 }
376
377 %defines
378 %define parse.error verbose
379
380 %nonassoc 'a' ;
381
382 %destructor {
383 std::cerr << "Discarding 'a'." << std::endl;
384 } 'a'
385
386 %%
387
388 start: error-reduce consistent-error 'a' { USE ($3); };
389
390 error-reduce:
391 'a' 'a' consistent-error 'a' { USE (($1, $2, $4)); }
392 | 'a' error { std::cerr << "Reducing 'a'." << std::endl; USE ($1); }
393 ;
394
395 consistent-error:
396 'a'
397 | /*empty*/ %prec 'a'
398 ;
399
400 // Provide another context in which all rules are useful so that this
401 // test case looks a little more realistic.
402 start: 'b' consistent-error ;
403
404 %%
405
406 int
407 yylex (yy::parser::semantic_type *)
408 {
409 static char const *input = "aa";
410 return *input++;
411 }
412
413 void
414 yy::parser::error (const std::string &m)
415 {
416 std::cerr << m << std::endl;
417 }
418
419 ]AT_MAIN_DEFINE[
420 ]])
421
422 AT_BISON_CHECK([[-o input.cc input.yy]])
423 AT_COMPILE_CXX([[input]])
424 # This used to print "Discarding 'a'." again at the end.
425 AT_PARSER_CHECK([[./input]], [[1]], [[]],
426 [[syntax error
427 Discarding 'a'.
428 Reducing 'a'.
429 ]])
430
431 AT_BISON_OPTION_POPDEFS
432 AT_CLEANUP
433
434
435 ## --------------------------- ##
436 ## Syntax error as exception. ##
437 ## --------------------------- ##
438
439 AT_SETUP([[Syntax error as exception]])
440
441 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
442
443 AT_DATA_GRAMMAR([[input.yy]],
444 [[%skeleton "lalr1.cc"
445
446 %code
447 {
448 #include <cstdlib>
449 int yylex (yy::parser::semantic_type *);
450 }
451
452 %defines
453 %define api.value.type variant
454 %define parse.error verbose
455 %define parse.trace
456 %%
457
458 start:
459 thing
460 | start thing
461 ;
462
463 thing:
464 error { std::cerr << "caught error" << std::endl; }
465 | item
466 ;
467
468 item:
469 'a'
470 | 's'
471 {
472 throw yy::parser::syntax_error ("invalid expression");
473 }
474
475 %%
476
477 int
478 yylex (yy::parser::semantic_type *)
479 {
480 // 's': syntax error, 'l': lexical error.
481 static char const *input = "asal";
482 switch (int res = *input++)
483 {
484 case 'l':
485 throw yy::parser::syntax_error ("invalid character");
486 default:
487 return res;
488 }
489 }
490
491 void
492 yy::parser::error (const std::string &m)
493 {
494 std::cerr << "error: " << m << std::endl;
495 }
496 ]AT_MAIN_DEFINE[
497 ]])
498
499 AT_BISON_CHECK([[-o input.cc input.yy]])
500 AT_COMPILE_CXX([[input]])
501
502 AT_PARSER_CHECK([[./input]], [[0]], [[]],
503 [[error: invalid expression
504 caught error
505 error: invalid character
506 caught error
507 ]])
508
509 AT_BISON_OPTION_POPDEFS
510 AT_CLEANUP
511
512
513 ## ------------------ ##
514 ## Exception safety. ##
515 ## ------------------ ##
516
517 AT_SETUP([[Exception safety]])
518
519 AT_BISON_OPTION_PUSHDEFS([%skeleton "lalr1.cc"])
520
521 AT_DATA_GRAMMAR([[input.yy]],
522 [[%skeleton "lalr1.cc"
523 %defines // FIXME: Mandated in 2.6.
524 %debug
525 %error-verbose
526
527 %code requires
528 {
529 #include <cassert>
530 #include <cstdlib> // size_t and getenv.
531 #include <iostream>
532 #include <list>
533
534 bool debug = false;
535
536 /// A class that counts its number of instances.
537 struct Object
538 {
539 typedef std::list<const Object*> objects;
540 static objects instances;
541 char val;
542
543 static bool
544 empty ()
545 {
546 return instances.empty();
547 }
548
549 static void
550 log (Object const *o, const std::string& msg)
551 {
552 if (debug)
553 {
554 if (o)
555 std::cerr << o << "->";
556 std::cerr << msg << " {";
557 const char* sep = " ";
558 for (objects::const_iterator i = instances.begin(),
559 i_end = instances.end();
560 i != i_end;
561 ++i)
562 {
563 std::cerr << sep << *i;
564 sep = ", ";
565 }
566 std::cerr << " }" << std::endl;
567 }
568 }
569
570 Object (char v)
571 : val (v)
572 {
573 instances.push_back(this);
574 log (this, "Object::Object");
575 }
576
577 ~Object ()
578 {
579 instances.remove(this);
580 log (this, "Object::~Object");
581 }
582 };
583 }
584
585 %code
586 {
587 #include <cassert>
588 #include <cstring> // strchr
589 #include <stdexcept>
590 int yylex (yy::parser::semantic_type *);
591 Object::objects Object::instances;
592 static char const *input;
593 }
594
595 %union
596 {
597 Object *obj;
598 }
599
600 %initial-action
601 {
602 if (strchr (input, 'i'))
603 throw std::runtime_error ("initial-action");
604 }
605
606 %destructor { delete $$; } <obj>;
607 %printer
608 {
609 yyo << $$ << " '" << $$->val << '\'';
610 if ($$->val == 'p')
611 throw std::runtime_error ("printer");
612 } <obj>;
613
614 %token <obj> 'a' 'E' 'e' 'p' 'R' 's' 'T'
615 %type <obj> list item
616
617 %%
618
619 start: list { delete $1; };
620
621 list:
622 item { $$ = $1; }
623 | item list { $$ = $1; delete $2; } // Right recursion to load the stack.
624 ;
625
626 item:
627 'a' { $$ = $1; }
628 | 'e' { YYUSE ($$); YYUSE($1); error ("syntax error"); }
629 // Not just 'E', otherwise we reduce when 'E' is the lookahead, and
630 // then the stack is emptied, defeating the point of the test.
631 | 'E' 'a' { YYUSE($1); $$ = $2; }
632 | 'R' { $$ = YY_NULL; delete $1; YYERROR; }
633 | 'p' { $$ = $1; }
634 | 's' { $$ = $1; throw std::runtime_error ("reduction"); }
635 | 'T' { $$ = YY_NULL; delete $1; YYABORT; }
636 | error { $$ = YY_NULL; yyerrok; }
637 ;
638 %%
639
640 int
641 yylex (yy::parser::semantic_type *lvalp)
642 {
643 // 'a': no error.
644 // 'e': user action calls error.
645 // 'E': syntax error, with yyerror that throws.
646 // 'i': initial action throws.
647 // 'l': yylex throws.
648 // 'R': call YYERROR in the action
649 // 's': reduction throws.
650 // 'T': call YYABORT in the action
651 switch (int res = *input++)
652 {
653 case 'l':
654 throw std::runtime_error ("yylex");
655 default:
656 lvalp->obj = new Object (res);
657 // Fall through.
658 case 0:
659 return res;
660 }
661 }
662
663 /* A C++ error reporting function. */
664 void
665 yy::parser::error (const std::string& m)
666 {
667 throw std::runtime_error (m);
668 }
669
670 int
671 main (int argc, const char *argv[])
672 {
673 switch (argc)
674 {
675 case 2:
676 input = argv[1];
677 break;
678 case 3:
679 assert (std::string(argv[1]) == "--debug");
680 debug = 1;
681 input = argv[2];
682 break;
683 default:
684 abort ();
685 }
686
687 yy::parser parser;
688 debug |= !!getenv ("YYDEBUG");
689 parser.set_debug_level (debug);
690 int res = 2;
691 try
692 {
693 res = parser.parse ();
694 }
695 catch (const std::exception& e)
696 {
697 std::cerr << "exception caught: " << e.what () << std::endl;
698 }
699 catch (...)
700 {
701 std::cerr << "unknown exception caught" << std::endl;
702 }
703 Object::log (YY_NULL, "end");
704 assert (Object::empty());
705 return res;
706 }
707 ]])
708 AT_BISON_CHECK([[-o input.cc --report=all input.yy]])
709 AT_COMPILE_CXX([[input]])
710
711 AT_PARSER_CHECK([[./input aaaas]], [[2]], [[]],
712 [[exception caught: reduction
713 ]])
714
715 AT_PARSER_CHECK([[./input aaaal]], [[2]], [[]],
716 [[exception caught: yylex
717 ]])
718
719 AT_PARSER_CHECK([[./input i]], [[2]], [[]],
720 [[exception caught: initial-action
721 ]])
722
723 AT_PARSER_CHECK([[./input aaaap]])
724
725 AT_PARSER_CHECK([[./input --debug aaaap]], [[2]], [[]], [[stderr]])
726 AT_CHECK([[grep '^exception caught: printer$' stderr]], [], [ignore])
727
728 AT_PARSER_CHECK([[./input aaaae]], [[2]], [[]],
729 [[exception caught: syntax error
730 ]])
731
732 AT_PARSER_CHECK([[./input aaaaE]], [[2]], [[]],
733 [[exception caught: syntax error, unexpected $end, expecting 'a'
734 ]])
735
736 AT_PARSER_CHECK([[./input aaaaT]], [[1]])
737
738 # There is error-recovery, so exit success.
739 AT_PARSER_CHECK([[./input aaaaR]], [[0]])
740
741 AT_BISON_OPTION_POPDEFS
742
743 AT_CLEANUP
744
745 ## ------------------------------------ ##
746 ## C++ GLR parser identifier shadowing ##
747 ## ------------------------------------ ##
748
749 AT_SETUP([[C++ GLR parser identifier shadowing]])
750
751 AT_DATA_GRAMMAR([input.yy], [
752 %skeleton "glr.cc"
753
754 %union
755 {
756 int ival;
757 }
758
759 %token <ival> ZERO;
760
761 %code
762 {
763 int yylex (yy::parser::semantic_type *yylval);
764 }
765
766 %%
767 exp: ZERO
768
769 %%
770
771 int yylex (yy::parser::semantic_type *yylval)
772 {
773 // Note: this argument is unused, but named on purpose. There used to be a
774 // bug with a macro that erroneously expanded this identifier to
775 // yystackp->yyval.
776 YYUSE (yylval);
777 return yy::parser::token::ZERO;
778 }
779
780 void yy::parser::error (std::string const&)
781 {}
782
783 int main()
784 {}
785 ])
786
787 AT_BISON_CHECK([[-o input.cc input.yy]])
788 AT_COMPILE_CXX([[input]])
789
790 AT_CLEANUP