doc: improve calling-convention doc
[bison.git] / doc / bison.texi
blob69c92c0bbad96f4d29237a67325fc1f45c00a6d8
1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename bison.info
4 @documentencoding UTF-8
5 @include version.texi
6 @settitle Bison @value{VERSION}
7 @xrefautomaticsectiontitle on
9 @c cite a reference in text.  Could not find a means to have a single
10 @c definition that looks nice in all the output formats.
11 @iftex
12 @macro tcite{ref}
13 @ref{\ref\,,\ref\}
14 @end macro
15 @end iftex
16 @ifnottex
17 @macro tcite{ref}
18 @ref{\ref\}
19 @end macro
20 @end ifnottex
22 @c cite a reference in parentheses.
23 @iftex
24 @macro pcite{ref}
25 (@pxref{\ref\,,\ref\})
26 @end macro
27 @end iftex
28 @ifnottex
29 @macro pcite{ref}
30 (@pxref{\ref\})
31 @end macro
32 @end ifnottex
35 @c ## ---------------------- ##
36 @c ## Diagnostics in color.  ##
37 @c ## ---------------------- ##
39 @tex
40 \gdef\rgbGreen{0 .80 0}
41 \gdef\colorGreen{%
42  \setcolor{\rgbGreen}%
44 \gdef\rgbYellow{1 .5 0}
45 \gdef\colorYellow{%
46  \setcolor{\rgbYellow}%
48 \gdef\rgbRed{1 0 0}
49 \gdef\colorRed{%
50  \setcolor{\rgbRed}%
52 \gdef\rgbBlue{0 0 1}
53 \gdef\colorBlue{%
54  \setcolor{\rgbBlue}%
56 \gdef\rgbPurple{0.50 0 0.50}
57 \gdef\colorPurple{%
58  \setcolor{\rgbPurple}%
60 \gdef\colorOff{%
61  \setcolor{\maincolor}%
64 \gdef\rgbError{0.80 0 0}
65 \gdef\diagError{%
66  \setcolor{\rgbError}%
68 \gdef\rgbNotice{0 0 0.80}
69 \gdef\diagNotice{%
70  \setcolor{\rgbNotice}%
72 \gdef\rgbWarning{0.50 0 0.50}
73 \gdef\diagWarning{%
74  \setcolor{\rgbWarning}%
76 \gdef\diagOff{%
77  \setcolor{\maincolor}%
79 @end tex
81 @ifnottex
82 @macro colorGreen
83 @inlineraw{html, <span style="color:green">}
84 @end macro
85 @macro colorYellow
86 @inlineraw{html, <span style="color:#ff8000">}
87 @end macro
88 @macro colorRed
89 @inlineraw{html, <span style="color:red">}
90 @end macro
91 @macro colorBlue
92 @inlineraw{html, <span style="color:blue">}
93 @end macro
94 @macro colorPurple
95 @inlineraw{html, <span style="color:darkviolet">}
96 @end macro
97 @macro colorOff
98 @inlineraw{html, </span>}
99 @end macro
101 @macro diagError
102 @inlineraw{html, <b style="color:red">}
103 @end macro
104 @macro diagNotice
105 @inlineraw{html, <b style="color:darkcyan">}
106 @end macro
107 @macro diagWarning
108 @inlineraw{html, <b style="color:darkviolet">}
109 @end macro
110 @macro diagOff
111 @inlineraw{html, </b>}
112 @end macro
113 @end ifnottex
115 @macro green{text}
116 @colorGreen{}\text\@colorOff{}
117 @end macro
119 @macro yellow{text}
120 @colorYellow{}\text\@colorOff{}
121 @end macro
123 @macro red{text}
124 @colorRed{}\text\@colorOff{}
125 @end macro
127 @macro blue{text}
128 @colorBlue{}\text\@colorOff{}
129 @end macro
131 @macro purple{text}
132 @colorPurple{}\text\@colorOff{}
133 @end macro
135 @macro dwarning{text}
136 @diagWarning{}\text\@diagOff{}
137 @end macro
139 @macro derror{text}
140 @diagError{}\text\@diagOff{}
141 @end macro
143 @macro dnotice{text}
144 @diagNotice{}\text\@diagOff{}
145 @end macro
147 @finalout
149 @c SMALL BOOK version
150 @c This edition has been formatted so that you can format and print it in
151 @c the smallbook format.
152 @c @smallbook
153 @c @setchapternewpage odd
155 @c Set following if you want to document %default-prec and %no-default-prec.
156 @c This feature is experimental and may change in future Bison versions.
157 @c @set defaultprec
159 @ifnotinfo
160 @syncodeindex fn cp
161 @syncodeindex vr cp
162 @syncodeindex tp cp
163 @end ifnotinfo
164 @ifinfo
165 @synindex fn cp
166 @synindex vr cp
167 @synindex tp cp
168 @end ifinfo
169 @comment %**end of header
171 @copying
173 This manual (@value{UPDATED}) is for GNU Bison (version @value{VERSION}),
174 the GNU parser generator.
176 Copyright @copyright{} 1988--1993, 1995, 1998--2015, 2018--2022 Free
177 Software Foundation, Inc.
179 @quotation
180 Permission is granted to copy, distribute and/or modify this document under
181 the terms of the GNU Free Documentation License, Version 1.3 or any later
182 version published by the Free Software Foundation; with no Invariant
183 Sections, with the Front-Cover texts being ``A GNU Manual,'' and with the
184 Back-Cover Texts as in (a) below.  A copy of the license is included in the
185 section entitled ``GNU Free Documentation License.''
187 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and modify
188 this GNU manual.  Buying copies from the FSF supports it in developing GNU
189 and promoting software freedom.''
190 @end quotation
191 @end copying
193 @dircategory Software development
194 @direntry
195 * bison: (bison).       GNU parser generator (Yacc replacement).
196 @end direntry
198 @titlepage
199 @title Bison
200 @subtitle The Yacc-compatible Parser Generator
201 @subtitle @value{UPDATED}, Bison Version @value{VERSION}
203 @author by Charles Donnelly and Richard Stallman
205 @page
206 @vskip 0pt plus 1filll
207 @insertcopying
208 @sp 2
209 Published by the Free Software Foundation @*
210 51 Franklin Street, Fifth Floor @*
211 Boston, MA  02110-1301  USA @*
212 Printed copies are available from the Free Software Foundation.@*
213 ISBN 1-882114-44-2
214 @sp 2
215 Cover art by Etienne Suvasa.
216 @end titlepage
218 @contents
220 @ifnottex
221 @node Top
222 @top Bison
223 @insertcopying
224 @end ifnottex
226 @menu
227 * Introduction::        What GNU Bison is.
228 * Conditions::          Conditions for using Bison and its output.
229 * Copying::             The GNU General Public License says
230                           how you can copy and share Bison.
232 Tutorial sections:
233 * Concepts::            Basic concepts for understanding Bison.
234 * Examples::            Three simple explained examples of using Bison.
236 Reference sections:
237 * Grammar File::        Writing Bison declarations and rules.
238 * Interface::           C-language interface to the parser function @code{yyparse}.
239 * Algorithm::           How the Bison parser works at run-time.
240 * Error Recovery::      Writing rules for error recovery.
241 * Context Dependency::  What to do if your language syntax is too
242                           messy for Bison to handle straightforwardly.
243 * Debugging::           Understanding or debugging Bison parsers.
244 * Invocation::          How to run Bison (to produce the parser implementation).
245 * Other Languages::     Creating C++, D and Java parsers.
246 * History::             How Bison came to be
247 * Versioning::          Dealing with Bison versioning
248 * FAQ::                 Frequently Asked Questions
249 * Table of Symbols::    All the keywords of the Bison language are explained.
250 * Glossary::            Basic concepts are explained.
251 * GNU Free Documentation License:: Copying and sharing this manual
252 * Bibliography::        Publications cited in this manual.
253 * Index of Terms::      Cross-references to the text.
255 @detailmenu
256  --- The Detailed Node Listing ---
258 The Concepts of Bison
260 * Language and Grammar:: Languages and context-free grammars,
261                            as mathematical ideas.
262 * Grammar in Bison::     How we represent grammars for Bison's sake.
263 * Semantic Values::      Each token or syntactic grouping can have
264                            a semantic value (the value of an integer,
265                            the name of an identifier, etc.).
266 * Semantic Actions::     Each rule can have an action containing C code.
267 * GLR Parsers::          Writing parsers for general context-free languages.
268 * Locations::            Overview of location tracking.
269 * Bison Parser::         What are Bison's input and output,
270                            how is the output used?
271 * Stages::               Stages in writing and running Bison grammars.
272 * Grammar Layout::       Overall structure of a Bison grammar file.
274 Writing GLR Parsers
276 * Simple GLR Parsers::     Using GLR parsers on unambiguous grammars.
277 * Merging GLR Parses::     Using GLR parsers to resolve ambiguities.
278 * GLR Semantic Actions::   Considerations for semantic values and deferred actions.
279 * Semantic Predicates::    Controlling a parse with arbitrary computations.
281 Examples
283 * RPN Calc::               Reverse Polish Notation Calculator;
284                              a first example with no operator precedence.
285 * Infix Calc::             Infix (algebraic) notation calculator.
286                              Operator precedence is introduced.
287 * Simple Error Recovery::  Continuing after syntax errors.
288 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
289 * Multi-function Calc::    Calculator with memory and trig functions.
290                              It uses multiple data-types for semantic values.
291 * Exercises::              Ideas for improving the multi-function calculator.
293 Reverse Polish Notation Calculator
295 * Rpcalc Declarations::    Prologue (declarations) for rpcalc.
296 * Rpcalc Rules::           Grammar Rules for rpcalc, with explanation.
297 * Rpcalc Lexer::           The lexical analyzer.
298 * Rpcalc Main::            The controlling function.
299 * Rpcalc Error::           The error reporting function.
300 * Rpcalc Generate::        Running Bison on the grammar file.
301 * Rpcalc Compile::         Run the C compiler on the output code.
303 Grammar Rules for @code{rpcalc}
305 * Rpcalc Input::            Explanation of the @code{input} nonterminal
306 * Rpcalc Line::             Explanation of the @code{line} nonterminal
307 * Rpcalc Exp::              Explanation of the @code{exp} nonterminal
309 Location Tracking Calculator: @code{ltcalc}
311 * Ltcalc Declarations::    Bison and C declarations for ltcalc.
312 * Ltcalc Rules::           Grammar rules for ltcalc, with explanations.
313 * Ltcalc Lexer::           The lexical analyzer.
315 Multi-Function Calculator: @code{mfcalc}
317 * Mfcalc Declarations::    Bison declarations for multi-function calculator.
318 * Mfcalc Rules::           Grammar rules for the calculator.
319 * Mfcalc Symbol Table::    Symbol table management subroutines.
320 * Mfcalc Lexer::           The lexical analyzer.
321 * Mfcalc Main::            The controlling function.
323 Bison Grammar Files
325 * Grammar Outline::    Overall layout of the grammar file.
326 * Symbols::            Terminal and nonterminal symbols.
327 * Rules::              How to write grammar rules.
328 * Semantics::          Semantic values and actions.
329 * Tracking Locations:: Locations and actions.
330 * Named References::   Using named references in actions.
331 * Declarations::       All kinds of Bison declarations are described here.
332 * Multiple Parsers::   Putting more than one Bison parser in one program.
334 Outline of a Bison Grammar
336 * Prologue::              Syntax and usage of the prologue.
337 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
338 * Bison Declarations::    Syntax and usage of the Bison declarations section.
339 * Grammar Rules::         Syntax and usage of the grammar rules section.
340 * Epilogue::              Syntax and usage of the epilogue.
342 Grammar Rules
344 * Rules Syntax::   Syntax of the rules.
345 * Empty Rules::    Symbols that can match the empty string.
346 * Recursion::      Writing recursive rules.
349 Defining Language Semantics
351 * Value Type::        Specifying one data type for all semantic values.
352 * Multiple Types::    Specifying several alternative data types.
353 * Type Generation::   Generating the semantic value type.
354 * Union Decl::        Declaring the set of all semantic value types.
355 * Structured Value Type::  Providing a structured semantic value type.
356 * Actions::           An action is the semantic definition of a grammar rule.
357 * Action Types::      Specifying data types for actions to operate on.
358 * Midrule Actions::   Most actions go at the end of a rule.
359                       This says when, why and how to use the exceptional
360                         action in the middle of a rule.
362 Actions in Midrule
364 * Using Midrule Actions::       Putting an action in the middle of a rule.
365 * Typed Midrule Actions::       Specifying the semantic type of their values.
366 * Midrule Action Translation::  How midrule actions are actually processed.
367 * Midrule Conflicts::           Midrule actions can cause conflicts.
369 Tracking Locations
371 * Location Type::               Specifying a data type for locations.
372 * Actions and Locations::       Using locations in actions.
373 * Printing Locations::          Defining how locations are printed.
374 * Location Default Action::     Defining a general way to compute locations.
376 Bison Declarations
378 * Require Decl::      Requiring a Bison version.
379 * Token Decl::        Declaring terminal symbols.
380 * Precedence Decl::   Declaring terminals with precedence and associativity.
381 * Type Decl::         Declaring the choice of type for a nonterminal symbol.
382 * Symbol Decls::      Summary of the Syntax of Symbol Declarations.
383 * Initial Action Decl::  Code run before parsing starts.
384 * Destructor Decl::   Declaring how symbols are freed.
385 * Printer Decl::      Declaring how symbol values are displayed.
386 * Expect Decl::       Suppressing warnings about parsing conflicts.
387 * Start Decl::        Specifying the start symbol.
388 * Pure Decl::         Requesting a reentrant parser.
389 * Push Decl::         Requesting a push parser.
390 * Decl Summary::      Table of all Bison declarations.
391 * %define Summary::   Defining variables to adjust Bison's behavior.
392 * %code Summary::     Inserting code into the parser source.
394 Parser C-Language Interface
396 * Parser Function::         How to call @code{yyparse} and what it returns.
397 * Push Parser Interface::   How to create, use, and destroy push parsers.
398 * Lexical::                 You must supply a function @code{yylex}
399                               which reads tokens.
400 * Error Reporting::         Passing error messages to the user.
401 * Action Features::         Special features for use in actions.
402 * Internationalization::    How to let the parser speak in the user's
403                               native language.
405 The Lexical Analyzer Function @code{yylex}
407 * Calling Convention::  How @code{yyparse} calls @code{yylex}.
408 * Special Tokens::      Signaling end-of-file and errors to the parser.
409 * Tokens from Literals:: Finding token kinds from string aliases.
410 * Token Values::        How @code{yylex} must return the semantic value
411                           of the token it has read.
412 * Token Locations::     How @code{yylex} must return the text location
413                           (line number, etc.) of the token, if the
414                           actions want that.
415 * Pure Calling::        How the calling convention differs in a pure parser
416                           (@pxref{Pure Decl}).
418 Error Reporting
420 * Error Reporting Function::         You must supply a @code{yyerror} function.
421 * Syntax Error Reporting Function::  You can supply a @code{yyreport_syntax_error} function.
423 Parser Internationalization
425 * Enabling I18n::    Preparing your project to support internationalization.
426 * Token I18n::       Preparing tokens for internationalization in error messages.
428 The Bison Parser Algorithm
430 * Lookahead::         Parser looks one token ahead when deciding what to do.
431 * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
432 * Precedence::        Operator precedence works by resolving conflicts.
433 * Contextual Precedence::  When an operator's precedence depends on context.
434 * Parser States::     The parser is a finite-state-machine with stack.
435 * Reduce/Reduce::     When two rules are applicable in the same situation.
436 * Mysterious Conflicts:: Conflicts that look unjustified.
437 * Tuning LR::         How to tune fundamental aspects of LR-based parsing.
438 * Generalized LR Parsing::  Parsing arbitrary context-free grammars.
439 * Memory Management:: What happens when memory is exhausted.  How to avoid it.
441 Operator Precedence
443 * Why Precedence::    An example showing why precedence is needed.
444 * Using Precedence::  How to specify precedence and associativity.
445 * Precedence Only::   How to specify precedence only.
446 * Precedence Examples::  How these features are used in the previous example.
447 * How Precedence::    How they work.
448 * Non Operators::     Using precedence for general conflicts.
450 Tuning LR
452 * LR Table Construction:: Choose a different construction algorithm.
453 * Default Reductions::    Disable default reductions.
454 * LAC::                   Correct lookahead sets in the parser states.
455 * Unreachable States::    Keep unreachable parser states for debugging.
457 Handling Context Dependencies
459 * Semantic Tokens::   Token parsing can depend on the semantic context.
460 * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
461 * Tie-in Recovery::   Lexical tie-ins have implications for how
462                         error recovery rules must be written.
464 Debugging Your Parser
466 * Counterexamples::   Understanding conflicts.
467 * Understanding::     Understanding the structure of your parser.
468 * Graphviz::          Getting a visual representation of the parser.
469 * Xml::               Getting a markup representation of the parser.
470 * Tracing::           Tracing the execution of your parser.
472 Tracing Your Parser
474 * Enabling Traces::    Activating run-time trace support
475 * Mfcalc Traces::      Extending @code{mfcalc} to support traces
477 Invoking Bison
479 * Bison Options::     All the options described in detail,
480                         in alphabetical order by short options.
481 * Option Cross Key::  Alphabetical list of long options.
482 * Yacc Library::      Yacc-compatible @code{yylex} and @code{main}.
484 Bison Options
486 * Operation Modes::    Options controlling the global behavior of @command{bison}
487 * Diagnostics::        Options controlling the diagnostics
488 * Tuning the Parser::  Options changing the generated parsers
489 * Output Files::       Options controlling the output
491 Parsers Written In Other Languages
493 * C++ Parsers::                 The interface to generate C++ parser classes
494 * D Parsers::                   The interface to generate D parser classes
495 * Java Parsers::                The interface to generate Java parser classes
497 C++ Parsers
499 * A Simple C++ Example::        A short introduction to C++ parsers
500 * C++ Bison Interface::         Asking for C++ parser generation
501 * C++ Parser Interface::        Instantiating and running the parser
502 * C++ Semantic Values::         %union vs. C++
503 * C++ Location Values::         The position and location classes
504 * C++ Parser Context::          You can supply a @code{report_syntax_error} function.
505 * C++ Scanner Interface::       Exchanges between yylex and parse
506 * A Complete C++ Example::      Demonstrating their use
508 C++ Location Values
510 * C++ position::                  One point in the source file
511 * C++ location::                  Two points in the source file
512 * Exposing the Location Classes:: Using the Bison location class in your
513                                   project
514 * User Defined Location Type::    Required interface for locations
516 A Complete C++ Example
518 * Calc++ --- C++ Calculator::   The specifications
519 * Calc++ Parsing Driver::       An active parsing context
520 * Calc++ Parser::               A parser class
521 * Calc++ Scanner::              A pure C++ Flex scanner
522 * Calc++ Top Level::            Conducting the band
524 D Parsers
526 * D Bison Interface::        Asking for D parser generation
527 * D Semantic Values::        %token and %nterm vs. D
528 * D Location Values::        The position and location classes
529 * D Parser Interface::       Instantiating and running the parser
530 * D Parser Context Interface:: Circumstances of a syntax error
531 * D Scanner Interface::      Specifying the scanner for the parser
532 * D Action Features::        Special features for use in actions
533 * D Push Parser Interface::  Instantiating and running the push parser
534 * D Complete Symbols::       Using token constructors
536 Java Parsers
538 * Java Bison Interface::        Asking for Java parser generation
539 * Java Semantic Values::        %token and %nterm vs. Java
540 * Java Location Values::        The position and location classes
541 * Java Parser Interface::       Instantiating and running the parser
542 * Java Parser Context Interface:: Circumstances of a syntax error
543 * Java Scanner Interface::      Specifying the scanner for the parser
544 * Java Action Features::        Special features for use in actions
545 * Java Push Parser Interface::  Instantiating and running the push parser
546 * Java Differences::            Differences between C/C++ and Java Grammars
547 * Java Declarations Summary::   List of Bison declarations used with Java
549 A Brief History of the Greater Ungulates
551 * Yacc::                        The original Yacc
552 * yacchack::                    An obscure early implementation of reentrancy
553 * Byacc::                       Berkeley Yacc
554 * Bison::                       This program
555 * Other Ungulates::             Similar programs
557 Bison Version Compatibility
559 * Versioning::                  Dealing with Bison versioning
561 Frequently Asked Questions
563 * Memory Exhausted::            Breaking the Stack Limits
564 * How Can I Reset the Parser::  @code{yyparse} Keeps some State
565 * Strings are Destroyed::       @code{yylval} Loses Track of Strings
566 * Implementing Gotos/Loops::    Control Flow in the Calculator
567 * Multiple start-symbols::      Factoring closely related grammars
568 * Enabling Relocatability::     Moving Bison/using it through network shares
569 * Secure?  Conform?::           Is Bison POSIX safe?
570 * I can't build Bison::         Troubleshooting
571 * Where can I find help?::      Troubleshouting
572 * Bug Reports::                 Troublereporting
573 * More Languages::              Parsers in C++, Java, and so on
574 * Beta Testing::                Experimenting development versions
575 * Mailing Lists::               Meeting other Bison users
577 Copying This Manual
579 * GNU Free Documentation License:: Copying and sharing this manual
581 @end detailmenu
582 @end menu
584 @node Introduction
585 @unnumbered Introduction
586 @cindex introduction
588 @dfn{Bison} is a general-purpose parser generator that converts an annotated
589 context-free grammar into a deterministic LR or generalized LR (GLR) parser
590 employing LALR(1), IELR(1) or canonical LR(1) parser tables.  Once you are
591 proficient with Bison, you can use it to develop a wide range of language
592 parsers, from those used in simple desk calculators to complex programming
593 languages.
595 Bison is upward compatible with Yacc: all properly-written Yacc grammars
596 ought to work with Bison with no change.  Anyone familiar with Yacc should
597 be able to use Bison with little trouble.  You need to be fluent in C, C++,
598 D or Java programming in order to use Bison or to understand this manual.
600 We begin with tutorial chapters that explain the basic concepts of
601 using Bison and show three explained examples, each building on the
602 last.  If you don't know Bison or Yacc, start by reading these
603 chapters.  Reference chapters follow, which describe specific aspects
604 of Bison in detail.
606 Bison was written originally by Robert Corbett.  Richard Stallman made
607 it Yacc-compatible.  Wilfred Hansen of Carnegie Mellon University
608 added multi-character string literals and other features.  Since then,
609 Bison has grown more robust and evolved many other new features thanks
610 to the hard work of a long list of volunteers.  For details, see the
611 @file{THANKS} and @file{ChangeLog} files included in the Bison
612 distribution.
614 This edition corresponds to version @value{VERSION} of Bison.
616 @node Conditions
617 @unnumbered Conditions for Using Bison
619 The distribution terms for Bison-generated parsers permit using the parsers
620 in nonfree programs.  Before Bison version 2.2, these extra permissions
621 applied only when Bison was generating LALR(1) parsers in C@.  And before
622 Bison version 1.24, Bison-generated parsers could be used only in programs
623 that were free software.
625 The other GNU programming tools, such as the GNU C compiler, have never had
626 such a requirement.  They could always be used for nonfree software.  The
627 reason Bison was different was not due to a special policy decision; it
628 resulted from applying the usual General Public License to all of the Bison
629 source code.
631 The main output of the Bison utility---the Bison parser implementation
632 file---contains a verbatim copy of a sizable piece of Bison, which is the
633 code for the parser's implementation.  (The actions from your grammar are
634 inserted into this implementation at one point, but most of the rest of the
635 implementation is not changed.)  When we applied the GPL terms to the
636 skeleton code for the parser's implementation, the effect was to restrict
637 the use of Bison output to free software.
639 We didn't change the terms because of sympathy for people who want to make
640 software proprietary.  @strong{Software should be free.}  But we concluded
641 that limiting Bison's use to free software was doing little to encourage
642 people to make other software free.  So we decided to make the practical
643 conditions for using Bison match the practical conditions for using the
644 other GNU tools.
646 This exception applies when Bison is generating code for a parser.  You can
647 tell whether the exception applies to a Bison output file by inspecting the
648 file for text beginning with ``As a special exception@dots{}''.  The text
649 spells out the exact terms of the exception.
651 @node Copying
652 @unnumbered GNU GENERAL PUBLIC LICENSE
653 @include gpl-3.0.texi
655 @node Concepts
656 @chapter The Concepts of Bison
658 This chapter introduces many of the basic concepts without which the details
659 of Bison will not make sense.  If you do not already know how to use Bison
660 or Yacc, we suggest you start by reading this chapter carefully.
662 @menu
663 * Language and Grammar:: Languages and context-free grammars,
664                            as mathematical ideas.
665 * Grammar in Bison::     How we represent grammars for Bison's sake.
666 * Semantic Values::      Each token or syntactic grouping can have
667                            a semantic value (the value of an integer,
668                            the name of an identifier, etc.).
669 * Semantic Actions::     Each rule can have an action containing C code.
670 * GLR Parsers::          Writing parsers for general context-free languages.
671 * Locations::            Overview of location tracking.
672 * Bison Parser::         What are Bison's input and output,
673                            how is the output used?
674 * Stages::               Stages in writing and running Bison grammars.
675 * Grammar Layout::       Overall structure of a Bison grammar file.
676 @end menu
678 @node Language and Grammar
679 @section Languages and Context-Free Grammars
681 @cindex context-free grammar
682 @cindex grammar, context-free
683 In order for Bison to parse a language, it must be described by a
684 @dfn{context-free grammar}.  This means that you specify one or more
685 @dfn{syntactic groupings} and give rules for constructing them from their
686 parts.  For example, in the C language, one kind of grouping is called an
687 `expression'.  One rule for making an expression might be, ``An expression
688 can be made of a minus sign and another expression''.  Another would be,
689 ``An expression can be an integer''.  As you can see, rules are often
690 recursive, but there must be at least one rule which leads out of the
691 recursion.
693 @cindex BNF
694 @cindex Backus-Naur form
695 The most common formal system for presenting such rules for humans to read
696 is @dfn{Backus-Naur Form} or ``BNF'', which was developed in
697 order to specify the language Algol 60.  Any grammar expressed in
698 BNF is a context-free grammar.  The input to Bison is
699 essentially machine-readable BNF.
701 @cindex LALR grammars
702 @cindex IELR grammars
703 @cindex LR grammars
704 There are various important subclasses of context-free grammars.  Although
705 it can handle almost all context-free grammars, Bison is optimized for what
706 are called LR(1) grammars.  In brief, in these grammars, it must be possible
707 to tell how to parse any portion of an input string with just a single token
708 of lookahead.  For historical reasons, Bison by default is limited by the
709 additional restrictions of LALR(1), which is hard to explain simply.
710 @xref{Mysterious Conflicts}, for more information on this.  You can escape
711 these additional restrictions by requesting IELR(1) or canonical LR(1)
712 parser tables.  @xref{LR Table Construction}, to learn how.
714 @cindex GLR parsing
715 @cindex generalized LR (GLR) parsing
716 @cindex ambiguous grammars
717 @cindex nondeterministic parsing
719 Parsers for LR(1) grammars are @dfn{deterministic}, meaning
720 roughly that the next grammar rule to apply at any point in the input is
721 uniquely determined by the preceding input and a fixed, finite portion
722 (called a @dfn{lookahead}) of the remaining input.  A context-free
723 grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
724 apply the grammar rules to get the same inputs.  Even unambiguous
725 grammars can be @dfn{nondeterministic}, meaning that no fixed
726 lookahead always suffices to determine the next grammar rule to apply.
727 With the proper declarations, Bison is also able to parse these more
728 general context-free grammars, using a technique known as GLR
729 parsing (for Generalized LR).  Bison's GLR parsers
730 are able to handle any context-free grammar for which the number of
731 possible parses of any given string is finite.
733 @cindex symbols (abstract)
734 @cindex token
735 @cindex syntactic grouping
736 @cindex grouping, syntactic
737 In the formal grammatical rules for a language, each kind of syntactic unit
738 or grouping is named by a @dfn{symbol}.  Those which are built by grouping
739 smaller constructs according to grammatical rules are called
740 @dfn{nonterminal symbols}; those which can't be subdivided are called
741 @dfn{terminal symbols} or @dfn{token kinds}.  We call a piece of input
742 corresponding to a single terminal symbol a @dfn{token}, and a piece
743 corresponding to a single nonterminal symbol a @dfn{grouping}.
745 We can use the C language as an example of what symbols, terminal and
746 nonterminal, mean.  The tokens of C are identifiers, constants (numeric
747 and string), and the various keywords, arithmetic operators and
748 punctuation marks.  So the terminal symbols of a grammar for C include
749 `identifier', `number', `string', plus one symbol for each keyword,
750 operator or punctuation mark: `if', `return', `const', `static', `int',
751 `char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
752 (These tokens can be subdivided into characters, but that is a matter of
753 lexicography, not grammar.)
755 Here is a simple C function subdivided into tokens:
757 @example
758 int             /* @r{keyword `int'} */
759 square (int x)  /* @r{identifier, open-paren, keyword `int',}
760                    @r{identifier, close-paren} */
761 @{               /* @r{open-brace} */
762   return x * x; /* @r{keyword `return', identifier, asterisk,}
763                    @r{identifier, semicolon} */
764 @}               /* @r{close-brace} */
765 @end example
767 The syntactic groupings of C include the expression, the statement, the
768 declaration, and the function definition.  These are represented in the
769 grammar of C by nonterminal symbols `expression', `statement',
770 `declaration' and `function definition'.  The full grammar uses dozens of
771 additional language constructs, each with its own nonterminal symbol, in
772 order to express the meanings of these four.  The example above is a
773 function definition; it contains one declaration, and one statement.  In
774 the statement, each @samp{x} is an expression and so is @samp{x * x}.
776 Each nonterminal symbol must have grammatical rules showing how it is made
777 out of simpler constructs.  For example, one kind of C statement is the
778 @code{return} statement; this would be described with a grammar rule which
779 reads informally as follows:
781 @quotation
782 A `statement' can be made of a `return' keyword, an `expression' and a
783 `semicolon'.
784 @end quotation
786 @noindent
787 There would be many other rules for `statement', one for each kind of
788 statement in C.
790 @cindex start symbol
791 One nonterminal symbol must be distinguished as the special one which
792 defines a complete utterance in the language.  It is called the @dfn{start
793 symbol}.  In a compiler, this means a complete input program.  In the C
794 language, the nonterminal symbol `sequence of definitions and declarations'
795 plays this role.
797 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
798 program---but it is not valid as an @emph{entire} C program.  In the
799 context-free grammar of C, this follows from the fact that `expression' is
800 not the start symbol.
802 The Bison parser reads a sequence of tokens as its input, and groups the
803 tokens using the grammar rules.  If the input is valid, the end result is
804 that the entire token sequence reduces to a single grouping whose symbol is
805 the grammar's start symbol.  If we use a grammar for C, the entire input
806 must be a `sequence of definitions and declarations'.  If not, the parser
807 reports a syntax error.
809 @node Grammar in Bison
810 @section From Formal Rules to Bison Input
811 @cindex Bison grammar
812 @cindex grammar, Bison
813 @cindex formal grammar
815 A formal grammar is a mathematical construct.  To define the language
816 for Bison, you must write a file expressing the grammar in Bison syntax:
817 a @dfn{Bison grammar} file.  @xref{Grammar File}.
819 A nonterminal symbol in the formal grammar is represented in Bison input
820 as an identifier, like an identifier in C@.  By convention, it should be
821 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
823 The Bison representation for a terminal symbol is also called a @dfn{token
824 kind}.  Token kinds as well can be represented as C-like identifiers.  By
825 convention, these identifiers should be upper case to distinguish them from
826 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
827 @code{RETURN}.  A terminal symbol that stands for a particular keyword in
828 the language should be named after that keyword converted to upper case.
829 The terminal symbol @code{error} is reserved for error recovery.
830 @xref{Symbols}.
832 A terminal symbol can also be represented as a character literal, just like
833 a C character constant.  You should do this whenever a token is just a
834 single character (parenthesis, plus-sign, etc.): use that same character in
835 a literal as the terminal symbol for that token.
837 A third way to represent a terminal symbol is with a C string constant
838 containing several characters.  @xref{Symbols}, for more information.
840 The grammar rules also have an expression in Bison syntax.  For example,
841 here is the Bison rule for a C @code{return} statement.  The semicolon in
842 quotes is a literal character token, representing part of the C syntax for
843 the statement; the naked semicolon, and the colon, are Bison punctuation
844 used in every rule.
846 @example
847 stmt: RETURN expr ';' ;
848 @end example
850 @noindent
851 @xref{Rules}.
853 @node Semantic Values
854 @section Semantic Values
855 @cindex semantic value
856 @cindex value, semantic
858 A formal grammar selects tokens only by their classifications: for example,
859 if a rule mentions the terminal symbol `integer constant', it means that
860 @emph{any} integer constant is grammatically valid in that position.  The
861 precise value of the constant is irrelevant to how to parse the input: if
862 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
863 grammatical.
865 But the precise value is very important for what the input means once it is
866 parsed.  A compiler is useless if it fails to distinguish between 4, 1 and
867 3989 as constants in the program!  Therefore, each token in a Bison grammar
868 has both a token kind and a @dfn{semantic value}.  @xref{Semantics}, for
869 details.
871 The token kind is a terminal symbol defined in the grammar, such as
872 @code{INTEGER}, @code{IDENTIFIER} or @code{','}.  It tells everything you
873 need to know to decide where the token may validly appear and how to group
874 it with other tokens.  The grammar rules know nothing about tokens except
875 their kinds.
877 The semantic value has all the rest of the information about the
878 meaning of the token, such as the value of an integer, or the name of an
879 identifier.  (A token such as @code{','} which is just punctuation doesn't
880 need to have any semantic value.)
882 For example, an input token might be classified as token kind @code{INTEGER}
883 and have the semantic value 4.  Another input token might have the same
884 token kind @code{INTEGER} but value 3989.  When a grammar rule says that
885 @code{INTEGER} is allowed, either of these tokens is acceptable because each
886 is an @code{INTEGER}.  When the parser accepts the token, it keeps track of
887 the token's semantic value.
889 Each grouping can also have a semantic value as well as its nonterminal
890 symbol.  For example, in a calculator, an expression typically has a
891 semantic value that is a number.  In a compiler for a programming
892 language, an expression typically has a semantic value that is a tree
893 structure describing the meaning of the expression.
895 @node Semantic Actions
896 @section Semantic Actions
897 @cindex semantic actions
898 @cindex actions, semantic
900 In order to be useful, a program must do more than parse input; it must
901 also produce some output based on the input.  In a Bison grammar, a grammar
902 rule can have an @dfn{action} made up of C statements.  Each time the
903 parser recognizes a match for that rule, the action is executed.
904 @xref{Actions}.
906 Most of the time, the purpose of an action is to compute the semantic value
907 of the whole construct from the semantic values of its parts.  For example,
908 suppose we have a rule which says an expression can be the sum of two
909 expressions.  When the parser recognizes such a sum, each of the
910 subexpressions has a semantic value which describes how it was built up.
911 The action for this rule should create a similar sort of value for the
912 newly recognized larger expression.
914 For example, here is a rule that says an expression can be the sum of
915 two subexpressions:
917 @example
918 expr: expr '+' expr   @{ $$ = $1 + $3; @} ;
919 @end example
921 @noindent
922 The action says how to produce the semantic value of the sum expression
923 from the values of the two subexpressions.
925 @node GLR Parsers
926 @section Writing GLR Parsers
927 @cindex GLR parsing
928 @cindex generalized LR (GLR) parsing
929 @findex %glr-parser
930 @cindex conflicts
931 @cindex shift/reduce conflicts
932 @cindex reduce/reduce conflicts
934 In some grammars, Bison's deterministic
935 LR(1) parsing algorithm cannot decide whether to apply a
936 certain grammar rule at a given point.  That is, it may not be able to
937 decide (on the basis of the input read so far) which of two possible
938 reductions (applications of a grammar rule) applies, or whether to apply
939 a reduction or read more of the input and apply a reduction later in the
940 input.  These are known respectively as @dfn{reduce/reduce} conflicts
941 (@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
942 (@pxref{Shift/Reduce}).
944 To use a grammar that is not easily modified to be LR(1), a more general
945 parsing algorithm is sometimes necessary.  If you include @code{%glr-parser}
946 among the Bison declarations in your file (@pxref{Grammar Outline}), the
947 result is a Generalized LR (GLR) parser.  These parsers handle Bison
948 grammars that contain no unresolved conflicts (i.e., after applying
949 precedence declarations) identically to deterministic parsers.  However,
950 when faced with unresolved shift/reduce and reduce/reduce conflicts, GLR
951 parsers use the simple expedient of doing both, effectively cloning the
952 parser to follow both possibilities.  Each of the resulting parsers can
953 again split, so that at any given time, there can be any number of possible
954 parses being explored.  The parsers proceed in lockstep; that is, all of
955 them consume (shift) a given input symbol before any of them proceed to the
956 next.  Each of the cloned parsers eventually meets one of two possible
957 fates: either it runs into a parsing error, in which case it simply
958 vanishes, or it merges with another parser, because the two of them have
959 reduced the input to an identical set of symbols.
961 During the time that there are multiple parsers, semantic actions are
962 recorded, but not performed.  When a parser disappears, its recorded
963 semantic actions disappear as well, and are never performed.  When a
964 reduction makes two parsers identical, causing them to merge, Bison records
965 both sets of semantic actions.  Whenever the last two parsers merge,
966 reverting to the single-parser case, Bison resolves all the outstanding
967 actions either by precedences given to the grammar rules involved, or by
968 performing both actions, and then calling a designated user-defined function
969 on the resulting values to produce an arbitrary merged result.
971 @menu
972 * Simple GLR Parsers::     Using GLR parsers on unambiguous grammars.
973 * Merging GLR Parses::     Using GLR parsers to resolve ambiguities.
974 * GLR Semantic Actions::   Considerations for semantic values and deferred actions.
975 * Semantic Predicates::    Controlling a parse with arbitrary computations.
976 @end menu
978 @node Simple GLR Parsers
979 @subsection Using GLR on Unambiguous Grammars
980 @cindex GLR parsing, unambiguous grammars
981 @cindex generalized LR (GLR) parsing, unambiguous grammars
982 @findex %glr-parser
983 @findex %expect-rr
984 @cindex conflicts
985 @cindex reduce/reduce conflicts
986 @cindex shift/reduce conflicts
988 In the simplest cases, you can use the GLR algorithm
989 to parse grammars that are unambiguous but fail to be LR(1).
990 Such grammars typically require more than one symbol of lookahead.
992 Consider a problem that
993 arises in the declaration of enumerated and subrange types in the
994 programming language Pascal.  Here are some examples:
996 @example
997 type subrange = lo .. hi;
998 type enum = (a, b, c);
999 @end example
1001 @noindent
1002 The original language standard allows only numeric literals and constant
1003 identifiers for the subrange bounds (@samp{lo} and @samp{hi}), but Extended
1004 Pascal (ISO/IEC 10206) and many other Pascal implementations allow arbitrary
1005 expressions there.  This gives rise to the following situation, containing a
1006 superfluous pair of parentheses:
1008 @example
1009 type subrange = (a) .. b;
1010 @end example
1012 @noindent
1013 Compare this to the following declaration of an enumerated
1014 type with only one value:
1016 @example
1017 type enum = (a);
1018 @end example
1020 @noindent
1021 (These declarations are contrived, but they are syntactically valid, and
1022 more-complicated cases can come up in practical programs.)
1024 These two declarations look identical until the @samp{..} token.  With
1025 normal LR(1) one-token lookahead it is not possible to decide between the
1026 two forms when the identifier @samp{a} is parsed.  It is, however, desirable
1027 for a parser to decide this, since in the latter case @samp{a} must become a
1028 new identifier to represent the enumeration value, while in the former case
1029 @samp{a} must be evaluated with its current meaning, which may be a constant
1030 or even a function call.
1032 You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
1033 to be resolved later, but this typically requires substantial contortions in
1034 both semantic actions and large parts of the grammar, where the parentheses
1035 are nested in the recursive rules for expressions.
1037 You might think of using the lexer to distinguish between the two forms by
1038 returning different tokens for currently defined and undefined identifiers.
1039 But if these declarations occur in a local scope, and @samp{a} is defined in
1040 an outer scope, then both forms are possible---either locally redefining
1041 @samp{a}, or using the value of @samp{a} from the outer scope.  So this
1042 approach cannot work.
1044 A simple solution to this problem is to declare the parser to use the GLR
1045 algorithm.  When the GLR parser reaches the critical state, it merely splits
1046 into two branches and pursues both syntax rules simultaneously.  Sooner or
1047 later, one of them runs into a parsing error.  If there is a @samp{..} token
1048 before the next @samp{;}, the rule for enumerated types fails since it
1049 cannot accept @samp{..} anywhere; otherwise, the subrange type rule fails
1050 since it requires a @samp{..} token.  So one of the branches fails silently,
1051 and the other one continues normally, performing all the intermediate
1052 actions that were postponed during the split.
1054 If the input is syntactically incorrect, both branches fail and the parser
1055 reports a syntax error as usual.
1057 The effect of all this is that the parser seems to ``guess'' the correct
1058 branch to take, or in other words, it seems to use more lookahead than the
1059 underlying LR(1) algorithm actually allows for.  In this example, LR(2)
1060 would suffice, but also some cases that are not LR(@math{k}) for any
1061 @math{k} can be handled this way.
1063 In general, a GLR parser can take quadratic or cubic worst-case time, and
1064 the current Bison parser even takes exponential time and space for some
1065 grammars.  In practice, this rarely happens, and for many grammars it is
1066 possible to prove that it cannot happen.  The present example contains only
1067 one conflict between two rules, and the type-declaration context containing
1068 the conflict cannot be nested.  So the number of branches that can exist at
1069 any time is limited by the constant 2, and the parsing time is still linear.
1071 Here is a Bison grammar corresponding to the example above.  It
1072 parses a vastly simplified form of Pascal type declarations.
1074 @example
1075 %token TYPE DOTDOT ID
1077 @group
1078 %left '+' '-'
1079 %left '*' '/'
1080 @end group
1083 type_decl: TYPE ID '=' type ';' ;
1085 @group
1086 type:
1087   '(' id_list ')'
1088 | expr DOTDOT expr
1090 @end group
1092 @group
1093 id_list:
1094   ID
1095 | id_list ',' ID
1097 @end group
1099 @group
1100 expr:
1101   '(' expr ')'
1102 | expr '+' expr
1103 | expr '-' expr
1104 | expr '*' expr
1105 | expr '/' expr
1106 | ID
1108 @end group
1109 @end example
1111 When used as a normal LR(1) grammar, Bison correctly complains
1112 about one reduce/reduce conflict.  In the conflicting situation the
1113 parser chooses one of the alternatives, arbitrarily the one
1114 declared first.  Therefore the following correct input is not
1115 recognized:
1117 @example
1118 type t = (a) .. b;
1119 @end example
1121 The parser can be turned into a GLR parser, while also telling Bison
1122 to be silent about the one known reduce/reduce conflict, by adding
1123 these two declarations to the Bison grammar file (before the first
1124 @samp{%%}):
1126 @example
1127 %glr-parser
1128 %expect-rr 1
1129 @end example
1131 @noindent
1132 No change in the grammar itself is required.  Now the parser recognizes all
1133 valid declarations, according to the limited syntax above, transparently.
1134 In fact, the user does not even notice when the parser splits.
1136 So here we have a case where we can use the benefits of GLR, almost without
1137 disadvantages.  Even in simple cases like this, however, there are at least
1138 two potential problems to beware.  First, always analyze the conflicts
1139 reported by Bison to make sure that GLR splitting is only done where it is
1140 intended.  A GLR parser splitting inadvertently may cause problems less
1141 obvious than an LR parser statically choosing the wrong alternative in a
1142 conflict.  Second, consider interactions with the lexer (@pxref{Semantic
1143 Tokens}) with great care.  Since a split parser consumes tokens without
1144 performing any actions during the split, the lexer cannot obtain information
1145 via parser actions.  Some cases of lexer interactions can be eliminated by
1146 using GLR to shift the complications from the lexer to the parser.  You must
1147 check the remaining cases for correctness.
1149 In our example, it would be safe for the lexer to return tokens based on
1150 their current meanings in some symbol table, because no new symbols are
1151 defined in the middle of a type declaration.  Though it is possible for a
1152 parser to define the enumeration constants as they are parsed, before the
1153 type declaration is completed, it actually makes no difference since they
1154 cannot be used within the same enumerated type declaration.
1156 @node Merging GLR Parses
1157 @subsection Using GLR to Resolve Ambiguities
1158 @cindex GLR parsing, ambiguous grammars
1159 @cindex generalized LR (GLR) parsing, ambiguous grammars
1160 @findex %dprec
1161 @findex %merge
1162 @cindex conflicts
1163 @cindex reduce/reduce conflicts
1165 Let's consider an example, vastly simplified from a C++
1166 grammar.@footnote{The sources of an extended version of this example are
1167 available in C as @file{examples/c/glr}, and in C++ as
1168 @file{examples/c++/glr}.}
1170 @example
1172   #include <stdio.h>
1173   int yylex (void);
1174   void yyerror (char const *);
1177 %define api.value.type @{char const *@}
1179 %token TYPENAME ID
1181 %right '='
1182 %left '+'
1184 %glr-parser
1188 prog:
1189   %empty
1190 | prog stmt   @{ printf ("\n"); @}
1193 stmt:
1194   expr ';'  %dprec 1
1195 | decl      %dprec 2
1198 expr:
1199   ID               @{ printf ("%s ", $$); @}
1200 | TYPENAME '(' expr ')'
1201                    @{ printf ("%s <cast> ", $1); @}
1202 | expr '+' expr    @{ printf ("+ "); @}
1203 | expr '=' expr    @{ printf ("= "); @}
1206 decl:
1207   TYPENAME declarator ';'
1208                    @{ printf ("%s <declare> ", $1); @}
1209 | TYPENAME declarator '=' expr ';'
1210                    @{ printf ("%s <init-declare> ", $1); @}
1213 declarator:
1214   ID               @{ printf ("\"%s\" ", $1); @}
1215 | '(' declarator ')'
1217 @end example
1219 @noindent
1220 This models a problematic part of the C++ grammar---the ambiguity between
1221 certain declarations and statements.  For example,
1223 @example
1224 T (x) = y+z;
1225 @end example
1227 @noindent
1228 parses as either an @code{expr} or a @code{stmt}
1229 (assuming that @samp{T} is recognized as a @code{TYPENAME} and
1230 @samp{x} as an @code{ID}).
1231 Bison detects this as a reduce/reduce conflict between the rules
1232 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
1233 time it encounters @code{x} in the example above.  Since this is a
1234 GLR parser, it therefore splits the problem into two parses, one for
1235 each choice of resolving the reduce/reduce conflict.
1236 Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1237 however, neither of these parses ``dies,'' because the grammar as it stands is
1238 ambiguous.  One of the parsers eventually reduces @code{stmt : expr ';'} and
1239 the other reduces @code{stmt : decl}, after which both parsers are in an
1240 identical state: they've seen @samp{prog stmt} and have the same unprocessed
1241 input remaining.  We say that these parses have @dfn{merged.}
1243 At this point, the GLR parser requires a specification in the
1244 grammar of how to choose between the competing parses.
1245 In the example above, the two @code{%dprec}
1246 declarations specify that Bison is to give precedence
1247 to the parse that interprets the example as a
1248 @code{decl}, which implies that @code{x} is a declarator.
1249 The parser therefore prints
1251 @example
1252 "x" y z + T <init-declare>
1253 @end example
1255 The @code{%dprec} declarations only come into play when more than one
1256 parse survives.  Consider a different input string for this parser:
1258 @example
1259 T (x) + y;
1260 @end example
1262 @noindent
1263 This is another example of using GLR to parse an unambiguous
1264 construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
1265 Here, there is no ambiguity (this cannot be parsed as a declaration).
1266 However, at the time the Bison parser encounters @code{x}, it does not
1267 have enough information to resolve the reduce/reduce conflict (again,
1268 between @code{x} as an @code{expr} or a @code{declarator}).  In this
1269 case, no precedence declaration is used.  Again, the parser splits
1270 into two, one assuming that @code{x} is an @code{expr}, and the other
1271 assuming @code{x} is a @code{declarator}.  The second of these parsers
1272 then vanishes when it sees @code{+}, and the parser prints
1274 @example
1275 x T <cast> y +
1276 @end example
1278 Suppose that instead of resolving the ambiguity, you wanted to see all
1279 the possibilities.  For this purpose, you must merge the semantic
1280 actions of the two possible parsers, rather than choosing one over the
1281 other.  To do so, you could change the declaration of @code{stmt} as
1282 follows:
1284 @example
1285 stmt:
1286   expr ';'  %merge <stmt_merge>
1287 | decl      %merge <stmt_merge>
1289 @end example
1291 @noindent
1292 and define the @code{stmt_merge} function as:
1294 @example
1295 static YYSTYPE
1296 stmt_merge (YYSTYPE x0, YYSTYPE x1)
1298   printf ("<OR> ");
1299   return "";
1301 @end example
1303 @noindent
1304 with an accompanying forward declaration
1305 in the C declarations at the beginning of the file:
1307 @example
1309   static YYSTYPE stmt_merge (YYSTYPE x0, YYSTYPE x1);
1311 @end example
1313 @noindent
1314 With these declarations, the resulting parser parses the first example
1315 as both an @code{expr} and a @code{decl}, and prints
1317 @example
1318 "x" y z + T <init-declare> x T <cast> y z + = <OR>
1319 @end example
1321 Bison requires that all of the
1322 productions that participate in any particular merge have identical
1323 @samp{%merge} clauses.  Otherwise, the ambiguity would be unresolvable,
1324 and the parser will report an error during any parse that results in
1325 the offending merge.
1327 @sp 1
1329 The signature of the merger depends on the type of the symbol.  In the
1330 previous example, the merged-to symbol (@code{stmt}) does not have a
1331 specific type, and the merger is
1333 @example
1334 YYSTYPE stmt_merge (YYSTYPE x0, YYSTYPE x1);
1335 @end example
1337 @noindent
1338 However, if @code{stmt} had a declared type, e.g.,
1340 @example
1341 %type <Node *> stmt;
1342 @end example
1344 @noindent
1347 @example
1348 @group
1349 %union @{
1350   Node *node;
1351   ...
1353 @end group
1354 %type <node> stmt;
1355 @end example
1357 @noindent
1358 then the prototype of the merger must be:
1360 @example
1361 Node *stmt_merge (YYSTYPE x0, YYSTYPE x1);
1362 @end example
1364 @noindent
1365 (This signature might be a mistake originally, and maybe it should have been
1366 @samp{Node *stmt_merge (Node *x0, Node *x1)}.  If you have an opinion about
1367 it, please let us know.)
1369 @node GLR Semantic Actions
1370 @subsection GLR Semantic Actions
1372 The nature of GLR parsing and the structure of the generated
1373 parsers give rise to certain restrictions on semantic values and actions.
1375 @subsubsection Deferred semantic actions
1376 @cindex deferred semantic actions
1377 By definition, a deferred semantic action is not performed at the same time as
1378 the associated reduction.
1379 This raises caveats for several Bison features you might use in a semantic
1380 action in a GLR parser.
1382 @vindex yychar
1383 @cindex GLR parsers and @code{yychar}
1384 @vindex yylval
1385 @cindex GLR parsers and @code{yylval}
1386 @vindex yylloc
1387 @cindex GLR parsers and @code{yylloc}
1388 In any semantic action, you can examine @code{yychar} to determine the kind
1389 of the lookahead token present at the time of the associated reduction.
1390 After checking that @code{yychar} is not set to @code{YYEMPTY} or
1391 @code{YYEOF}, you can then examine @code{yylval} and @code{yylloc} to
1392 determine the lookahead token's semantic value and location, if any.  In a
1393 nondeferred semantic action, you can also modify any of these variables to
1394 influence syntax analysis.  @xref{Lookahead}.
1396 @findex yyclearin
1397 @cindex GLR parsers and @code{yyclearin}
1398 In a deferred semantic action, it's too late to influence syntax analysis.
1399 In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1400 shallow copies of the values they had at the time of the associated reduction.
1401 For this reason alone, modifying them is dangerous.
1402 Moreover, the result of modifying them is undefined and subject to change with
1403 future versions of Bison.
1404 For example, if a semantic action might be deferred, you should never write it
1405 to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1406 memory referenced by @code{yylval}.
1408 @subsubsection YYERROR
1409 @findex YYERROR
1410 @cindex GLR parsers and @code{YYERROR}
1411 Another Bison feature requiring special consideration is @code{YYERROR}
1412 (@pxref{Action Features}), which you can invoke in a semantic action to
1413 initiate error recovery.
1414 During deterministic GLR operation, the effect of @code{YYERROR} is
1415 the same as its effect in a deterministic parser.
1416 The effect in a deferred action is similar, but the precise point of the
1417 error is undefined;  instead, the parser reverts to deterministic operation,
1418 selecting an unspecified stack on which to continue with a syntax error.
1419 In a semantic predicate (see @ref{Semantic Predicates}) during nondeterministic
1420 parsing, @code{YYERROR} silently prunes
1421 the parse that invoked the test.
1423 @subsubsection Restrictions on semantic values and locations
1424 GLR parsers require that you use POD (Plain Old Data) types for
1425 semantic values and location types when using the generated parsers as
1426 C++ code.
1428 @node Semantic Predicates
1429 @subsection Controlling a Parse with Arbitrary Predicates
1430 @findex %?
1431 @cindex Semantic predicates in GLR parsers
1433 In addition to the @code{%dprec} and @code{%merge} directives,
1434 GLR parsers
1435 allow you to reject parses on the basis of arbitrary computations executed
1436 in user code, without having Bison treat this rejection as an error
1437 if there are alternative parses.  For example,
1439 @example
1440 widget:
1441   %?@{  new_syntax @} "widget" id new_args  @{ $$ = f($3, $4); @}
1442 | %?@{ !new_syntax @} "widget" id old_args  @{ $$ = f($3, $4); @}
1444 @end example
1446 @noindent
1447 is one way to allow the same parser to handle two different syntaxes for
1448 widgets.  The clause preceded by @code{%?} is treated like an ordinary
1449 midrule action, except that its text is handled as an expression and is always
1450 evaluated immediately (even when in nondeterministic mode).  If the
1451 expression yields 0 (false), the clause is treated as a syntax error,
1452 which, in a nondeterministic parser, causes the stack in which it is reduced
1453 to die.  In a deterministic parser, it acts like @code{YYERROR}.
1455 As the example shows, predicates otherwise look like semantic actions, and
1456 therefore you must take them into account when determining the numbers
1457 to use for denoting the semantic values of right-hand side symbols.
1458 Predicate actions, however, have no defined value, and may not be given
1459 labels.
1461 There is a subtle difference between semantic predicates and ordinary
1462 actions in nondeterministic mode, since the latter are deferred.
1463 For example, we could try to rewrite the previous example as
1465 @example
1466 widget:
1467   @{ if (!new_syntax) YYERROR; @}
1468     "widget" id new_args  @{ $$ = f($3, $4); @}
1469 |  @{ if (new_syntax) YYERROR; @}
1470     "widget" id old_args  @{ $$ = f($3, $4); @}
1472 @end example
1474 @noindent
1475 (reversing the sense of the predicate tests to cause an error when they are
1476 false).  However, this
1477 does @emph{not} have the same effect if @code{new_args} and @code{old_args}
1478 have overlapping syntax.
1479 Since the midrule actions testing @code{new_syntax} are deferred,
1480 a GLR parser first encounters the unresolved ambiguous reduction
1481 for cases where @code{new_args} and @code{old_args} recognize the same string
1482 @emph{before} performing the tests of @code{new_syntax}.  It therefore
1483 reports an error.
1485 Finally, be careful in writing predicates: deferred actions have not been
1486 evaluated, so that using them in a predicate will have undefined effects.
1488 @node Locations
1489 @section Locations
1490 @cindex location
1491 @cindex textual location
1492 @cindex location, textual
1494 Many applications, like interpreters or compilers, have to produce verbose
1495 and useful error messages.  To achieve this, one must be able to keep track of
1496 the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
1497 Bison provides a mechanism for handling these locations.
1499 Each token has a semantic value.  In a similar fashion, each token has an
1500 associated location, but the type of locations is the same for all tokens
1501 and groupings.  Moreover, the output parser is equipped with a default data
1502 structure for storing locations (@pxref{Tracking Locations}, for more
1503 details).
1505 Like semantic values, locations can be reached in actions using a dedicated
1506 set of constructs.  In the example above, the location of the whole grouping
1507 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1508 @code{@@3}.
1510 When a rule is matched, a default action is used to compute the semantic value
1511 of its left hand side (@pxref{Actions}).  In the same way, another default
1512 action is used for locations.  However, the action for locations is general
1513 enough for most cases, meaning there is usually no need to describe for each
1514 rule how @code{@@$} should be formed.  When building a new location for a given
1515 grouping, the default behavior of the output parser is to take the beginning
1516 of the first symbol, and the end of the last symbol.
1518 @node Bison Parser
1519 @section Bison Output: the Parser Implementation File
1520 @cindex Bison parser
1521 @cindex Bison utility
1522 @cindex lexical analyzer, purpose
1523 @cindex parser
1525 When you run Bison, you give it a Bison grammar file as input.  The
1526 most important output is a C source file that implements a parser for
1527 the language described by the grammar.  This parser is called a
1528 @dfn{Bison parser}, and this file is called a @dfn{Bison parser
1529 implementation file}.  Keep in mind that the Bison utility and the
1530 Bison parser are two distinct programs: the Bison utility is a program
1531 whose output is the Bison parser implementation file that becomes part
1532 of your program.
1534 The job of the Bison parser is to group tokens into groupings according to
1535 the grammar rules---for example, to build identifiers and operators into
1536 expressions.  As it does this, it runs the actions for the grammar rules it
1537 uses.
1539 The tokens come from a function called the @dfn{lexical analyzer} that
1540 you must supply in some fashion (such as by writing it in C).  The Bison
1541 parser calls the lexical analyzer each time it wants a new token.  It
1542 doesn't know what is ``inside'' the tokens (though their semantic values
1543 may reflect this).  Typically the lexical analyzer makes the tokens by
1544 parsing characters of text, but Bison does not depend on this.
1545 @xref{Lexical}.
1547 The Bison parser implementation file is C code which defines a
1548 function named @code{yyparse} which implements that grammar.  This
1549 function does not make a complete C program: you must supply some
1550 additional functions.  One is the lexical analyzer.  Another is an
1551 error-reporting function which the parser calls to report an error.
1552 In addition, a complete C program must start with a function called
1553 @code{main}; you have to provide this, and arrange for it to call
1554 @code{yyparse} or the parser will never run.  @xref{Interface}.
1556 Aside from the token kind names and the symbols in the actions you
1557 write, all symbols defined in the Bison parser implementation file
1558 itself begin with @samp{yy} or @samp{YY}.  This includes interface
1559 functions such as the lexical analyzer function @code{yylex}, the
1560 error reporting function @code{yyerror} and the parser function
1561 @code{yyparse} itself.  This also includes numerous identifiers used
1562 for internal purposes.  Therefore, you should avoid using C
1563 identifiers starting with @samp{yy} or @samp{YY} in the Bison grammar
1564 file except for the ones defined in this manual.  Also, you should
1565 avoid using the C identifiers @samp{malloc} and @samp{free} for
1566 anything other than their usual meanings.
1568 In some cases the Bison parser implementation file includes system
1569 headers, and in those cases your code should respect the identifiers
1570 reserved by those headers.  On some non-GNU hosts, @code{<limits.h>},
1571 @code{<stddef.h>}, @code{<stdint.h>} (if available), and @code{<stdlib.h>}
1572 are included to declare memory allocators and integer types and constants.
1573 @code{<libintl.h>} is included if message translation is in use
1574 (@pxref{Internationalization}).  Other system headers may be included
1575 if you define @code{YYDEBUG} (@pxref{Tracing}) or
1576 @code{YYSTACK_USE_ALLOCA} (@pxref{Table of Symbols}) to a nonzero value.
1578 @node Stages
1579 @section Stages in Using Bison
1580 @cindex stages in using Bison
1581 @cindex using Bison
1583 The actual language-design process using Bison, from grammar specification
1584 to a working compiler or interpreter, has these parts:
1586 @enumerate
1587 @item
1588 Formally specify the grammar in a form recognized by Bison
1589 (@pxref{Grammar File}).  For each grammatical rule
1590 in the language, describe the action that is to be taken when an
1591 instance of that rule is recognized.  The action is described by a
1592 sequence of C statements.
1594 @item
1595 Write a lexical analyzer to process input and pass tokens to the parser.
1596 The lexical analyzer may be written by hand in C (@pxref{Lexical}).  It
1597 could also be produced using Lex, but the use of Lex is not discussed in
1598 this manual.
1600 @item
1601 Write a controlling function that calls the Bison-produced parser.
1603 @item
1604 Write error-reporting routines.
1605 @end enumerate
1607 To turn this source code as written into a runnable program, you
1608 must follow these steps:
1610 @enumerate
1611 @item
1612 Run Bison on the grammar to produce the parser.
1614 @item
1615 Compile the code output by Bison, as well as any other source files.
1617 @item
1618 Link the object files to produce the finished product.
1619 @end enumerate
1621 @node Grammar Layout
1622 @section The Overall Layout of a Bison Grammar
1623 @cindex grammar file
1624 @cindex file format
1625 @cindex format of grammar file
1626 @cindex layout of Bison grammar
1628 The input file for the Bison utility is a @dfn{Bison grammar file}.  The
1629 general form of a Bison grammar file is as follows:
1631 @example
1633 @var{Prologue}
1636 @var{Bison declarations}
1639 @var{Grammar rules}
1641 @var{Epilogue}
1642 @end example
1644 @noindent
1645 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1646 in every Bison grammar file to separate the sections.
1648 The prologue may define types and variables used in the actions.  You can
1649 also use preprocessor commands to define macros used there, and use
1650 @code{#include} to include header files that do any of these things.
1651 You need to declare the lexical analyzer @code{yylex} and the error
1652 printer @code{yyerror} here, along with any other global identifiers
1653 used by the actions in the grammar rules.
1655 The Bison declarations declare the names of the terminal and nonterminal
1656 symbols, and may also describe operator precedence and the data types of
1657 semantic values of various symbols.
1659 The grammar rules define how to construct each nonterminal symbol from its
1660 parts.
1662 The epilogue can contain any code you want to use.  Often the
1663 definitions of functions declared in the prologue go here.  In a
1664 simple program, all the rest of the program can go here.
1666 @node Examples
1667 @chapter Examples
1668 @cindex simple examples
1669 @cindex examples, simple
1671 Now we show and explain several sample programs written using Bison: a
1672 Reverse Polish Notation calculator, an algebraic (infix) notation
1673 calculator --- later extended to track ``locations'' ---
1674 and a multi-function calculator.  All
1675 produce usable, though limited, interactive desk-top calculators.
1677 These examples are simple, but Bison grammars for real programming
1678 languages are written the same way.  You can copy these examples into a
1679 source file to try them.
1681 @sp 1
1683 Bison comes with several examples (including for the different target
1684 languages).  If this package is properly installed, you shall find them in
1685 @file{@var{prefix}/share/doc/bison/examples}, where @var{prefix} is the root
1686 of the installation, probably something like @file{/usr/local} or
1687 @file{/usr}.
1689 @menu
1690 * RPN Calc::               Reverse Polish Notation Calculator;
1691                              a first example with no operator precedence.
1692 * Infix Calc::             Infix (algebraic) notation calculator.
1693                              Operator precedence is introduced.
1694 * Simple Error Recovery::  Continuing after syntax errors.
1695 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1696 * Multi-function Calc::    Calculator with memory and trig functions.
1697                              It uses multiple data-types for semantic values.
1698 * Exercises::              Ideas for improving the multi-function calculator.
1699 @end menu
1701 @node RPN Calc
1702 @section Reverse Polish Notation Calculator
1703 @cindex Reverse Polish Notation
1704 @cindex @code{rpcalc}
1705 @cindex calculator, simple
1707 The first example@footnote{The sources of @command{rpcalc} are available as
1708 @file{examples/c/rpcalc}.} is that of a simple double-precision @dfn{Reverse
1709 Polish
1710 Notation} calculator (a calculator using postfix operators).  This example
1711 provides a good starting point, since operator precedence is not an issue.
1712 The second example will illustrate how operator precedence is handled.
1714 The source code for this calculator is named @file{rpcalc.y}.  The
1715 @samp{.y} extension is a convention used for Bison grammar files.
1717 @menu
1718 * Rpcalc Declarations::    Prologue (declarations) for rpcalc.
1719 * Rpcalc Rules::           Grammar Rules for rpcalc, with explanation.
1720 * Rpcalc Lexer::           The lexical analyzer.
1721 * Rpcalc Main::            The controlling function.
1722 * Rpcalc Error::           The error reporting function.
1723 * Rpcalc Generate::        Running Bison on the grammar file.
1724 * Rpcalc Compile::         Run the C compiler on the output code.
1725 @end menu
1727 @node Rpcalc Declarations
1728 @subsection Declarations for @code{rpcalc}
1730 Here are the C and Bison declarations for the Reverse Polish Notation
1731 calculator.  As in C, comments are placed between @samp{/*@dots{}*/} or
1732 after @samp{//}.
1734 @ignore
1735 @comment file: c/rpcalc/rpcalc.y
1736 @example
1737 /* Parser for rpcalc.   -*- C -*-
1739    Copyright (C) 1988-1993, 1995, 1998-2015, 2018-2021 Free Software
1740    Foundation, Inc.
1742    This file is part of Bison, the GNU Compiler Compiler.
1744    This program is free software: you can redistribute it and/or modify
1745    it under the terms of the GNU General Public License as published by
1746    the Free Software Foundation, either version 3 of the License, or
1747    (at your option) any later version.
1749    This program is distributed in the hope that it will be useful,
1750    but WITHOUT ANY WARRANTY; without even the implied warranty of
1751    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1752    GNU General Public License for more details.
1754    You should have received a copy of the GNU General Public License
1755    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
1756 @end example
1757 @end ignore
1759 @comment file: c/rpcalc/rpcalc.y
1760 @example
1761 /* Reverse Polish Notation calculator. */
1763 @group
1765   #include <stdio.h>
1766   #include <math.h>
1767   int yylex (void);
1768   void yyerror (char const *);
1770 @end group
1772 %define api.value.type @{double@}
1773 %token NUM
1775 %% /* Grammar rules and actions follow. */
1776 @end example
1778 The declarations section (@pxref{Prologue}) contains two
1779 preprocessor directives and two forward declarations.
1781 The @code{#include} directive is used to declare the exponentiation
1782 function @code{pow}.
1784 The forward declarations for @code{yylex} and @code{yyerror} are
1785 needed because the C language requires that functions be declared
1786 before they are used.  These functions will be defined in the
1787 epilogue, but the parser calls them so they must be declared in the
1788 prologue.
1790 The second section, Bison declarations, provides information to Bison about
1791 the tokens and their types (@pxref{Bison Declarations}).
1793 The @code{%define} directive defines the variable @code{api.value.type},
1794 thus specifying the C data type for semantic values of both tokens and
1795 groupings (@pxref{Value Type}).  The Bison
1796 parser will use whatever type @code{api.value.type} is defined as; if you
1797 don't define it, @code{int} is the default.  Because we specify
1798 @samp{@{double@}}, each token and each expression has an associated value,
1799 which is a floating point number.  C code can use @code{YYSTYPE} to refer to
1800 the value @code{api.value.type}.
1802 Each terminal symbol that is not a single-character literal must be
1803 declared.  (Single-character literals normally don't need to be declared.)
1804 In this example, all the arithmetic operators are designated by
1805 single-character literals, so the only terminal symbol that needs to be
1806 declared is @code{NUM}, the token kind for numeric constants.
1808 @node Rpcalc Rules
1809 @subsection Grammar Rules for @code{rpcalc}
1811 Here are the grammar rules for the Reverse Polish Notation calculator.
1813 @comment file: c/rpcalc/rpcalc.y
1814 @example
1815 @group
1816 input:
1817   %empty
1818 | input line
1820 @end group
1822 @group
1823 line:
1824   '\n'
1825 | exp '\n'      @{ printf ("%.10g\n", $1); @}
1827 @end group
1829 @group
1830 exp:
1831   NUM
1832 | exp exp '+'   @{ $$ = $1 + $2;      @}
1833 | exp exp '-'   @{ $$ = $1 - $2;      @}
1834 | exp exp '*'   @{ $$ = $1 * $2;      @}
1835 | exp exp '/'   @{ $$ = $1 / $2;      @}
1836 | exp exp '^'   @{ $$ = pow ($1, $2); @}  /* Exponentiation */
1837 | exp 'n'       @{ $$ = -$1;          @}  /* Unary minus   */
1839 @end group
1841 @end example
1843 The groupings of the rpcalc ``language'' defined here are the expression
1844 (given the name @code{exp}), the line of input (@code{line}), and the
1845 complete input transcript (@code{input}).  Each of these nonterminal
1846 symbols has several alternate rules, joined by the vertical bar @samp{|}
1847 which is read as ``or''.  The following sections explain what these rules
1848 mean.
1850 The semantics of the language is determined by the actions taken when a
1851 grouping is recognized.  The actions are the C code that appears inside
1852 braces.  @xref{Actions}.
1854 You must specify these actions in C, but Bison provides the means for
1855 passing semantic values between the rules.  In each action, the
1856 pseudo-variable @code{$$} stands for the semantic value for the grouping
1857 that the rule is going to construct.  Assigning a value to @code{$$} is the
1858 main job of most actions.  The semantic values of the components of the
1859 rule are referred to as @code{$1}, @code{$2}, and so on.
1861 @menu
1862 * Rpcalc Input::            Explanation of the @code{input} nonterminal
1863 * Rpcalc Line::             Explanation of the @code{line} nonterminal
1864 * Rpcalc Exp::              Explanation of the @code{exp} nonterminal
1865 @end menu
1867 @node Rpcalc Input
1868 @subsubsection Explanation of @code{input}
1870 Consider the definition of @code{input}:
1872 @example
1873 input:
1874   %empty
1875 | input line
1877 @end example
1879 This definition reads as follows: ``A complete input is either an empty
1880 string, or a complete input followed by an input line''.  Notice that
1881 ``complete input'' is defined in terms of itself.  This definition is said
1882 to be @dfn{left recursive} since @code{input} appears always as the
1883 leftmost symbol in the sequence.  @xref{Recursion}.
1885 The first alternative is empty because there are no symbols between the
1886 colon and the first @samp{|}; this means that @code{input} can match an
1887 empty string of input (no tokens).  We write the rules this way because it
1888 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1889 It's conventional to put an empty alternative first and to use the
1890 (optional) @code{%empty} directive, or to write the comment @samp{/* empty
1891 */} in it (@pxref{Empty Rules}).
1893 The second alternate rule (@code{input line}) handles all nontrivial input.
1894 It means, ``After reading any number of lines, read one more line if
1895 possible.''  The left recursion makes this rule into a loop.  Since the
1896 first alternative matches empty input, the loop can be executed zero or
1897 more times.
1899 The parser function @code{yyparse} continues to process input until a
1900 grammatical error is seen or the lexical analyzer says there are no more
1901 input tokens; we will arrange for the latter to happen at end-of-input.
1903 @node Rpcalc Line
1904 @subsubsection Explanation of @code{line}
1906 Now consider the definition of @code{line}:
1908 @example
1909 line:
1910   '\n'
1911 | exp '\n'  @{ printf ("%.10g\n", $1); @}
1913 @end example
1915 The first alternative is a token which is a newline character; this means
1916 that rpcalc accepts a blank line (and ignores it, since there is no
1917 action).  The second alternative is an expression followed by a newline.
1918 This is the alternative that makes rpcalc useful.  The semantic value of
1919 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1920 question is the first symbol in the alternative.  The action prints this
1921 value, which is the result of the computation the user asked for.
1923 This action is unusual because it does not assign a value to @code{$$}.  As
1924 a consequence, the semantic value associated with the @code{line} is
1925 uninitialized (its value will be unpredictable).  This would be a bug if
1926 that value were ever used, but we don't use it: once rpcalc has printed the
1927 value of the user's input line, that value is no longer needed.
1929 @node Rpcalc Exp
1930 @subsubsection Explanation of @code{exp}
1932 The @code{exp} grouping has several rules, one for each kind of expression.
1933 The first rule handles the simplest expressions: those that are just
1934 numbers.  The second handles an addition-expression, which looks like two
1935 expressions followed by a plus-sign.  The third handles subtraction, and so
1938 @example
1939 exp:
1940   NUM
1941 | exp exp '+'     @{ $$ = $1 + $2;    @}
1942 | exp exp '-'     @{ $$ = $1 - $2;    @}
1943 @dots{}
1945 @end example
1947 We have used @samp{|} to join all the rules for @code{exp}, but we could
1948 equally well have written them separately:
1950 @example
1951 exp: NUM;
1952 exp: exp exp '+'  @{ $$ = $1 + $2; @};
1953 exp: exp exp '-'  @{ $$ = $1 - $2; @};
1954 @dots{}
1955 @end example
1957 Most of the rules have actions that compute the value of the expression in
1958 terms of the value of its parts.  For example, in the rule for addition,
1959 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1960 the second one.  The third component, @code{'+'}, has no meaningful
1961 associated semantic value, but if it had one you could refer to it as
1962 @code{$3}.  The first rule relies on the implicit default action: @samp{@{
1963 $$ = $1; @}}.
1966 When @code{yyparse} recognizes a sum expression using this rule, the sum of
1967 the two subexpressions' values is produced as the value of the entire
1968 expression.  @xref{Actions}.
1970 You don't have to give an action for every rule.  When a rule has no action,
1971 Bison by default copies the value of @code{$1} into @code{$$}.  This is what
1972 happens in the first rule (the one that uses @code{NUM}).
1974 The formatting shown here is the recommended convention, but Bison does not
1975 require it.  You can add or change white space as much as you wish.  For
1976 example, this:
1978 @example
1979 exp: NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
1980 @end example
1982 @noindent
1983 means the same thing as this:
1985 @example
1986 exp:
1987   NUM
1988 | exp exp '+'    @{ $$ = $1 + $2; @}
1989 | @dots{}
1991 @end example
1993 @noindent
1994 The latter, however, is much more readable.
1996 @node Rpcalc Lexer
1997 @subsection The @code{rpcalc} Lexical Analyzer
1998 @cindex writing a lexical analyzer
1999 @cindex lexical analyzer, writing
2001 The lexical analyzer's job is low-level parsing: converting characters
2002 or sequences of characters into tokens.  The Bison parser gets its
2003 tokens by calling the lexical analyzer.  @xref{Lexical}.
2005 Only a simple lexical analyzer is needed for the RPN
2006 calculator.  This
2007 lexical analyzer skips blanks and tabs, then reads in numbers as
2008 @code{double} and returns them as @code{NUM} tokens.  Any other character
2009 that isn't part of a number is a separate token.  Note that the token-code
2010 for such a single-character token is the character itself.
2012 The return value of the lexical analyzer function is a numeric code which
2013 represents a token kind.  The same text used in Bison rules to stand for
2014 this token kind is also a C expression for the numeric code of the kind.
2015 This works in two ways.  If the token kind is a character literal, then its
2016 numeric code is that of the character; you can use the same character
2017 literal in the lexical analyzer to express the number.  If the token kind is
2018 an identifier, that identifier is defined by Bison as a C enum whose
2019 definition is the appropriate code.  In this example, therefore, @code{NUM}
2020 becomes an enum for @code{yylex} to use.
2022 The semantic value of the token (if it has one) is stored into the global
2023 variable @code{yylval}, which is where the Bison parser will look for it.
2024 (The C data type of @code{yylval} is @code{YYSTYPE}, whose value was defined
2025 at the beginning of the grammar via @samp{%define api.value.type
2026 @{double@}}; @pxref{Rpcalc Declarations}.)
2028 A token kind code of zero is returned if the end-of-input is encountered.
2029 (Bison recognizes any nonpositive value as indicating end-of-input.)
2031 Here is the code for the lexical analyzer:
2033 @comment file: c/rpcalc/rpcalc.y
2034 @example
2035 @group
2036 /* The lexical analyzer returns a double floating point
2037    number on the stack and the token NUM, or the numeric code
2038    of the character read if not a number.  It skips all blanks
2039    and tabs, and returns 0 for end-of-input. */
2041 #include <ctype.h>
2042 #include <stdlib.h>
2043 @end group
2045 @group
2047 yylex (void)
2049   int c = getchar ();
2050   /* Skip white space. */
2051   while (c == ' ' || c == '\t')
2052     c = getchar ();
2053 @end group
2054 @group
2055   /* Process numbers. */
2056   if (c == '.' || isdigit (c))
2057     @{
2058       ungetc (c, stdin);
2059       if (scanf ("%lf", &yylval) != 1)
2060         abort ();
2061       return NUM;
2062     @}
2063 @end group
2064 @group
2065   /* Return end-of-input. */
2066   else if (c == EOF)
2067     return YYEOF;
2068   /* Return a single char. */
2069   else
2070     return c;
2072 @end group
2073 @end example
2075 @node Rpcalc Main
2076 @subsection The Controlling Function
2077 @cindex controlling function
2078 @cindex main function in simple example
2080 In keeping with the spirit of this example, the controlling function is
2081 kept to the bare minimum.  The only requirement is that it call
2082 @code{yyparse} to start the process of parsing.
2084 @comment file: c/rpcalc/rpcalc.y
2085 @example
2086 @group
2088 main (void)
2090   return yyparse ();
2092 @end group
2093 @end example
2095 @node Rpcalc Error
2096 @subsection The Error Reporting Routine
2097 @cindex error reporting routine
2099 When @code{yyparse} detects a syntax error, it calls the error reporting
2100 function @code{yyerror} to print an error message (usually but not
2101 always @code{"syntax error"}).  It is up to the programmer to supply
2102 @code{yyerror} (@pxref{Interface}), so
2103 here is the definition we will use:
2105 @comment file: c/rpcalc/rpcalc.y
2106 @example
2107 #include <stdio.h>
2109 @group
2110 /* Called by yyparse on error. */
2111 void
2112 yyerror (char const *s)
2114   fprintf (stderr, "%s\n", s);
2116 @end group
2117 @end example
2119 After @code{yyerror} returns, the Bison parser may recover from the error
2120 and continue parsing if the grammar contains a suitable error rule
2121 (@pxref{Error Recovery}).  Otherwise, @code{yyparse} returns nonzero.  We
2122 have not written any error rules in this example, so any invalid input will
2123 cause the calculator program to exit.  This is not clean behavior for a
2124 real calculator, but it is adequate for the first example.
2126 @node Rpcalc Generate
2127 @subsection Running Bison to Make the Parser
2128 @cindex running Bison (introduction)
2130 Before running Bison to produce a parser, we need to decide how to
2131 arrange all the source code in one or more source files.  For such a
2132 simple example, the easiest thing is to put everything in one file,
2133 the grammar file.  The definitions of @code{yylex}, @code{yyerror} and
2134 @code{main} go at the end, in the epilogue of the grammar file
2135 (@pxref{Grammar Layout}).
2137 For a large project, you would probably have several source files, and use
2138 @code{make} to arrange to recompile them.
2140 With all the source in the grammar file, you use the following command
2141 to convert it into a parser implementation file:
2143 @example
2144 $ @kbd{bison @var{file}.y}
2145 @end example
2147 @noindent
2148 In this example, the grammar file is called @file{rpcalc.y} (for
2149 ``Reverse Polish @sc{calc}ulator'').  Bison produces a parser
2150 implementation file named @file{@var{file}.tab.c}, removing the
2151 @samp{.y} from the grammar file name.  The parser implementation file
2152 contains the source code for @code{yyparse}.  The additional functions
2153 in the grammar file (@code{yylex}, @code{yyerror} and @code{main}) are
2154 copied verbatim to the parser implementation file.
2156 @node Rpcalc Compile
2157 @subsection Compiling the Parser Implementation File
2158 @cindex compiling the parser
2160 Here is how to compile and run the parser implementation file:
2162 @example
2163 @group
2164 # @r{List files in current directory.}
2165 $ @kbd{ls}
2166 rpcalc.tab.c  rpcalc.y
2167 @end group
2169 @group
2170 # @r{Compile the Bison parser.}
2171 # @r{@option{-lm} tells compiler to search math library for @code{pow}.}
2172 $ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
2173 @end group
2175 @group
2176 # @r{List files again.}
2177 $ @kbd{ls}
2178 rpcalc  rpcalc.tab.c  rpcalc.y
2179 @end group
2180 @end example
2182 The file @file{rpcalc} now contains the executable code.  Here is an
2183 example session using @code{rpcalc}.
2185 @example
2186 $ @kbd{rpcalc}
2187 @kbd{4 9 +}
2188 @result{} 13
2189 @kbd{3 7 + 3 4 5 *+-}
2190 @result{} -13
2191 @kbd{3 7 + 3 4 5 * + - n}              @r{Note the unary minus, @samp{n}}
2192 @result{} 13
2193 @kbd{5 6 / 4 n +}
2194 @result{} -3.166666667
2195 @kbd{3 4 ^}                            @r{Exponentiation}
2196 @result{} 81
2197 @kbd{^D}                               @r{End-of-file indicator}
2199 @end example
2201 @node Infix Calc
2202 @section Infix Notation Calculator: @code{calc}
2203 @cindex infix notation calculator
2204 @cindex @code{calc}
2205 @cindex calculator, infix notation
2207 We now modify rpcalc to handle infix operators instead of
2208 postfix.@footnote{A similar example, but using an unambiguous grammar rather
2209 than precedence and associativity annotations, is available as
2210 @file{examples/c/calc}.}  Infix
2211 notation involves the concept of operator precedence and the need for
2212 parentheses nested to arbitrary depth.  Here is the Bison code for
2213 @file{calc.y}, an infix desk-top calculator.
2215 @example
2216 /* Infix notation calculator. */
2218 @group
2220   #include <math.h>
2221   #include <stdio.h>
2222   int yylex (void);
2223   void yyerror (char const *);
2225 @end group
2227 @group
2228 /* Bison declarations. */
2229 %define api.value.type @{double@}
2230 %token NUM
2231 %left '-' '+'
2232 %left '*' '/'
2233 %precedence NEG   /* negation--unary minus */
2234 %right '^'        /* exponentiation */
2235 @end group
2237 %% /* The grammar follows. */
2238 @group
2239 input:
2240   %empty
2241 | input line
2243 @end group
2245 @group
2246 line:
2247   '\n'
2248 | exp '\n'  @{ printf ("\t%.10g\n", $1); @}
2250 @end group
2252 @group
2253 exp:
2254   NUM
2255 | exp '+' exp        @{ $$ = $1 + $3;      @}
2256 | exp '-' exp        @{ $$ = $1 - $3;      @}
2257 | exp '*' exp        @{ $$ = $1 * $3;      @}
2258 | exp '/' exp        @{ $$ = $1 / $3;      @}
2259 | '-' exp  %prec NEG @{ $$ = -$2;          @}
2260 | exp '^' exp        @{ $$ = pow ($1, $3); @}
2261 | '(' exp ')'        @{ $$ = $2;           @}
2263 @end group
2265 @end example
2267 @noindent
2268 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
2269 same as before.
2271 There are two important new features shown in this code.
2273 In the second section (Bison declarations), @code{%left} declares token
2274 kinds and says they are left-associative operators.  The declarations
2275 @code{%left} and @code{%right} (right associativity) take the place of
2276 @code{%token} which is used to declare a token kind name without
2277 associativity/precedence.  (These tokens are single-character literals,
2278 which ordinarily don't need to be declared.  We declare them here to specify
2279 the associativity/precedence.)
2281 Operator precedence is determined by the line ordering of the
2282 declarations; the higher the line number of the declaration (lower on
2283 the page or screen), the higher the precedence.  Hence, exponentiation
2284 has the highest precedence, unary minus (@code{NEG}) is next, followed
2285 by @samp{*} and @samp{/}, and so on.  Unary minus is not associative,
2286 only precedence matters (@code{%precedence}. @xref{Precedence}.
2288 The other important new feature is the @code{%prec} in the grammar
2289 section for the unary minus operator.  The @code{%prec} simply instructs
2290 Bison that the rule @samp{| '-' exp} has the same precedence as
2291 @code{NEG}---in this case the next-to-highest.  @xref{Contextual
2292 Precedence}.
2294 Here is a sample run of @file{calc.y}:
2296 @need 500
2297 @example
2298 $ @kbd{calc}
2299 @kbd{4 + 4.5 - (34/(8*3+-3))}
2300 6.880952381
2301 @kbd{-56 + 2}
2303 @kbd{3 ^ 2}
2305 @end example
2307 @node Simple Error Recovery
2308 @section Simple Error Recovery
2309 @cindex error recovery, simple
2311 Up to this point, this manual has not addressed the issue of @dfn{error
2312 recovery}---how to continue parsing after the parser detects a syntax
2313 error.  All we have handled is error reporting with @code{yyerror}.
2314 Recall that by default @code{yyparse} returns after calling
2315 @code{yyerror}.  This means that an erroneous input line causes the
2316 calculator program to exit.  Now we show how to rectify this deficiency.
2318 The Bison language itself includes the reserved word @code{error}, which
2319 may be included in the grammar rules.  In the example below it has
2320 been added to one of the alternatives for @code{line}:
2322 @example
2323 @group
2324 line:
2325   '\n'
2326 | exp '\n'   @{ printf ("\t%.10g\n", $1); @}
2327 | error '\n' @{ yyerrok;                  @}
2329 @end group
2330 @end example
2332 This addition to the grammar allows for simple error recovery in the
2333 event of a syntax error.  If an expression that cannot be evaluated is
2334 read, the error will be recognized by the third rule for @code{line},
2335 and parsing will continue.  (The @code{yyerror} function is still called
2336 upon to print its message as well.)  The action executes the statement
2337 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
2338 that error recovery is complete (@pxref{Error Recovery}).  Note the
2339 difference between @code{yyerrok} and @code{yyerror}; neither one is a
2340 misprint.
2342 This form of error recovery deals with syntax errors.  There are other
2343 kinds of errors; for example, division by zero, which raises an exception
2344 signal that is normally fatal.  A real calculator program must handle this
2345 signal and use @code{longjmp} to return to @code{main} and resume parsing
2346 input lines; it would also have to discard the rest of the current line of
2347 input.  We won't discuss this issue further because it is not specific to
2348 Bison programs.
2350 @node Location Tracking Calc
2351 @section Location Tracking Calculator: @code{ltcalc}
2352 @cindex location tracking calculator
2353 @cindex @code{ltcalc}
2354 @cindex calculator, location tracking
2356 This example extends the infix notation calculator with location
2357 tracking.  This feature will be used to improve the error messages.  For
2358 the sake of clarity, this example is a simple integer calculator, since
2359 most of the work needed to use locations will be done in the lexical
2360 analyzer.
2362 @menu
2363 * Ltcalc Declarations::    Bison and C declarations for ltcalc.
2364 * Ltcalc Rules::           Grammar rules for ltcalc, with explanations.
2365 * Ltcalc Lexer::           The lexical analyzer.
2366 @end menu
2368 @node Ltcalc Declarations
2369 @subsection Declarations for @code{ltcalc}
2371 The C and Bison declarations for the location tracking calculator are
2372 the same as the declarations for the infix notation calculator.
2374 @example
2375 /* Location tracking calculator. */
2378   #include <math.h>
2379   int yylex (void);
2380   void yyerror (char const *);
2383 /* Bison declarations. */
2384 %define api.value.type @{int@}
2385 %token NUM
2387 %left '-' '+'
2388 %left '*' '/'
2389 %precedence NEG
2390 %right '^'
2392 %% /* The grammar follows. */
2393 @end example
2395 @noindent
2396 Note there are no declarations specific to locations.  Defining a data type
2397 for storing locations is not needed: we will use the type provided by
2398 default (@pxref{Location Type}), which is a four member structure with the
2399 following integer fields: @code{first_line}, @code{first_column},
2400 @code{last_line} and @code{last_column}.  By conventions, and in accordance
2401 with the GNU Coding Standards and common practice, the line and column count
2402 both start at 1.
2404 @node Ltcalc Rules
2405 @subsection Grammar Rules for @code{ltcalc}
2407 Whether handling locations or not has no effect on the syntax of your
2408 language.  Therefore, grammar rules for this example will be very close
2409 to those of the previous example: we will only modify them to benefit
2410 from the new information.
2412 Here, we will use locations to report divisions by zero, and locate the
2413 wrong expressions or subexpressions.
2415 @example
2416 @group
2417 input:
2418   %empty
2419 | input line
2421 @end group
2423 @group
2424 line:
2425   '\n'
2426 | exp '\n' @{ printf ("%d\n", $1); @}
2428 @end group
2430 @group
2431 exp:
2432   NUM
2433 | exp '+' exp   @{ $$ = $1 + $3; @}
2434 | exp '-' exp   @{ $$ = $1 - $3; @}
2435 | exp '*' exp   @{ $$ = $1 * $3; @}
2436 @end group
2437 @group
2438 | exp '/' exp
2439     @{
2440       if ($3)
2441         $$ = $1 / $3;
2442       else
2443         @{
2444           $$ = 1;
2445           fprintf (stderr, "%d.%d-%d.%d: division by zero",
2446                    @@3.first_line, @@3.first_column,
2447                    @@3.last_line, @@3.last_column);
2448         @}
2449     @}
2450 @end group
2451 @group
2452 | '-' exp %prec NEG     @{ $$ = -$2; @}
2453 | exp '^' exp           @{ $$ = pow ($1, $3); @}
2454 | '(' exp ')'           @{ $$ = $2; @}
2455 @end group
2456 @end example
2458 This code shows how to reach locations inside of semantic actions, by
2459 using the pseudo-variables @code{@@@var{n}} for rule components, and the
2460 pseudo-variable @code{@@$} for groupings.
2462 We don't need to assign a value to @code{@@$}: the output parser does it
2463 automatically.  By default, before executing the C code of each action,
2464 @code{@@$} is set to range from the beginning of @code{@@1} to the end of
2465 @code{@@@var{n}}, for a rule with @var{n} components.  This behavior can be
2466 redefined (@pxref{Location Default Action}), and for very specific rules,
2467 @code{@@$} can be computed by hand.
2469 @node Ltcalc Lexer
2470 @subsection The @code{ltcalc} Lexical Analyzer.
2472 Until now, we relied on Bison's defaults to enable location
2473 tracking.  The next step is to rewrite the lexical analyzer, and make it
2474 able to feed the parser with the token locations, as it already does for
2475 semantic values.
2477 To this end, we must take into account every single character of the
2478 input text, to avoid the computed locations of being fuzzy or wrong:
2480 @example
2481 @group
2483 yylex (void)
2485   int c;
2486 @end group
2488 @group
2489   /* Skip white space. */
2490   while ((c = getchar ()) == ' ' || c == '\t')
2491     ++yylloc.last_column;
2492 @end group
2494 @group
2495   /* Step. */
2496   yylloc.first_line = yylloc.last_line;
2497   yylloc.first_column = yylloc.last_column;
2498 @end group
2500 @group
2501   /* Process numbers. */
2502   if (isdigit (c))
2503     @{
2504       yylval = c - '0';
2505       ++yylloc.last_column;
2506       while (isdigit (c = getchar ()))
2507         @{
2508           ++yylloc.last_column;
2509           yylval = yylval * 10 + c - '0';
2510         @}
2511       ungetc (c, stdin);
2512       return NUM;
2513     @}
2514 @end group
2516   /* Return end-of-input. */
2517   if (c == EOF)
2518     return YYEOF;
2520 @group
2521   /* Return a single char, and update location. */
2522   if (c == '\n')
2523     @{
2524       ++yylloc.last_line;
2525       yylloc.last_column = 0;
2526     @}
2527   else
2528     ++yylloc.last_column;
2529   return c;
2531 @end group
2532 @end example
2534 Basically, the lexical analyzer performs the same processing as before: it
2535 skips blanks and tabs, and reads numbers or single-character tokens.  In
2536 addition, it updates @code{yylloc}, the global variable (of type
2537 @code{YYLTYPE}) containing the token's location.
2539 Now, each time this function returns a token, the parser has its kind as
2540 well as its semantic value, and its location in the text.  The last needed
2541 change is to initialize @code{yylloc}, for example in the controlling
2542 function:
2544 @example
2545 @group
2547 main (void)
2549   yylloc.first_line = yylloc.last_line = 1;
2550   yylloc.first_column = yylloc.last_column = 0;
2551   return yyparse ();
2553 @end group
2554 @end example
2556 Remember that computing locations is not a matter of syntax.  Every
2557 character must be associated to a location update, whether it is in
2558 valid input, in comments, in literal strings, and so on.
2560 @node Multi-function Calc
2561 @section Multi-Function Calculator: @code{mfcalc}
2562 @cindex multi-function calculator
2563 @cindex @code{mfcalc}
2564 @cindex calculator, multi-function
2566 Now that the basics of Bison have been discussed, it is time to move on to a
2567 more advanced problem.@footnote{The sources of @command{mfcalc} are
2568 available as @file{examples/c/mfcalc}.}  The above calculators provided only
2569 five functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}.  It
2570 would be nice to have a calculator that provides other mathematical
2571 functions such as @code{sin}, @code{cos}, etc.
2573 It is easy to add new operators to the infix calculator as long as they are
2574 only single-character literals.  The lexical analyzer @code{yylex} passes
2575 back all nonnumeric characters as tokens, so new grammar rules suffice for
2576 adding a new operator.  But we want something more flexible: built-in
2577 functions whose syntax has this form:
2579 @example
2580 @var{function_name} (@var{argument})
2581 @end example
2583 @noindent
2584 At the same time, we will add memory to the calculator, by allowing you
2585 to create named variables, store values in them, and use them later.
2586 Here is a sample session with the multi-function calculator:
2588 @example
2589 @group
2590 $ @kbd{mfcalc}
2591 @kbd{pi = 3.141592653589}
2592 @result{} 3.1415926536
2593 @end group
2594 @group
2595 @kbd{sin(pi)}
2596 @result{} 0.0000000000
2597 @end group
2598 @kbd{alpha = beta1 = 2.3}
2599 @result{} 2.3000000000
2600 @kbd{alpha}
2601 @result{} 2.3000000000
2602 @kbd{ln(alpha)}
2603 @result{} 0.8329091229
2604 @kbd{exp(ln(beta1))}
2605 @result{} 2.3000000000
2607 @end example
2609 Note that multiple assignment and nested function calls are permitted.
2611 @menu
2612 * Mfcalc Declarations::    Bison declarations for multi-function calculator.
2613 * Mfcalc Rules::           Grammar rules for the calculator.
2614 * Mfcalc Symbol Table::    Symbol table management subroutines.
2615 * Mfcalc Lexer::           The lexical analyzer.
2616 * Mfcalc Main::            The controlling function.
2617 @end menu
2619 @node Mfcalc Declarations
2620 @subsection Declarations for @code{mfcalc}
2622 Here are the C and Bison declarations for the multi-function
2623 calculator.
2625 @ignore
2626 @comment file: c/mfcalc/mfcalc.y
2627 @example
2628 /* Parser for mfcalc.   -*- C -*-
2630    Copyright (C) 1988-1993, 1995, 1998-2015, 2018-2021 Free Software
2631    Foundation, Inc.
2633    This file is part of Bison, the GNU Compiler Compiler.
2635    This program is free software: you can redistribute it and/or modify
2636    it under the terms of the GNU General Public License as published by
2637    the Free Software Foundation, either version 3 of the License, or
2638    (at your option) any later version.
2640    This program is distributed in the hope that it will be useful,
2641    but WITHOUT ANY WARRANTY; without even the implied warranty of
2642    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2643    GNU General Public License for more details.
2645    You should have received a copy of the GNU General Public License
2646    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
2648 %code top {
2649   /* Portability issues for strdup. */
2650 #ifndef _XOPEN_SOURCE
2651 # define _XOPEN_SOURCE 600
2652 #endif
2654 @end example
2655 @end ignore
2657 @comment file: c/mfcalc/mfcalc.y: 1
2658 @example
2659 @group
2661   #include <stdio.h>  /* For printf, etc. */
2662   #include <math.h>   /* For pow, used in the grammar. */
2663   #include "calc.h"   /* Contains definition of 'symrec'. */
2664   int yylex (void);
2665   void yyerror (char const *);
2667 @end group
2669 %define api.value.type union /* Generate YYSTYPE from these types: */
2670 %token <double>  NUM     /* Double precision number. */
2671 %token <symrec*> VAR FUN /* Symbol table pointer: variable/function. */
2672 %nterm <double>  exp
2674 @group
2675 %precedence '='
2676 %left '-' '+'
2677 %left '*' '/'
2678 %precedence NEG /* negation--unary minus */
2679 %right '^'      /* exponentiation */
2680 @end group
2681 @end example
2683 The above grammar introduces only two new features of the Bison language.
2684 These features allow semantic values to have various data types
2685 (@pxref{Multiple Types}).
2687 The special @code{union} value assigned to the @code{%define} variable
2688 @code{api.value.type} specifies that the symbols are defined with their data
2689 types.  Bison will generate an appropriate definition of @code{YYSTYPE} to
2690 store these values.
2692 Since values can now have various types, it is necessary to associate a type
2693 with each grammar symbol whose semantic value is used.  These symbols are
2694 @code{NUM}, @code{VAR}, @code{FUN}, and @code{exp}.  Their declarations are
2695 augmented with their data type (placed between angle brackets).  For
2696 instance, values of @code{NUM} are stored in @code{double}.
2698 The Bison construct @code{%nterm} is used for declaring nonterminal symbols,
2699 just as @code{%token} is used for declaring token kinds.  Previously we did
2700 not use @code{%nterm} before because nonterminal symbols are normally
2701 declared implicitly by the rules that define them.  But @code{exp} must be
2702 declared explicitly so we can specify its value type.  @xref{Type Decl}.
2704 @node Mfcalc Rules
2705 @subsection Grammar Rules for @code{mfcalc}
2707 Here are the grammar rules for the multi-function calculator.
2708 Most of them are copied directly from @code{calc}; three rules,
2709 those which mention @code{VAR} or @code{FUN}, are new.
2711 @comment file: c/mfcalc/mfcalc.y: 3
2712 @example
2713 %% /* The grammar follows. */
2714 @group
2715 input:
2716   %empty
2717 | input line
2719 @end group
2721 @group
2722 line:
2723   '\n'
2724 | exp '\n'   @{ printf ("%.10g\n", $1); @}
2725 | error '\n' @{ yyerrok;                @}
2727 @end group
2729 @group
2730 exp:
2731   NUM
2732 | VAR                @{ $$ = $1->value.var;              @}
2733 | VAR '=' exp        @{ $$ = $3; $1->value.var = $3;     @}
2734 | FUN '(' exp ')'    @{ $$ = $1->value.fun ($3);         @}
2735 | exp '+' exp        @{ $$ = $1 + $3;                    @}
2736 | exp '-' exp        @{ $$ = $1 - $3;                    @}
2737 | exp '*' exp        @{ $$ = $1 * $3;                    @}
2738 | exp '/' exp        @{ $$ = $1 / $3;                    @}
2739 | '-' exp  %prec NEG @{ $$ = -$2;                        @}
2740 | exp '^' exp        @{ $$ = pow ($1, $3);               @}
2741 | '(' exp ')'        @{ $$ = $2;                         @}
2743 @end group
2744 /* End of grammar. */
2746 @end example
2748 @node Mfcalc Symbol Table
2749 @subsection The @code{mfcalc} Symbol Table
2750 @cindex symbol table example
2752 The multi-function calculator requires a symbol table to keep track of the
2753 names and meanings of variables and functions.  This doesn't affect the
2754 grammar rules (except for the actions) or the Bison declarations, but it
2755 requires some additional C functions for support.
2757 The symbol table itself consists of a linked list of records.  Its
2758 definition, which is kept in the header @file{calc.h}, is as follows.  It
2759 provides for either functions or variables to be placed in the table.
2761 @ignore
2762 @comment file: c/mfcalc/calc.h
2763 @example
2764 /* Functions for mfcalc.   -*- C -*-
2766    Copyright (C) 1988-1993, 1995, 1998-2015, 2018-2021 Free Software
2767    Foundation, Inc.
2769    This file is part of Bison, the GNU Compiler Compiler.
2771    This program is free software: you can redistribute it and/or modify
2772    it under the terms of the GNU General Public License as published by
2773    the Free Software Foundation, either version 3 of the License, or
2774    (at your option) any later version.
2776    This program is distributed in the hope that it will be useful,
2777    but WITHOUT ANY WARRANTY; without even the implied warranty of
2778    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2779    GNU General Public License for more details.
2781    You should have received a copy of the GNU General Public License
2782    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
2783 @end example
2784 @end ignore
2786 @comment file: c/mfcalc/calc.h
2787 @example
2788 @group
2789 /* Function type. */
2790 typedef double (func_t) (double);
2791 @end group
2793 @group
2794 /* Data type for links in the chain of symbols. */
2795 struct symrec
2797   char *name;  /* name of symbol */
2798   int type;    /* type of symbol: either VAR or FUN */
2799   union
2800   @{
2801     double var;    /* value of a VAR */
2802     func_t *fun;   /* value of a FUN */
2803   @} value;
2804   struct symrec *next;  /* link field */
2806 @end group
2808 @group
2809 typedef struct symrec symrec;
2811 /* The symbol table: a chain of 'struct symrec'. */
2812 extern symrec *sym_table;
2814 symrec *putsym (char const *name, int sym_type);
2815 symrec *getsym (char const *name);
2816 @end group
2817 @end example
2819 The new version of @code{main} will call @code{init_table} to initialize
2820 the symbol table:
2822 @comment file: c/mfcalc/mfcalc.y: 3
2823 @example
2824 @group
2825 struct init
2827   char const *name;
2828   func_t *fun;
2830 @end group
2832 @group
2833 struct init const funs[] =
2835   @{ "atan", atan @},
2836   @{ "cos",  cos  @},
2837   @{ "exp",  exp  @},
2838   @{ "ln",   log  @},
2839   @{ "sin",  sin  @},
2840   @{ "sqrt", sqrt @},
2841   @{ 0, 0 @},
2843 @end group
2845 @group
2846 /* The symbol table: a chain of 'struct symrec'. */
2847 symrec *sym_table;
2848 @end group
2850 @group
2851 /* Put functions in table. */
2852 static void
2853 init_table (void)
2854 @end group
2855 @group
2857   for (int i = 0; funs[i].name; i++)
2858     @{
2859       symrec *ptr = putsym (funs[i].name, FUN);
2860       ptr->value.fun = funs[i].fun;
2861     @}
2863 @end group
2864 @end example
2866 By simply editing the initialization list and adding the necessary include
2867 files, you can add additional functions to the calculator.
2869 Two important functions allow look-up and installation of symbols in the
2870 symbol table.  The function @code{putsym} is passed a name and the kind
2871 (@code{VAR} or @code{FUN}) of the object to be installed.  The object is
2872 linked to the front of the list, and a pointer to the object is returned.
2873 The function @code{getsym} is passed the name of the symbol to look up.  If
2874 found, a pointer to that symbol is returned; otherwise zero is returned.
2876 @comment file: c/mfcalc/mfcalc.y: 3
2877 @example
2878 @group
2879 /* The mfcalc code assumes that malloc and realloc
2880    always succeed, and that integer calculations
2881    never overflow.  Production-quality code should
2882    not make these assumptions.  */
2883 #include <assert.h>
2884 #include <stdlib.h> /* malloc, realloc. */
2885 #include <string.h> /* strdup, strlen. */
2886 @end group
2888 @group
2889 symrec *
2890 putsym (char const *name, int sym_type)
2892   symrec *res = (symrec *) malloc (sizeof (symrec));
2893   res->name = strdup (name);
2894   res->type = sym_type;
2895   res->value.var = 0; /* Set value to 0 even if fun. */
2896   res->next = sym_table;
2897   sym_table = res;
2898   return res;
2900 @end group
2902 @group
2903 symrec *
2904 getsym (char const *name)
2906   for (symrec *p = sym_table; p; p = p->next)
2907     if (strcmp (p->name, name) == 0)
2908       return p;
2909   return NULL;
2911 @end group
2912 @end example
2914 @node Mfcalc Lexer
2915 @subsection The @code{mfcalc} Lexer
2917 The function @code{yylex} must now recognize variables, numeric values, and
2918 the single-character arithmetic operators.  Strings of alphanumeric
2919 characters with a leading letter are recognized as either variables or
2920 functions depending on what the symbol table says about them.
2922 The string is passed to @code{getsym} for look up in the symbol table.  If
2923 the name appears in the table, a pointer to its location and its type
2924 (@code{VAR} or @code{FUN}) is returned to @code{yyparse}.  If it is not
2925 already in the table, then it is installed as a @code{VAR} using
2926 @code{putsym}.  Again, a pointer and its type (which must be @code{VAR}) is
2927 returned to @code{yyparse}.
2929 No change is needed in the handling of numeric values and arithmetic
2930 operators in @code{yylex}.
2932 @comment file: c/mfcalc/mfcalc.y: 3
2933 @example
2934 #include <ctype.h>
2935 #include <stddef.h>
2937 @group
2939 yylex (void)
2941   int c = getchar ();
2943   /* Ignore white space, get first nonwhite character. */
2944   while (c == ' ' || c == '\t')
2945     c = getchar ();
2947   if (c == EOF)
2948     return YYEOF;
2949 @end group
2951 @group
2952   /* Char starts a number => parse the number. */
2953   if (c == '.' || isdigit (c))
2954     @{
2955       ungetc (c, stdin);
2956       if (scanf ("%lf", &yylval.NUM) != 1)
2957         abort ();
2958       return NUM;
2959     @}
2960 @end group
2961 @end example
2963 @noindent
2964 Bison generated a definition of @code{YYSTYPE} with a member named
2965 @code{NUM} to store value of @code{NUM} symbols.
2967 @comment file: c/mfcalc/mfcalc.y: 3
2968 @example
2969 @group
2970   /* Char starts an identifier => read the name. */
2971   if (isalpha (c))
2972     @{
2973       static ptrdiff_t bufsize = 0;
2974       static char *symbuf = 0;
2975 @end group
2976       ptrdiff_t i = 0;
2977       do
2978 @group
2979         @{
2980           /* If buffer is full, make it bigger. */
2981           if (bufsize <= i)
2982             @{
2983               bufsize = 2 * bufsize + 40;
2984               symbuf = realloc (symbuf, (size_t) bufsize);
2985             @}
2986           /* Add this character to the buffer. */
2987           symbuf[i++] = (char) c;
2988           /* Get another character. */
2989           c = getchar ();
2990         @}
2991 @end group
2992 @group
2993       while (isalnum (c));
2995       ungetc (c, stdin);
2996       symbuf[i] = '\0';
2997 @end group
2999 @group
3000       symrec *s = getsym (symbuf);
3001       if (!s)
3002         s = putsym (symbuf, VAR);
3003       yylval.VAR = s; /* or yylval.FUN = s. */
3004       return s->type;
3005     @}
3007   /* Any other character is a token by itself. */
3008   return c;
3010 @end group
3011 @end example
3013 @node Mfcalc Main
3014 @subsection The @code{mfcalc} Main
3016 The error reporting function is unchanged, and the new version of
3017 @code{main} includes a call to @code{init_table} and sets the @code{yydebug}
3018 on user demand (@xref{Tracing}, for details):
3020 @comment file: c/mfcalc/mfcalc.y: 3
3021 @example
3022 @group
3023 /* Called by yyparse on error. */
3024 void yyerror (char const *s)
3026   fprintf (stderr, "%s\n", s);
3028 @end group
3030 @group
3031 int main (int argc, char const* argv[])
3032 @end group
3033 @group
3035   /* Enable parse traces on option -p. */
3036   if (argc == 2 && strcmp(argv[1], "-p") == 0)
3037     yydebug = 1;
3038 @end group
3039 @group
3040   init_table ();
3041   return yyparse ();
3043 @end group
3044 @end example
3046 This program is both powerful and flexible.  You may easily add new
3047 functions, and it is a simple job to modify this code to install
3048 predefined variables such as @code{pi} or @code{e} as well.
3050 @node Exercises
3051 @section Exercises
3052 @cindex exercises
3054 @enumerate
3055 @item
3056 Add some new functions from @file{math.h} to the initialization list.
3058 @item
3059 Add another array that contains constants and their values.  Then modify
3060 @code{init_table} to add these constants to the symbol table.  It will be
3061 easiest to give the constants type @code{VAR}.
3063 @item
3064 Make the program report an error if the user refers to an uninitialized
3065 variable in any way except to store a value in it.
3066 @end enumerate
3068 @node Grammar File
3069 @chapter Bison Grammar Files
3071 Bison takes as input a context-free grammar specification and produces a
3072 C-language function that recognizes correct instances of the grammar.
3074 The Bison grammar file conventionally has a name ending in @samp{.y}.
3075 @xref{Invocation}.
3077 @menu
3078 * Grammar Outline::    Overall layout of the grammar file.
3079 * Symbols::            Terminal and nonterminal symbols.
3080 * Rules::              How to write grammar rules.
3081 * Semantics::          Semantic values and actions.
3082 * Tracking Locations:: Locations and actions.
3083 * Named References::   Using named references in actions.
3084 * Declarations::       All kinds of Bison declarations are described here.
3085 * Multiple Parsers::   Putting more than one Bison parser in one program.
3086 @end menu
3088 @node Grammar Outline
3089 @section Outline of a Bison Grammar
3090 @cindex comment
3091 @findex // @dots{}
3092 @findex /* @dots{} */
3094 A Bison grammar file has four main sections, shown here with the
3095 appropriate delimiters:
3097 @example
3099   @var{Prologue}
3102 @var{Bison declarations}
3105 @var{Grammar rules}
3108 @var{Epilogue}
3109 @end example
3111 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
3112 As a GNU extension, @samp{//} introduces a comment that continues until end
3113 of line.
3115 @menu
3116 * Prologue::              Syntax and usage of the prologue.
3117 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
3118 * Bison Declarations::    Syntax and usage of the Bison declarations section.
3119 * Grammar Rules::         Syntax and usage of the grammar rules section.
3120 * Epilogue::              Syntax and usage of the epilogue.
3121 @end menu
3123 @node Prologue
3124 @subsection The prologue
3125 @cindex declarations section
3126 @cindex Prologue
3127 @cindex declarations
3129 The @var{Prologue} section contains macro definitions and declarations of
3130 functions and variables that are used in the actions in the grammar rules.
3131 These are copied to the beginning of the parser implementation file so that
3132 they precede the definition of @code{yyparse}.  You can use @samp{#include}
3133 to get the declarations from a header file.  If you don't need any C
3134 declarations, you may omit the @samp{%@{} and @samp{%@}} delimiters that
3135 bracket this section.
3137 The @var{Prologue} section is terminated by the first occurrence of
3138 @samp{%@}} that is outside a comment, a string literal, or a character
3139 constant.
3141 You may have more than one @var{Prologue} section, intermixed with the
3142 @var{Bison declarations}.  This allows you to have C and Bison declarations
3143 that refer to each other.  For example, the @code{%union} declaration may
3144 use types defined in a header file, and you may wish to prototype functions
3145 that take arguments of type @code{YYSTYPE}.  This can be done with two
3146 @var{Prologue} blocks, one before and one after the @code{%union}
3147 declaration.
3149 @example
3150 @group
3152   #define _GNU_SOURCE
3153   #include <stdio.h>
3154   #include "ptypes.h"
3156 @end group
3158 @group
3159 %union @{
3160   long n;
3161   tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
3163 @end group
3165 @group
3167   static void print_token (yytoken_kind_t token, YYSTYPE val);
3169 @end group
3171 @dots{}
3172 @end example
3174 When in doubt, it is usually safer to put prologue code before all Bison
3175 declarations, rather than after.  For example, any definitions of feature
3176 test macros like @code{_GNU_SOURCE} or @code{_POSIX_C_SOURCE} should appear
3177 before all Bison declarations, as feature test macros can affect the
3178 behavior of Bison-generated @code{#include} directives.
3180 @node Prologue Alternatives
3181 @subsection Prologue Alternatives
3182 @cindex Prologue Alternatives
3184 @findex %code
3185 @findex %code requires
3186 @findex %code provides
3187 @findex %code top
3189 The functionality of @var{Prologue} sections can often be subtle and
3190 inflexible.  As an alternative, Bison provides a @code{%code} directive with
3191 an explicit qualifier field, which identifies the purpose of the code and
3192 thus the location(s) where Bison should generate it.  For C/C++, the
3193 qualifier can be omitted for the default location, or it can be one of
3194 @code{requires}, @code{provides}, @code{top}.  @xref{%code Summary}.
3196 Look again at the example of the previous section:
3198 @example
3199 @group
3201   #define _GNU_SOURCE
3202   #include <stdio.h>
3203   #include "ptypes.h"
3205 @end group
3207 @group
3208 %union @{
3209   long n;
3210   tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
3212 @end group
3214 @group
3216   static void print_token (yytoken_kind_t token, YYSTYPE val);
3218 @end group
3220 @dots{}
3221 @end example
3223 @noindent
3224 Notice that there are two @var{Prologue} sections here, but there's a subtle
3225 distinction between their functionality.  For example, if you decide to
3226 override Bison's default definition for @code{YYLTYPE}, in which
3227 @var{Prologue} section should you write your new
3228 definition?@footnote{However, defining @code{YYLTYPE} via a C macro is not
3229 the recommended way.  @xref{Location Type}}
3230 You should
3231 write it in the first since Bison will insert that code into the parser
3232 implementation file @emph{before} the default @code{YYLTYPE} definition.  In
3233 which @var{Prologue} section should you prototype an internal function,
3234 @code{trace_token}, that accepts @code{YYLTYPE} and @code{yytoken_kind_t} as
3235 arguments?  You should prototype it in the second since Bison will insert
3236 that code @emph{after} the @code{YYLTYPE} and @code{yytoken_kind_t}
3237 definitions.
3239 This distinction in functionality between the two @var{Prologue} sections is
3240 established by the appearance of the @code{%union} between them.  This
3241 behavior raises a few questions.  First, why should the position of a
3242 @code{%union} affect definitions related to @code{YYLTYPE} and
3243 @code{yytoken_kind_t}?  Second, what if there is no @code{%union}?  In that
3244 case, the second kind of @var{Prologue} section is not available.  This
3245 behavior is not intuitive.
3247 To avoid this subtle @code{%union} dependency, rewrite the example using a
3248 @code{%code top} and an unqualified @code{%code}.  Let's go ahead and add
3249 the new @code{YYLTYPE} definition and the @code{trace_token} prototype at
3250 the same time:
3252 @example
3253 %code top @{
3254   #define _GNU_SOURCE
3255   #include <stdio.h>
3257   /* WARNING: The following code really belongs
3258    * in a '%code requires'; see below. */
3260   #include "ptypes.h"
3261   #define YYLTYPE YYLTYPE
3262   typedef struct YYLTYPE
3263   @{
3264     int first_line;
3265     int first_column;
3266     int last_line;
3267     int last_column;
3268     char *filename;
3269   @} YYLTYPE;
3272 @group
3273 %union @{
3274   long n;
3275   tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
3277 @end group
3279 @group
3280 %code @{
3281   static void print_token (yytoken_kind_t token, YYSTYPE val);
3282   static void trace_token (yytoken_kind_t token, YYLTYPE loc);
3284 @end group
3286 @dots{}
3287 @end example
3289 @noindent
3290 In this way, @code{%code top} and the unqualified @code{%code} achieve the
3291 same functionality as the two kinds of @var{Prologue} sections, but it's
3292 always explicit which kind you intend.  Moreover, both kinds are always
3293 available even in the absence of @code{%union}.
3295 The @code{%code top} block above logically contains two parts.  The first
3296 two lines before the warning need to appear near the top of the parser
3297 implementation file.  The first line after the warning is required by
3298 @code{YYSTYPE} and thus also needs to appear in the parser implementation
3299 file.  However, if you've instructed Bison to generate a parser header file
3300 (@pxref{Decl Summary}), you probably want that line to appear
3301 before the @code{YYSTYPE} definition in that header file as well.  The
3302 @code{YYLTYPE} definition should also appear in the parser header file to
3303 override the default @code{YYLTYPE} definition there.
3305 In other words, in the @code{%code top} block above, all but the first two
3306 lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
3307 definitions.
3308 Thus, they belong in one or more @code{%code requires}:
3310 @example
3311 @group
3312 %code top @{
3313   #define _GNU_SOURCE
3314   #include <stdio.h>
3316 @end group
3318 @group
3319 %code requires @{
3320   #include "ptypes.h"
3322 @end group
3323 @group
3324 %union @{
3325   long n;
3326   tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
3328 @end group
3330 @group
3331 %code requires @{
3332   #define YYLTYPE YYLTYPE
3333   typedef struct YYLTYPE
3334   @{
3335     int first_line;
3336     int first_column;
3337     int last_line;
3338     int last_column;
3339     char *filename;
3340   @} YYLTYPE;
3342 @end group
3344 @group
3345 %code @{
3346   static void print_token (yytoken_kind_t token, YYSTYPE val);
3347   static void trace_token (yytoken_kind_t token, YYLTYPE loc);
3349 @end group
3351 @dots{}
3352 @end example
3354 @noindent
3355 Now Bison will insert @code{#include "ptypes.h"} and the new @code{YYLTYPE}
3356 definition before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
3357 definitions in both the parser implementation file and the parser header
3358 file.  (By the same reasoning, @code{%code requires} would also be the
3359 appropriate place to write your own definition for @code{YYSTYPE}.)
3361 When you are writing dependency code for @code{YYSTYPE} and @code{YYLTYPE},
3362 you should prefer @code{%code requires} over @code{%code top} regardless of
3363 whether you instruct Bison to generate a parser header file.  When you are
3364 writing code that you need Bison to insert only into the parser
3365 implementation file and that has no special need to appear at the top of
3366 that file, you should prefer the unqualified @code{%code} over @code{%code
3367 top}.  These practices will make the purpose of each block of your code
3368 explicit to Bison and to other developers reading your grammar file.
3369 Following these practices, we expect the unqualified @code{%code} and
3370 @code{%code requires} to be the most important of the four @var{Prologue}
3371 alternatives.
3373 At some point while developing your parser, you might decide to provide
3374 @code{trace_token} to modules that are external to your parser.  Thus, you
3375 might wish for Bison to insert the prototype into both the parser header
3376 file and the parser implementation file.  Since this function is not a
3377 dependency required by @code{YYSTYPE} or @code{YYLTYPE}, it doesn't make
3378 sense to move its prototype to a @code{%code requires}.  More importantly,
3379 since it depends upon @code{YYLTYPE} and @code{yytoken_kind_t}, @code{%code
3380 requires} is not sufficient.  Instead, move its prototype from the
3381 unqualified @code{%code} to a @code{%code provides}:
3383 @example
3384 @group
3385 %code top @{
3386   #define _GNU_SOURCE
3387   #include <stdio.h>
3389 @end group
3391 @group
3392 %code requires @{
3393   #include "ptypes.h"
3395 @end group
3396 @group
3397 %union @{
3398   long n;
3399   tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
3401 @end group
3403 @group
3404 %code requires @{
3405   #define YYLTYPE YYLTYPE
3406   typedef struct YYLTYPE
3407   @{
3408     int first_line;
3409     int first_column;
3410     int last_line;
3411     int last_column;
3412     char *filename;
3413   @} YYLTYPE;
3415 @end group
3417 @group
3418 %code provides @{
3419   void trace_token (yytoken_kind_t token, YYLTYPE loc);
3421 @end group
3423 @group
3424 %code @{
3425   static void print_token (FILE *file, int token, YYSTYPE val);
3427 @end group
3429 @dots{}
3430 @end example
3432 @noindent
3433 Bison will insert the @code{trace_token} prototype into both the parser
3434 header file and the parser implementation file after the definitions for
3435 @code{yytoken_kind_t}, @code{YYLTYPE}, and @code{YYSTYPE}.
3437 The above examples are careful to write directives in an order that reflects
3438 the layout of the generated parser implementation and header files:
3439 @code{%code top}, @code{%code requires}, @code{%code provides}, and then
3440 @code{%code}.  While your grammar files may generally be easier to read if
3441 you also follow this order, Bison does not require it.  Instead, Bison lets
3442 you choose an organization that makes sense to you.
3444 You may declare any of these directives multiple times in the grammar file.
3445 In that case, Bison concatenates the contained code in declaration order.
3446 This is the only way in which the position of one of these directives within
3447 the grammar file affects its functionality.
3449 The result of the previous two properties is greater flexibility in how you may
3450 organize your grammar file.
3451 For example, you may organize semantic-type-related directives by semantic
3452 type:
3454 @example
3455 @group
3456 %code requires @{ #include "type1.h" @}
3457 %union @{ type1 field1; @}
3458 %destructor @{ type1_free ($$); @} <field1>
3459 %printer @{ type1_print (yyo, $$); @} <field1>
3460 @end group
3462 @group
3463 %code requires @{ #include "type2.h" @}
3464 %union @{ type2 field2; @}
3465 %destructor @{ type2_free ($$); @} <field2>
3466 %printer @{ type2_print (yyo, $$); @} <field2>
3467 @end group
3468 @end example
3470 @noindent
3471 You could even place each of the above directive groups in the rules section of
3472 the grammar file next to the set of rules that uses the associated semantic
3473 type.
3474 (In the rules section, you must terminate each of those directives with a
3475 semicolon.)
3476 And you don't have to worry that some directive (like a @code{%union}) in the
3477 definitions section is going to adversely affect their functionality in some
3478 counter-intuitive manner just because it comes first.
3479 Such an organization is not possible using @var{Prologue} sections.
3481 This section has been concerned with explaining the advantages of the four
3482 @var{Prologue} alternatives over the original Yacc @var{Prologue}.
3483 However, in most cases when using these directives, you shouldn't need to
3484 think about all the low-level ordering issues discussed here.
3485 Instead, you should simply use these directives to label each block of your
3486 code according to its purpose and let Bison handle the ordering.
3487 @code{%code} is the most generic label.
3488 Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
3489 as needed.
3491 @node Bison Declarations
3492 @subsection The Bison Declarations Section
3493 @cindex Bison declarations (introduction)
3494 @cindex declarations, Bison (introduction)
3496 The @var{Bison declarations} section contains declarations that define
3497 terminal and nonterminal symbols, specify precedence, and so on.
3498 In some simple grammars you may not need any declarations.
3499 @xref{Declarations}.
3501 @node Grammar Rules
3502 @subsection The Grammar Rules Section
3503 @cindex grammar rules section
3504 @cindex rules section for grammar
3506 The @dfn{grammar rules} section contains one or more Bison grammar
3507 rules, and nothing else.  @xref{Rules}.
3509 There must always be at least one grammar rule, and the first
3510 @samp{%%} (which precedes the grammar rules) may never be omitted even
3511 if it is the first thing in the file.
3513 @node Epilogue
3514 @subsection The epilogue
3515 @cindex additional C code section
3516 @cindex epilogue
3517 @cindex C code, section for additional
3519 The @var{Epilogue} is copied verbatim to the end of the parser
3520 implementation file, just as the @var{Prologue} is copied to the
3521 beginning.  This is the most convenient place to put anything that you
3522 want to have in the parser implementation file but which need not come
3523 before the definition of @code{yyparse}.  For example, the definitions
3524 of @code{yylex} and @code{yyerror} often go here.  Because C requires
3525 functions to be declared before being used, you often need to declare
3526 functions like @code{yylex} and @code{yyerror} in the Prologue, even
3527 if you define them in the Epilogue.  @xref{Interface}.
3529 If the last section is empty, you may omit the @samp{%%} that separates it
3530 from the grammar rules.
3532 The Bison parser itself contains many macros and identifiers whose names
3533 start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3534 any such names (except those documented in this manual) in the epilogue
3535 of the grammar file.
3537 @node Symbols
3538 @section Symbols, Terminal and Nonterminal
3539 @cindex nonterminal symbol
3540 @cindex terminal symbol
3541 @cindex token kind
3542 @cindex symbol
3544 @dfn{Symbols} in Bison grammars represent the grammatical classifications
3545 of the language.
3547 A @dfn{terminal symbol} (also known as a @dfn{token kind}) represents a
3548 class of syntactically equivalent tokens.  You use the symbol in grammar
3549 rules to mean that a token in that class is allowed.  The symbol is
3550 represented in the Bison parser by a numeric code, and the @code{yylex}
3551 function returns a token kind code to indicate what kind of token has been
3552 read.  You don't need to know what the code value is; you can use the symbol
3553 to stand for it.
3555 A @dfn{nonterminal symbol} stands for a class of syntactically
3556 equivalent groupings.  The symbol name is used in writing grammar rules.
3557 By convention, it should be all lower case.
3559 Symbol names can contain letters, underscores, periods, and non-initial
3560 digits and dashes.  Dashes in symbol names are a GNU extension, incompatible
3561 with POSIX Yacc.  Periods and dashes make symbol names less convenient to
3562 use with named references, which require brackets around such names
3563 (@pxref{Named References}).  Terminal symbols that contain periods or dashes
3564 make little sense: since they are not valid symbols (in most programming
3565 languages) they are not exported as token names.
3567 There are three ways of writing terminal symbols in the grammar:
3569 @itemize @bullet
3570 @item
3571 A @dfn{named token kind} is written with an identifier, like an identifier
3572 in C@.  By convention, it should be all upper case.  Each such name must be
3573 defined with a Bison declaration such as @code{%token}.  @xref{Token Decl}.
3575 @item
3576 @cindex character token
3577 @cindex literal token
3578 @cindex single-character literal
3579 A @dfn{character token kind} (or @dfn{literal character token}) is written
3580 in the grammar using the same syntax used in C for character constants; for
3581 example, @code{'+'} is a character token kind.  A character token kind
3582 doesn't need to be declared unless you need to specify its semantic value
3583 data type (@pxref{Value Type}), associativity, or precedence
3584 (@pxref{Precedence}).
3586 By convention, a character token kind is used only to represent a token that
3587 consists of that particular character.  Thus, the token kind @code{'+'} is
3588 used to represent the character @samp{+} as a token.  Nothing enforces this
3589 convention, but if you depart from it, your program will confuse other
3590 readers.
3592 All the usual escape sequences used in character literals in C can be used
3593 in Bison as well, but you must not use the null character as a character
3594 literal because its numeric code, zero, signifies end-of-input
3595 (@pxref{Calling Convention}).  Also, unlike standard C, trigraphs have no
3596 special meaning in Bison character literals, nor is backslash-newline
3597 allowed.
3599 @item
3600 @cindex string token
3601 @cindex literal string token
3602 @cindex multicharacter literal
3603 A @dfn{literal string token} is written like a C string constant; for
3604 example, @code{"<="} is a literal string token.  A literal string token
3605 doesn't need to be declared unless you need to specify its semantic
3606 value data type (@pxref{Value Type}), associativity, or precedence
3607 (@pxref{Precedence}).
3609 You can associate the literal string token with a symbolic name as an alias,
3610 using the @code{%token} declaration (@pxref{Token Decl}).  If you don't do
3611 that, the lexical analyzer has to retrieve the token code for the literal
3612 string token from the @code{yytname} table (@pxref{Calling Convention}).
3614 @strong{Warning}: literal string tokens do not work in Yacc.
3616 By convention, a literal string token is used only to represent a token
3617 that consists of that particular string.  Thus, you should use the token
3618 kind @code{"<="} to represent the string @samp{<=} as a token.  Bison
3619 does not enforce this convention, but if you depart from it, people who
3620 read your program will be confused.
3622 All the escape sequences used in string literals in C can be used in
3623 Bison as well, except that you must not use a null character within a
3624 string literal.  Also, unlike Standard C, trigraphs have no special
3625 meaning in Bison string literals, nor is backslash-newline allowed.  A
3626 literal string token must contain two or more characters; for a token
3627 containing just one character, use a character token (see above).
3628 @end itemize
3630 How you choose to write a terminal symbol has no effect on its
3631 grammatical meaning.  That depends only on where it appears in rules and
3632 on when the parser function returns that symbol.
3634 The value returned by @code{yylex} is always one of the terminal
3635 symbols, except that a zero or negative value signifies end-of-input.
3636 Whichever way you write the token kind in the grammar rules, you write
3637 it the same way in the definition of @code{yylex}.  The numeric code
3638 for a character token kind is simply the positive numeric code of the
3639 character, so @code{yylex} can use the identical value to generate the
3640 requisite code, though you may need to convert it to @code{unsigned
3641 char} to avoid sign-extension on hosts where @code{char} is signed.
3642 Each named token kind becomes a C macro in the parser implementation
3643 file, so @code{yylex} can use the name to stand for the code.  (This
3644 is why periods don't make sense in terminal symbols.)  @xref{Calling
3645 Convention}.
3647 If @code{yylex} is defined in a separate file, you need to arrange for the
3648 token-kind definitions to be available there.  Use the @option{-d} option
3649 when you run Bison, so that it will write these definitions into a separate
3650 header file @file{@var{name}.tab.h} which you can include in the other
3651 source files that need it.  @xref{Invocation}.
3653 If you want to write a grammar that is portable to any Standard C
3654 host, you must use only nonnull character tokens taken from the basic
3655 execution character set of Standard C@.  This set consists of the ten
3656 digits, the 52 lower- and upper-case English letters, and the
3657 characters in the following C-language string:
3659 @example
3660 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3661 @end example
3663 The @code{yylex} function and Bison must use a consistent character set
3664 and encoding for character tokens.  For example, if you run Bison in an
3665 ASCII environment, but then compile and run the resulting
3666 program in an environment that uses an incompatible character set like
3667 EBCDIC, the resulting program may not work because the tables
3668 generated by Bison will assume ASCII numeric values for
3669 character tokens.  It is standard practice for software distributions to
3670 contain C source files that were generated by Bison in an
3671 ASCII environment, so installers on platforms that are
3672 incompatible with ASCII must rebuild those files before
3673 compiling them.
3675 The symbol @code{error} is a terminal symbol reserved for error recovery
3676 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
3677 In particular, @code{yylex} should never return this value.  The default
3678 value of the error token is 256, unless you explicitly assigned 256 to
3679 one of your tokens with a @code{%token} declaration.
3681 @node Rules
3682 @section Grammar Rules
3684 A Bison grammar is a list of rules.
3686 @menu
3687 * Rules Syntax::   Syntax of the rules.
3688 * Empty Rules::    Symbols that can match the empty string.
3689 * Recursion::      Writing recursive rules.
3690 @end menu
3692 @node Rules Syntax
3693 @subsection Syntax of Grammar Rules
3694 @cindex rule syntax
3695 @cindex grammar rule syntax
3696 @cindex syntax of grammar rules
3698 A Bison grammar rule has the following general form:
3700 @example
3701 @var{result}: @var{components}@dots{};
3702 @end example
3704 @noindent
3705 where @var{result} is the nonterminal symbol that this rule describes,
3706 and @var{components} are various terminal and nonterminal symbols that
3707 are put together by this rule (@pxref{Symbols}).
3709 For example,
3711 @example
3712 exp: exp '+' exp;
3713 @end example
3715 @noindent
3716 says that two groupings of type @code{exp}, with a @samp{+} token in between,
3717 can be combined into a larger grouping of type @code{exp}.
3719 White space in rules is significant only to separate symbols.  You can add
3720 extra white space as you wish.
3722 Scattered among the components can be @var{actions} that determine
3723 the semantics of the rule.  An action looks like this:
3725 @example
3726 @{@var{C statements}@}
3727 @end example
3729 @noindent
3730 @cindex braced code
3731 This is an example of @dfn{braced code}, that is, C code surrounded by
3732 braces, much like a compound statement in C@.  Braced code can contain
3733 any sequence of C tokens, so long as its braces are balanced.  Bison
3734 does not check the braced code for correctness directly; it merely
3735 copies the code to the parser implementation file, where the C
3736 compiler can check it.
3738 Within braced code, the balanced-brace count is not affected by braces
3739 within comments, string literals, or character constants, but it is
3740 affected by the C digraphs @samp{<%} and @samp{%>} that represent
3741 braces.  At the top level braced code must be terminated by @samp{@}}
3742 and not by a digraph.  Bison does not look for trigraphs, so if braced
3743 code uses trigraphs you should ensure that they do not affect the
3744 nesting of braces or the boundaries of comments, string literals, or
3745 character constants.
3747 Usually there is only one action and it follows the components.
3748 @xref{Actions}.
3750 @findex |
3751 Multiple rules for the same @var{result} can be written separately or can
3752 be joined with the vertical-bar character @samp{|} as follows:
3754 @example
3755 @group
3756 @var{result}:
3757   @var{rule1-components}@dots{}
3758 | @var{rule2-components}@dots{}
3759 @dots{}
3761 @end group
3762 @end example
3764 @noindent
3765 They are still considered distinct rules even when joined in this way.
3767 @node Empty Rules
3768 @subsection Empty Rules
3769 @cindex empty rule
3770 @cindex rule, empty
3771 @findex %empty
3773 A rule is said to be @dfn{empty} if its right-hand side (@var{components})
3774 is empty.  It means that @var{result} in the previous example can match the
3775 empty string.  As another example, here is how to define an optional
3776 semicolon:
3778 @example
3779 semicolon.opt: | ";";
3780 @end example
3782 @noindent
3783 It is easy not to see an empty rule, especially when @code{|} is used.  The
3784 @code{%empty} directive allows to make explicit that a rule is empty on
3785 purpose:
3787 @example
3788 @group
3789 semicolon.opt:
3790   %empty
3791 | ";"
3793 @end group
3794 @end example
3796 Flagging a non-empty rule with @code{%empty} is an error.  If run with
3797 @option{-Wempty-rule}, @command{bison} will report empty rules without
3798 @code{%empty}.  Using @code{%empty} enables this warning, unless
3799 @option{-Wno-empty-rule} was specified.
3801 The @code{%empty} directive is a Bison extension, it does not work with
3802 Yacc.  To remain compatible with POSIX Yacc, it is customary to write a
3803 comment @samp{/* empty */} in each rule with no components:
3805 @example
3806 @group
3807 semicolon.opt:
3808   /* empty */
3809 | ";"
3811 @end group
3812 @end example
3815 @node Recursion
3816 @subsection Recursive Rules
3817 @cindex recursive rule
3818 @cindex rule, recursive
3820 A rule is called @dfn{recursive} when its @var{result} nonterminal
3821 appears also on its right hand side.  Nearly all Bison grammars need to
3822 use recursion, because that is the only way to define a sequence of any
3823 number of a particular thing.  Consider this recursive definition of a
3824 comma-separated sequence of one or more expressions:
3826 @example
3827 @group
3828 expseq1:
3829   exp
3830 | expseq1 ',' exp
3832 @end group
3833 @end example
3835 @cindex left recursion
3836 @cindex right recursion
3837 @noindent
3838 Since the recursive use of @code{expseq1} is the leftmost symbol in the
3839 right hand side, we call this @dfn{left recursion}.  By contrast, here
3840 the same construct is defined using @dfn{right recursion}:
3842 @example
3843 @group
3844 expseq1:
3845   exp
3846 | exp ',' expseq1
3848 @end group
3849 @end example
3851 @noindent
3852 Any kind of sequence can be defined using either left recursion or right
3853 recursion, but you should always use left recursion, because it can
3854 parse a sequence of any number of elements with bounded stack space.
3855 Right recursion uses up space on the Bison stack in proportion to the
3856 number of elements in the sequence, because all the elements must be
3857 shifted onto the stack before the rule can be applied even once.
3858 @xref{Algorithm}, for further explanation
3859 of this.
3861 @cindex mutual recursion
3862 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3863 rule does not appear directly on its right hand side, but does appear
3864 in rules for other nonterminals which do appear on its right hand
3865 side.
3867 For example:
3869 @example
3870 @group
3871 expr:
3872   primary
3873 | primary '+' primary
3875 @end group
3877 @group
3878 primary:
3879   constant
3880 | '(' expr ')'
3882 @end group
3883 @end example
3885 @noindent
3886 defines two mutually-recursive nonterminals, since each refers to the
3887 other.
3889 @node Semantics
3890 @section Defining Language Semantics
3891 @cindex defining language semantics
3892 @cindex language semantics, defining
3894 The grammar rules for a language determine only the syntax.  The semantics
3895 are determined by the semantic values associated with various tokens and
3896 groupings, and by the actions taken when various groupings are recognized.
3898 For example, the calculator calculates properly because the value
3899 associated with each expression is the proper number; it adds properly
3900 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3901 the numbers associated with @var{x} and @var{y}.
3903 @menu
3904 * Value Type::        Specifying one data type for all semantic values.
3905 * Multiple Types::    Specifying several alternative data types.
3906 * Type Generation::   Generating the semantic value type.
3907 * Union Decl::        Declaring the set of all semantic value types.
3908 * Structured Value Type::  Providing a structured semantic value type.
3909 * Actions::           An action is the semantic definition of a grammar rule.
3910 * Action Types::      Specifying data types for actions to operate on.
3911 * Midrule Actions::   Most actions go at the end of a rule.
3912                       This says when, why and how to use the exceptional
3913                         action in the middle of a rule.
3914 @end menu
3916 @node Value Type
3917 @subsection Data Types of Semantic Values
3918 @cindex semantic value type
3919 @cindex value type, semantic
3920 @cindex data types of semantic values
3921 @cindex default data type
3923 In a simple program it may be sufficient to use the same data type for
3924 the semantic values of all language constructs.  This was true in the
3925 RPN and infix calculator examples (@pxref{RPN Calc}).
3927 Bison normally uses the type @code{int} for semantic values if your program
3928 uses the same data type for all language constructs.  To specify some other
3929 type, define the @code{%define} variable @code{api.value.type} like this:
3931 @example
3932 %define api.value.type @{double@}
3933 @end example
3935 @noindent
3938 @example
3939 %define api.value.type @{struct semantic_value_type@}
3940 @end example
3942 The value of @code{api.value.type} should be a type name that does not
3943 contain parentheses or square brackets.
3945 Alternatively in C, instead of relying of Bison's @code{%define} support,
3946 you may rely on the C preprocessor and define @code{YYSTYPE} as a macro:
3948 @example
3949 #define YYSTYPE double
3950 @end example
3952 @noindent
3953 This macro definition must go in the prologue of the grammar file
3954 (@pxref{Grammar Outline}).  If compatibility with POSIX Yacc matters to you,
3955 use this.  Note however that Bison cannot know @code{YYSTYPE}'s value, not
3956 even whether it is defined, so there are services it cannot provide.
3957 Besides this works only for C.
3959 @node Multiple Types
3960 @subsection More Than One Value Type
3962 In most programs, you will need different data types for different kinds
3963 of tokens and groupings.  For example, a numeric constant may need type
3964 @code{int} or @code{long}, while a string constant needs type
3965 @code{char *}, and an identifier might need a pointer to an entry in the
3966 symbol table.
3968 To use more than one data type for semantic values in one parser, Bison
3969 requires you to do two things:
3971 @itemize @bullet
3972 @item
3973 Specify the entire collection of possible data types.  There are several
3974 options:
3975 @itemize @bullet
3976 @item
3977 let Bison compute the union type from the tags you assign to symbols;
3979 @item
3980 use the @code{%union} Bison declaration (@pxref{Union Decl});
3982 @item
3983 define the @code{%define} variable @code{api.value.type} to be a union type
3984 whose members are the type tags (@pxref{Structured Value Type});
3986 @item
3987 use a @code{typedef} or a @code{#define} to define @code{YYSTYPE} to be a
3988 union type whose member names are the type tags.
3989 @end itemize
3991 @item
3992 Choose one of those types for each symbol (terminal or nonterminal) for
3993 which semantic values are used.  This is done for tokens with the
3994 @code{%token} Bison declaration (@pxref{Token Decl}) and
3995 for groupings with the @code{%nterm}/@code{%type} Bison declarations
3996 (@pxref{Type Decl}).
3997 @end itemize
3999 @node Type Generation
4000 @subsection Generating the Semantic Value Type
4001 @cindex declaring value types
4002 @cindex value types, declaring
4003 @findex %define api.value.type union
4005 The special value @code{union} of the @code{%define} variable
4006 @code{api.value.type} instructs Bison that the type tags (used with the
4007 @code{%token}, @code{%nterm} and @code{%type} directives) are genuine types,
4008 not names of members of @code{YYSTYPE}.
4010 For example:
4012 @example
4013 %define api.value.type union
4014 %token <int> INT "integer"
4015 %token <int> 'n'
4016 %nterm <int> expr
4017 %token <char const *> ID "identifier"
4018 @end example
4020 @noindent
4021 generates an appropriate value of @code{YYSTYPE} to support each symbol
4022 type.  The name of the member of @code{YYSTYPE} for tokens than have a
4023 declared identifier @var{id} (such as @code{INT} and @code{ID} above, but
4024 not @code{'n'}) is @code{@var{id}}.  The other symbols have unspecified
4025 names on which you should not depend; instead, relying on C casts to access
4026 the semantic value with the appropriate type:
4028 @example
4029 /* For an "integer". */
4030 yylval.INT = 42;
4031 return INT;
4033 /* For an 'n', also declared as int. */
4034 *((int*)&yylval) = 42;
4035 return 'n';
4037 /* For an "identifier". */
4038 yylval.ID = "42";
4039 return ID;
4040 @end example
4042 If the @code{%define} variable @code{api.token.prefix} is defined
4043 (@pxref{%define Summary}), then it is also used to prefix
4044 the union member names.  For instance, with @samp{%define api.token.prefix
4045 @{TOK_@}}:
4047 @example
4048 /* For an "integer". */
4049 yylval.TOK_INT = 42;
4050 return TOK_INT;
4051 @end example
4053 This Bison extension cannot work if @code{%yacc} (or
4054 @option{-y}/@option{--yacc}) is enabled, as POSIX mandates that Yacc
4055 generate tokens as macros (e.g., @samp{#define INT 258}, or @samp{#define
4056 TOK_INT 258}).
4058 A similar feature is provided for C++ that in addition overcomes C++
4059 limitations (that forbid non-trivial objects to be part of a @code{union}):
4060 @samp{%define api.value.type variant}, see @ref{C++ Variants}.
4062 @node Union Decl
4063 @subsection The Union Declaration
4064 @cindex declaring value types
4065 @cindex value types, declaring
4066 @findex %union
4068 The @code{%union} declaration specifies the entire collection of possible
4069 data types for semantic values.  The keyword @code{%union} is followed by
4070 braced code containing the same thing that goes inside a @code{union} in C@.
4072 For example:
4074 @example
4075 @group
4076 %union @{
4077   double val;
4078   symrec *tptr;
4080 @end group
4081 @end example
4083 @noindent
4084 This says that the two alternative types are @code{double} and @code{symrec
4085 *}.  They are given names @code{val} and @code{tptr}; these names are used
4086 in the @code{%token}, @code{%nterm} and @code{%type} declarations to pick
4087 one of the types for a terminal or nonterminal symbol (@pxref{Type Decl}).
4089 As an extension to POSIX, a tag is allowed after the @code{%union}.  For
4090 example:
4092 @example
4093 @group
4094 %union value @{
4095   double val;
4096   symrec *tptr;
4098 @end group
4099 @end example
4101 @noindent
4102 specifies the union tag @code{value}, so the corresponding C type is
4103 @code{union value}.  If you do not specify a tag, it defaults to
4104 @code{YYSTYPE} (@pxref{%define Summary}).
4106 As another extension to POSIX, you may specify multiple @code{%union}
4107 declarations; their contents are concatenated.  However, only the first
4108 @code{%union} declaration can specify a tag.
4110 Note that, unlike making a @code{union} declaration in C, you need not write
4111 a semicolon after the closing brace.
4113 @node Structured Value Type
4114 @subsection Providing a Structured Semantic Value Type
4115 @cindex declaring value types
4116 @cindex value types, declaring
4117 @findex %union
4119 Instead of @code{%union}, you can define and use your own union type
4120 @code{YYSTYPE} if your grammar contains at least one @samp{<@var{type}>}
4121 tag.  For example, you can put the following into a header file
4122 @file{parser.h}:
4124 @example
4125 @group
4126 union YYSTYPE @{
4127   double val;
4128   symrec *tptr;
4130 @end group
4131 @end example
4133 @noindent
4134 and then your grammar can use the following instead of @code{%union}:
4136 @example
4137 @group
4139 #include "parser.h"
4141 %define api.value.type @{union YYSTYPE@}
4142 %nterm <val> expr
4143 %token <tptr> ID
4144 @end group
4145 @end example
4147 Actually, you may also provide a @code{struct} rather that a @code{union},
4148 which may be handy if you want to track information for every symbol (such
4149 as preceding comments).
4151 The type you provide may even be structured and include pointers, in which
4152 case the type tags you provide may be composite, with @samp{.} and @samp{->}
4153 operators.
4155 @node Actions
4156 @subsection Actions
4157 @cindex action
4158 @vindex $$
4159 @vindex $@var{n}
4160 @vindex $@var{name}
4161 @vindex $[@var{name}]
4163 An action accompanies a syntactic rule and contains C code to be executed
4164 each time an instance of that rule is recognized.  The task of most actions
4165 is to compute a semantic value for the grouping built by the rule from the
4166 semantic values associated with tokens or smaller groupings.
4168 An action consists of braced code containing C statements, and can be
4169 placed at any position in the rule;
4170 it is executed at that position.  Most rules have just one action at the
4171 end of the rule, following all the components.  Actions in the middle of
4172 a rule are tricky and used only for special purposes (@pxref{Midrule
4173 Actions}).
4175 The C code in an action can refer to the semantic values of the
4176 components matched by the rule with the construct @code{$@var{n}},
4177 which stands for the value of the @var{n}th component.  The semantic
4178 value for the grouping being constructed is @code{$$}.  In addition,
4179 the semantic values of symbols can be accessed with the named
4180 references construct @code{$@var{name}} or @code{$[@var{name}]}.
4181 Bison translates both of these constructs into expressions of the
4182 appropriate type when it copies the actions into the parser
4183 implementation file.  @code{$$} (or @code{$@var{name}}, when it stands
4184 for the current grouping) is translated to a modifiable lvalue, so it
4185 can be assigned to.
4187 Here is a typical example:
4189 @example
4190 @group
4191 exp:
4192 @dots{}
4193 | exp '+' exp     @{ $$ = $1 + $3; @}
4194 @end group
4195 @end example
4197 Or, in terms of named references:
4199 @example
4200 @group
4201 exp[result]:
4202 @dots{}
4203 | exp[left] '+' exp[right]  @{ $result = $left + $right; @}
4204 @end group
4205 @end example
4207 @noindent
4208 This rule constructs an @code{exp} from two smaller @code{exp} groupings
4209 connected by a plus-sign token.  In the action, @code{$1} and @code{$3}
4210 (@code{$left} and @code{$right})
4211 refer to the semantic values of the two component @code{exp} groupings,
4212 which are the first and third symbols on the right hand side of the rule.
4213 The sum is stored into @code{$$} (@code{$result}) so that it becomes the
4214 semantic value of
4215 the addition-expression just recognized by the rule.  If there were a
4216 useful semantic value associated with the @samp{+} token, it could be
4217 referred to as @code{$2}.
4219 @xref{Named References}, for more information about using the named
4220 references construct.
4222 Note that the vertical-bar character @samp{|} is really a rule
4223 separator, and actions are attached to a single rule.  This is a
4224 difference with tools like Flex, for which @samp{|} stands for either
4225 ``or'', or ``the same action as that of the next rule''.  In the
4226 following example, the action is triggered only when @samp{b} is found:
4228 @example
4229 a-or-b: 'a'|'b'   @{ a_or_b_found = 1; @};
4230 @end example
4232 @cindex default action
4233 If you don't specify an action for a rule, Bison supplies a default:
4234 @w{@code{$$ = $1}.}  Thus, the value of the first symbol in the rule
4235 becomes the value of the whole rule.  Of course, the default action is
4236 valid only if the two data types match.  There is no meaningful default
4237 action for an empty rule; every empty rule must have an explicit action
4238 unless the rule's value does not matter.
4240 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
4241 to tokens and groupings on the stack @emph{before} those that match the
4242 current rule.  This is a very risky practice, and to use it reliably
4243 you must be certain of the context in which the rule is applied.  Here
4244 is a case in which you can use this reliably:
4246 @example
4247 @group
4248 foo:
4249   expr bar '+' expr  @{ @dots{} @}
4250 | expr bar '-' expr  @{ @dots{} @}
4252 @end group
4254 @group
4255 bar:
4256   %empty    @{ previous_expr = $0; @}
4258 @end group
4259 @end example
4261 As long as @code{bar} is used only in the fashion shown here, @code{$0}
4262 always refers to the @code{expr} which precedes @code{bar} in the
4263 definition of @code{foo}.
4265 @vindex yylval
4266 It is also possible to access the semantic value of the lookahead token, if
4267 any, from a semantic action.
4268 This semantic value is stored in @code{yylval}.
4269 @xref{Action Features}.
4271 @node Action Types
4272 @subsection Data Types of Values in Actions
4273 @cindex action data types
4274 @cindex data types in actions
4276 If you have chosen a single data type for semantic values, the @code{$$}
4277 and @code{$@var{n}} constructs always have that data type.
4279 If you have used @code{%union} to specify a variety of data types, then you
4280 must declare a choice among these types for each terminal or nonterminal
4281 symbol that can have a semantic value.  Then each time you use @code{$$} or
4282 @code{$@var{n}}, its data type is determined by which symbol it refers to
4283 in the rule.  In this example,
4285 @example
4286 @group
4287 exp:
4288   @dots{}
4289 | exp '+' exp    @{ $$ = $1 + $3; @}
4290 @end group
4291 @end example
4293 @noindent
4294 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
4295 have the data type declared for the nonterminal symbol @code{exp}.  If
4296 @code{$2} were used, it would have the data type declared for the
4297 terminal symbol @code{'+'}, whatever that might be.
4299 Alternatively, you can specify the data type when you refer to the value,
4300 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
4301 reference.  For example, if you have defined types as shown here:
4303 @example
4304 @group
4305 %union @{
4306   int itype;
4307   double dtype;
4309 @end group
4310 @end example
4312 @noindent
4313 then you can write @code{$<itype>1} to refer to the first subunit of the
4314 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
4316 @node Midrule Actions
4317 @subsection Actions in Midrule
4318 @cindex actions in midrule
4319 @cindex midrule actions
4321 Occasionally it is useful to put an action in the middle of a rule.
4322 These actions are written just like usual end-of-rule actions, but they
4323 are executed before the parser even recognizes the following components.
4325 @menu
4326 * Using Midrule Actions::       Putting an action in the middle of a rule.
4327 * Typed Midrule Actions::       Specifying the semantic type of their values.
4328 * Midrule Action Translation::  How midrule actions are actually processed.
4329 * Midrule Conflicts::           Midrule actions can cause conflicts.
4330 @end menu
4332 @node Using Midrule Actions
4333 @subsubsection Using Midrule Actions
4335 A midrule action may refer to the components preceding it using
4336 @code{$@var{n}}, but it may not refer to subsequent components because
4337 it is run before they are parsed.
4339 The midrule action itself counts as one of the components of the rule.
4340 This makes a difference when there is another action later in the same rule
4341 (and usually there is another at the end): you have to count the actions
4342 along with the symbols when working out which number @var{n} to use in
4343 @code{$@var{n}}.
4345 The midrule action can also have a semantic value.  The action can set
4346 its value with an assignment to @code{$$}, and actions later in the rule
4347 can refer to the value using @code{$@var{n}}.  Since there is no symbol
4348 to name the action, there is no way to declare a data type for the value
4349 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
4350 specify a data type each time you refer to this value.
4352 There is no way to set the value of the entire rule with a midrule
4353 action, because assignments to @code{$$} do not have that effect.  The
4354 only way to set the value for the entire rule is with an ordinary action
4355 at the end of the rule.
4357 Here is an example from a hypothetical compiler, handling a @code{let}
4358 statement that looks like @samp{let (@var{variable}) @var{statement}} and
4359 serves to create a variable named @var{variable} temporarily for the
4360 duration of @var{statement}.  To parse this construct, we must put
4361 @var{variable} into the symbol table while @var{statement} is parsed, then
4362 remove it afterward.  Here is how it is done:
4364 @example
4365 @group
4366 stmt:
4367   "let" '(' var ')'
4368     @{
4369       $<context>$ = push_context ();
4370       declare_variable ($3);
4371     @}
4372   stmt
4373     @{
4374       $$ = $6;
4375       pop_context ($<context>5);
4376     @}
4377 @end group
4378 @end example
4380 @noindent
4381 As soon as @samp{let (@var{variable})} has been recognized, the first
4382 action is run.  It saves a copy of the current semantic context (the
4383 list of accessible variables) as its semantic value, using alternative
4384 @code{context} in the data-type union.  Then it calls
4385 @code{declare_variable} to add the new variable to that list.  Once the
4386 first action is finished, the embedded statement @code{stmt} can be
4387 parsed.
4389 Note that the midrule action is component number 5, so the @samp{stmt} is
4390 component number 6.  Named references can be used to improve the readability
4391 and maintainability (@pxref{Named References}):
4393 @example
4394 @group
4395 stmt:
4396   "let" '(' var ')'
4397     @{
4398       $<context>let = push_context ();
4399       declare_variable ($3);
4400     @}[let]
4401   stmt
4402     @{
4403       $$ = $6;
4404       pop_context ($<context>let);
4405     @}
4406 @end group
4407 @end example
4409 After the embedded statement is parsed, its semantic value becomes the
4410 value of the entire @code{let}-statement.  Then the semantic value from the
4411 earlier action is used to restore the prior list of variables.  This
4412 removes the temporary @code{let}-variable from the list so that it won't
4413 appear to exist while the rest of the program is parsed.
4415 Because the types of the semantic values of midrule actions are unknown to
4416 Bison, type-based features (e.g., @samp{%printer}, @samp{%destructor}) do
4417 not work, which could result in memory leaks.  They also forbid the use of
4418 the @code{variant} implementation of the @code{api.value.type} in C++
4419 (@pxref{C++ Variants}).
4421 @xref{Typed Midrule Actions}, for one way to address this issue, and
4422 @ref{Midrule Action Translation}, for another: turning mid-action actions
4423 into regular actions.
4426 @node Typed Midrule Actions
4427 @subsubsection Typed Midrule Actions
4429 @findex %destructor
4430 @cindex discarded symbols, midrule actions
4431 @cindex error recovery, midrule actions
4432 In the above example, if the parser initiates error recovery (@pxref{Error
4433 Recovery}) while parsing the tokens in the embedded statement @code{stmt},
4434 it might discard the previous semantic context @code{$<context>5} without
4435 restoring it.  Thus, @code{$<context>5} needs a destructor
4436 (@pxref{Destructor Decl}), and Bison needs the
4437 type of the semantic value (@code{context}) to select the right destructor.
4439 As an extension to Yacc's midrule actions, Bison offers a means to type
4440 their semantic value: specify its type tag (@samp{<...>} before the midrule
4441 action.
4443 Consider the previous example, with an untyped midrule action:
4445 @example
4446 @group
4447 stmt:
4448   "let" '(' var ')'
4449     @{
4450       $<context>$ = push_context (); // ***
4451       declare_variable ($3);
4452     @}
4453   stmt
4454     @{
4455       $$ = $6;
4456       pop_context ($<context>5);     // ***
4457     @}
4458 @end group
4459 @end example
4461 @noindent
4462 If instead you write:
4464 @example
4465 @group
4466 stmt:
4467   "let" '(' var ')'
4468     <context>@{                       // ***
4469       $$ = push_context ();          // ***
4470       declare_variable ($3);
4471     @}
4472   stmt
4473     @{
4474       $$ = $6;
4475       pop_context ($5);              // ***
4476     @}
4477 @end group
4478 @end example
4480 @noindent
4481 then @code{%printer} and @code{%destructor} work properly (no more leaks!),
4482 C++ @code{variant}s can be used, and redundancy is reduced (@code{<context>}
4483 is specified once).
4486 @node Midrule Action Translation
4487 @subsubsection Midrule Action Translation
4488 @vindex $@@@var{n}
4489 @vindex @@@var{n}
4491 Midrule actions are actually transformed into regular rules and actions.
4492 The various reports generated by Bison (textual, graphical, etc., see
4493 @ref{Understanding}) reveal this translation,
4494 best explained by means of an example.  The following rule:
4496 @example
4497 exp: @{ a(); @} "b" @{ c(); @} @{ d(); @} "e" @{ f(); @};
4498 @end example
4500 @noindent
4501 is translated into:
4503 @example
4504 $@@1: %empty @{ a(); @};
4505 $@@2: %empty @{ c(); @};
4506 $@@3: %empty @{ d(); @};
4507 exp: $@@1 "b" $@@2 $@@3 "e" @{ f(); @};
4508 @end example
4510 @noindent
4511 with new nonterminal symbols @code{$@@@var{n}}, where @var{n} is a number.
4513 A midrule action is expected to generate a value if it uses @code{$$}, or
4514 the (final) action uses @code{$@var{n}} where @var{n} denote the midrule
4515 action.  In that case its nonterminal is rather named @code{@@@var{n}}:
4517 @example
4518 exp: @{ a(); @} "b" @{ $$ = c(); @} @{ d(); @} "e" @{ f = $1; @};
4519 @end example
4521 @noindent
4522 is translated into
4524 @example
4525 @@1: %empty @{ a(); @};
4526 @@2: %empty @{ $$ = c(); @};
4527 $@@3: %empty @{ d(); @};
4528 exp: @@1 "b" @@2 $@@3 "e" @{ f = $1; @}
4529 @end example
4531 There are probably two errors in the above example: the first midrule action
4532 does not generate a value (it does not use @code{$$} although the final
4533 action uses it), and the value of the second one is not used (the final
4534 action does not use @code{$3}).  Bison reports these errors when the
4535 @code{midrule-value} warnings are enabled (@pxref{Invocation}):
4537 @example
4538 $ @kbd{bison -Wmidrule-value mid.y}
4539 @group
4540 mid.y:2.6-13: @dwarning{warning}: unset value: $$
4541     2 | exp: @dwarning{@{ a(); @}} "b" @{ $$ = c(); @} @{ d(); @} "e" @{ f = $1; @};
4542       |      @dwarning{^~~~~~~~}
4543 @end group
4544 @group
4545 mid.y:2.19-31: @dwarning{warning}: unused value: $3
4546     2 | exp: @{ a(); @} "b" @dwarning{@{ $$ = c(); @}} @{ d(); @} "e" @{ f = $1; @};
4547       |                   @dwarning{^~~~~~~~~~~~~}
4548 @end group
4549 @end example
4551 @sp 1
4553 It is sometimes useful to turn midrule actions into regular actions, e.g.,
4554 to factor them, or to escape from their limitations.  For instance, as an
4555 alternative to @emph{typed} midrule action, you may bury the midrule action
4556 inside a nonterminal symbol and to declare a printer and a destructor for
4557 that symbol:
4559 @example
4560 @group
4561 %nterm <context> let
4562 %destructor @{ pop_context ($$); @} let
4563 %printer @{ print_context (yyo, $$); @} let
4564 @end group
4568 @group
4569 stmt:
4570   let stmt
4571     @{
4572       $$ = $2;
4573       pop_context ($let);
4574     @};
4575 @end group
4577 @group
4578 let:
4579   "let" '(' var ')'
4580     @{
4581       $let = push_context ();
4582       declare_variable ($var);
4583     @};
4585 @end group
4586 @end example
4591 @node Midrule Conflicts
4592 @subsubsection Conflicts due to Midrule Actions
4593 Taking action before a rule is completely recognized often leads to
4594 conflicts since the parser must commit to a parse in order to execute the
4595 action.  For example, the following two rules, without midrule actions,
4596 can coexist in a working parser because the parser can shift the open-brace
4597 token and look at what follows before deciding whether there is a
4598 declaration or not:
4600 @example
4601 @group
4602 compound:
4603   '@{' declarations statements '@}'
4604 | '@{' statements '@}'
4606 @end group
4607 @end example
4609 @noindent
4610 But when we add a midrule action as follows, the rules become nonfunctional:
4612 @example
4613 @group
4614 compound:
4615   @{ prepare_for_local_variables (); @}
4616      '@{' declarations statements '@}'
4617 @end group
4618 @group
4619 |    '@{' statements '@}'
4621 @end group
4622 @end example
4624 @noindent
4625 Now the parser is forced to decide whether to run the midrule action
4626 when it has read no farther than the open-brace.  In other words, it
4627 must commit to using one rule or the other, without sufficient
4628 information to do it correctly.  (The open-brace token is what is called
4629 the @dfn{lookahead} token at this time, since the parser is still
4630 deciding what to do about it.  @xref{Lookahead}.)
4632 You might think that you could correct the problem by putting identical
4633 actions into the two rules, like this:
4635 @example
4636 @group
4637 compound:
4638   @{ prepare_for_local_variables (); @}
4639     '@{' declarations statements '@}'
4640 | @{ prepare_for_local_variables (); @}
4641     '@{' statements '@}'
4643 @end group
4644 @end example
4646 @noindent
4647 But this does not help, because Bison does not realize that the two actions
4648 are identical.  (Bison never tries to understand the C code in an action.)
4650 If the grammar is such that a declaration can be distinguished from a
4651 statement by the first token (which is true in C), then one solution which
4652 does work is to put the action after the open-brace, like this:
4654 @example
4655 @group
4656 compound:
4657   '@{' @{ prepare_for_local_variables (); @}
4658     declarations statements '@}'
4659 | '@{' statements '@}'
4661 @end group
4662 @end example
4664 @noindent
4665 Now the first token of the following declaration or statement,
4666 which would in any case tell Bison which rule to use, can still do so.
4668 Another solution is to bury the action inside a nonterminal symbol which
4669 serves as a subroutine:
4671 @example
4672 @group
4673 subroutine:
4674   %empty  @{ prepare_for_local_variables (); @}
4676 @end group
4678 @group
4679 compound:
4680   subroutine '@{' declarations statements '@}'
4681 | subroutine '@{' statements '@}'
4683 @end group
4684 @end example
4686 @noindent
4687 Now Bison can execute the action in the rule for @code{subroutine} without
4688 deciding which rule for @code{compound} it will eventually use.
4691 @node Tracking Locations
4692 @section Tracking Locations
4693 @cindex location
4694 @cindex textual location
4695 @cindex location, textual
4697 Though grammar rules and semantic actions are enough to write a fully
4698 functional parser, it can be useful to process some additional information,
4699 especially symbol locations.
4701 The way locations are handled is defined by providing a data type, and
4702 actions to take when rules are matched.
4704 @menu
4705 * Location Type::               Specifying a data type for locations.
4706 * Actions and Locations::       Using locations in actions.
4707 * Printing Locations::          Defining how locations are printed.
4708 * Location Default Action::     Defining a general way to compute locations.
4709 @end menu
4711 @node Location Type
4712 @subsection Data Type of Locations
4713 @cindex data type of locations
4714 @cindex default location type
4716 Defining a data type for locations is much simpler than for semantic values,
4717 since all tokens and groupings always use the same type.  The location type
4718 is specified using @samp{%define api.location.type}:
4720 @example
4721 %define api.location.type @{location_t@}
4722 @end example
4724 This defines, in the C generated code, the @code{YYLTYPE} type name.  When
4725 @code{YYLTYPE} is not defined, Bison uses a default structure type with four
4726 members:
4728 @example
4729 typedef struct YYLTYPE
4731   int first_line;
4732   int first_column;
4733   int last_line;
4734   int last_column;
4735 @} YYLTYPE;
4736 @end example
4738 In C, you may also specify the type of locations by defining a macro called
4739 @code{YYLTYPE}, just as you can specify the semantic value type by defining
4740 a @code{YYSTYPE} macro (@pxref{Value Type}).  However, rather than using
4741 macros, we recommend the @code{api.value.type} and @code{api.location.type}
4742 @code{%define} variables.
4744 Default locations represent a range in the source file(s), but this is not a
4745 requirement.  It could be a single point or just a line number, or even more
4746 complex structures.
4748 When the default location type is used, Bison initializes all these fields
4749 to 1 for @code{yylloc} at the beginning of the parsing.  To initialize
4750 @code{yylloc} with a custom location type (or to chose a different
4751 initialization), use the @code{%initial-action} directive.  @xref{Initial
4752 Action Decl}.
4755 @node Actions and Locations
4756 @subsection Actions and Locations
4757 @cindex location actions
4758 @cindex actions, location
4759 @vindex @@$
4760 @vindex @@@var{n}
4761 @vindex @@@var{name}
4762 @vindex @@[@var{name}]
4764 Actions are not only useful for defining language semantics, but also for
4765 describing the behavior of the output parser with locations.
4767 The most obvious way for building locations of syntactic groupings is very
4768 similar to the way semantic values are computed.  In a given rule, several
4769 constructs can be used to access the locations of the elements being matched.
4770 The location of the @var{n}th component of the right hand side is
4771 @code{@@@var{n}}, while the location of the left hand side grouping is
4772 @code{@@$}.
4774 In addition, the named references construct @code{@@@var{name}} and
4775 @code{@@[@var{name}]} may also be used to address the symbol locations.
4776 @xref{Named References}, for more information about using the named
4777 references construct.
4779 Here is a basic example using the default data type for locations:
4781 @example
4782 @group
4783 exp:
4784   @dots{}
4785 | exp '/' exp
4786     @{
4787       @@$.first_column = @@1.first_column;
4788       @@$.first_line = @@1.first_line;
4789       @@$.last_column = @@3.last_column;
4790       @@$.last_line = @@3.last_line;
4791       if ($3)
4792         $$ = $1 / $3;
4793       else
4794         @{
4795           $$ = 1;
4796           fprintf (stderr, "%d.%d-%d.%d: division by zero",
4797                    @@3.first_line, @@3.first_column,
4798                    @@3.last_line, @@3.last_column);
4799         @}
4800     @}
4801 @end group
4802 @end example
4804 As for semantic values, there is a default action for locations that is
4805 run each time a rule is matched.  It sets the beginning of @code{@@$} to the
4806 beginning of the first symbol, and the end of @code{@@$} to the end of the
4807 last symbol.
4809 With this default action, the location tracking can be fully automatic.  The
4810 example above simply rewrites this way:
4812 @example
4813 @group
4814 exp:
4815   @dots{}
4816 | exp '/' exp
4817     @{
4818       if ($3)
4819         $$ = $1 / $3;
4820       else
4821         @{
4822           $$ = 1;
4823           fprintf (stderr, "%d.%d-%d.%d: division by zero",
4824                    @@3.first_line, @@3.first_column,
4825                    @@3.last_line, @@3.last_column);
4826         @}
4827     @}
4828 @end group
4829 @end example
4831 @vindex yylloc
4832 It is also possible to access the location of the lookahead token, if any,
4833 from a semantic action.
4834 This location is stored in @code{yylloc}.
4835 @xref{Action Features}.
4837 @node Printing Locations
4838 @subsection Printing Locations
4839 @vindex YYLOCATION_PRINT
4841 When using the default location type, the debug traces report the symbols'
4842 location.  The generated parser does so using the @code{YYLOCATION_PRINT}
4843 macro.
4845 @deffn {Macro} YYLOCATION_PRINT (@var{file}, @var{loc})@code{;}
4846 When traces are enabled, print @var{loc} (of type @samp{YYLTYPE const *}) on
4847 @var{file} (of type @samp{FILE *}).  Do nothing when traces are disabled, or
4848 if the location type is user defined.
4849 @end deffn
4851 To get locations in the debug traces with your user-defined location types,
4852 define the @code{YYLOCATION_PRINT} macro.  For instance:
4854 @example
4855 #define YYLOCATION_PRINT   location_print
4856 @end example
4860 @node Location Default Action
4861 @subsection Default Action for Locations
4862 @vindex YYLLOC_DEFAULT
4863 @cindex GLR parsers and @code{YYLLOC_DEFAULT}
4865 Actually, actions are not the best place to compute locations.  Since
4866 locations are much more general than semantic values, there is room in
4867 the output parser to redefine the default action to take for each
4868 rule.  The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
4869 matched, before the associated action is run.  It is also invoked
4870 while processing a syntax error, to compute the error's location.
4871 Before reporting an unresolvable syntactic ambiguity, a GLR
4872 parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
4873 of that ambiguity.
4875 Most of the time, this macro is general enough to suppress location
4876 dedicated code from semantic actions.
4878 The @code{YYLLOC_DEFAULT} macro takes three parameters.  The first one is
4879 the location of the grouping (the result of the computation).  When a
4880 rule is matched, the second parameter identifies locations of
4881 all right hand side elements of the rule being matched, and the third
4882 parameter is the size of the rule's right hand side.
4883 When a GLR parser reports an ambiguity, which of multiple candidate
4884 right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
4885 When processing a syntax error, the second parameter identifies locations
4886 of the symbols that were discarded during error processing, and the third
4887 parameter is the number of discarded symbols.
4889 By default, @code{YYLLOC_DEFAULT} is defined this way:
4891 @example
4892 @group
4893 # define YYLLOC_DEFAULT(Cur, Rhs, N)                      \
4894 do                                                        \
4895   if (N)                                                  \
4896     @{                                                     \
4897       (Cur).first_line   = YYRHSLOC(Rhs, 1).first_line;   \
4898       (Cur).first_column = YYRHSLOC(Rhs, 1).first_column; \
4899       (Cur).last_line    = YYRHSLOC(Rhs, N).last_line;    \
4900       (Cur).last_column  = YYRHSLOC(Rhs, N).last_column;  \
4901     @}                                                     \
4902   else                                                    \
4903     @{                                                     \
4904       (Cur).first_line   = (Cur).last_line   =            \
4905         YYRHSLOC(Rhs, 0).last_line;                       \
4906       (Cur).first_column = (Cur).last_column =            \
4907         YYRHSLOC(Rhs, 0).last_column;                     \
4908     @}                                                     \
4909 while (0)
4910 @end group
4911 @end example
4913 @noindent
4914 where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
4915 in @var{rhs} when @var{k} is positive, and the location of the symbol
4916 just before the reduction when @var{k} and @var{n} are both zero.
4918 When defining @code{YYLLOC_DEFAULT}, you should consider that:
4920 @itemize @bullet
4921 @item
4922 All arguments are free of side-effects.  However, only the first one (the
4923 result) should be modified by @code{YYLLOC_DEFAULT}.
4925 @item
4926 For consistency with semantic actions, valid indexes within the
4927 right hand side range from 1 to @var{n}.  When @var{n} is zero, only 0 is a
4928 valid index, and it refers to the symbol just before the reduction.
4929 During error processing @var{n} is always positive.
4931 @item
4932 Your macro should parenthesize its arguments, if need be, since the
4933 actual arguments may not be surrounded by parentheses.  Also, your
4934 macro should expand to something that can be used as a single
4935 statement when it is followed by a semicolon.
4936 @end itemize
4938 @node Named References
4939 @section Named References
4940 @cindex named references
4942 As described in the preceding sections, the traditional way to refer to any
4943 semantic value or location is a @dfn{positional reference}, which takes the
4944 form @code{$@var{n}}, @code{$$}, @code{@@@var{n}}, and @code{@@$}.  However,
4945 such a reference is not very descriptive.  Moreover, if you later decide to
4946 insert or remove symbols in the right-hand side of a grammar rule, the need
4947 to renumber such references can be tedious and error-prone.
4949 To avoid these issues, you can also refer to a semantic value or location
4950 using a @dfn{named reference}.  First of all, original symbol names may be
4951 used as named references.  For example:
4953 @example
4954 @group
4955 invocation: op '(' args ')'
4956   @{ $invocation = new_invocation ($op, $args, @@invocation); @}
4957 @end group
4958 @end example
4960 @noindent
4961 Positional and named references can be mixed arbitrarily.  For example:
4963 @example
4964 @group
4965 invocation: op '(' args ')'
4966   @{ $$ = new_invocation ($op, $args, @@$); @}
4967 @end group
4968 @end example
4970 @noindent
4971 However, sometimes regular symbol names are not sufficient due to
4972 ambiguities:
4974 @example
4975 @group
4976 exp: exp '/' exp
4977   @{ $exp = $exp / $exp; @} // $exp is ambiguous.
4979 exp: exp '/' exp
4980   @{ $$ = $1 / $exp; @} // One usage is ambiguous.
4982 exp: exp '/' exp
4983   @{ $$ = $1 / $3; @} // No error.
4984 @end group
4985 @end example
4987 @noindent
4988 When ambiguity occurs, explicitly declared names may be used for values and
4989 locations.  Explicit names are declared as a bracketed name after a symbol
4990 appearance in rule definitions.  For example:
4991 @example
4992 @group
4993 exp[result]: exp[left] '/' exp[right]
4994   @{ $result = $left / $right; @}
4995 @end group
4996 @end example
4998 @noindent
4999 In order to access a semantic value generated by a midrule action, an
5000 explicit name may also be declared by putting a bracketed name after the
5001 closing brace of the midrule action code:
5002 @example
5003 @group
5004 exp[res]: exp[x] '+' @{$left = $x;@}[left] exp[right]
5005   @{ $res = $left + $right; @}
5006 @end group
5007 @end example
5009 @noindent
5011 In references, in order to specify names containing dots and dashes, an explicit
5012 bracketed syntax @code{$[name]} and @code{@@[name]} must be used:
5013 @example
5014 @group
5015 if-stmt: "if" '(' expr ')' "then" then.stmt ';'
5016   @{ $[if-stmt] = new_if_stmt ($expr, $[then.stmt]); @}
5017 @end group
5018 @end example
5020 It often happens that named references are followed by a dot, dash or other
5021 C punctuation marks and operators.  By default, Bison will read
5022 @samp{$name.suffix} as a reference to symbol value @code{$name} followed by
5023 @samp{.suffix}, i.e., an access to the @code{suffix} field of the semantic
5024 value.  In order to force Bison to recognize @samp{name.suffix} in its
5025 entirety as the name of a semantic value, the bracketed syntax
5026 @samp{$[name.suffix]} must be used.
5028 @node Declarations
5029 @section Bison Declarations
5030 @cindex declarations, Bison
5031 @cindex Bison declarations
5033 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
5034 used in formulating the grammar and the data types of semantic values.
5035 @xref{Symbols}.
5037 All token kind names (but not single-character literal tokens such as
5038 @code{'+'} and @code{'*'}) must be declared.  Nonterminal symbols must be
5039 declared if you need to specify which data type to use for the semantic
5040 value (@pxref{Multiple Types}).
5042 The first rule in the grammar file also specifies the start symbol, by
5043 default.  If you want some other symbol to be the start symbol, you
5044 must declare it explicitly (@pxref{Language and Grammar}).
5046 @menu
5047 * Require Decl::      Requiring a Bison version.
5048 * Token Decl::        Declaring terminal symbols.
5049 * Precedence Decl::   Declaring terminals with precedence and associativity.
5050 * Type Decl::         Declaring the choice of type for a nonterminal symbol.
5051 * Symbol Decls::      Summary of the Syntax of Symbol Declarations.
5052 * Initial Action Decl::  Code run before parsing starts.
5053 * Destructor Decl::   Declaring how symbols are freed.
5054 * Printer Decl::      Declaring how symbol values are displayed.
5055 * Expect Decl::       Suppressing warnings about parsing conflicts.
5056 * Start Decl::        Specifying the start symbol.
5057 * Pure Decl::         Requesting a reentrant parser.
5058 * Push Decl::         Requesting a push parser.
5059 * Decl Summary::      Table of all Bison declarations.
5060 * %define Summary::   Defining variables to adjust Bison's behavior.
5061 * %code Summary::     Inserting code into the parser source.
5062 @end menu
5064 @node Require Decl
5065 @subsection Require a Version of Bison
5066 @cindex version requirement
5067 @cindex requiring a version of Bison
5068 @findex %require
5070 You may require the minimum version of Bison to process the grammar.  If
5071 the requirement is not met, @command{bison} exits with an error (exit
5072 status 63).
5074 @example
5075 %require "@var{version}"
5076 @end example
5078 Some deprecated behaviors are disabled for some required @var{version}:
5079 @table @asis
5080 @item @code{"3.2"} (or better)
5081 The C++ deprecated files @file{position.hh} and @file{stack.hh} are no
5082 longer generated.
5083 @end table
5086 @node Token Decl
5087 @subsection Token Kind Names
5088 @cindex declaring token kind names
5089 @cindex token kind names, declaring
5090 @cindex declaring literal string tokens
5091 @findex %token
5093 The basic way to declare a token kind name (terminal symbol) is as follows:
5095 @example
5096 %token @var{name}
5097 @end example
5099 Bison will convert this into a definition in the parser, so that the
5100 function @code{yylex} (if it is in this file) can use the name @var{name} to
5101 stand for this token kind's code.
5103 Alternatively, you can use @code{%left}, @code{%right}, @code{%precedence},
5104 or @code{%nonassoc} instead of @code{%token}, if you wish to specify
5105 associativity and precedence.  @xref{Precedence Decl}.  However, for
5106 clarity, we recommend to use these directives only to declare associativity
5107 and precedence, and not to add string aliases, semantic types, etc.
5109 You can explicitly specify the numeric code for a token kind by appending a
5110 nonnegative decimal or hexadecimal integer value in the field immediately
5111 following the token name:
5113 @example
5114 %token NUM 300
5115 %token XNUM 0x12d // a GNU extension
5116 @end example
5118 @noindent
5119 It is generally best, however, to let Bison choose the numeric codes for all
5120 token kinds.  Bison will automatically select codes that don't conflict with
5121 each other or with normal characters.
5123 In the event that the stack type is a union, you must augment the
5124 @code{%token} or other token declaration to include the data type
5125 alternative delimited by angle-brackets (@pxref{Multiple Types}).
5127 For example:
5129 @example
5130 @group
5131 %union @{              /* define stack type */
5132   double val;
5133   symrec *tptr;
5135 %token <val> NUM      /* define token NUM and its type */
5136 @end group
5137 @end example
5139 You can associate a literal string token with a token kind name by writing
5140 the literal string at the end of a @code{%token} declaration which declares
5141 the name.  For example:
5143 @example
5144 %token ARROW "=>"
5145 @end example
5147 @noindent
5148 For example, a grammar for the C language might specify these names with
5149 equivalent literal string tokens:
5151 @example
5152 %token  <operator>  OR      "||"
5153 %token  <operator>  LE 134  "<="
5154 %left  OR  "<="
5155 @end example
5157 @noindent
5158 Once you equate the literal string and the token kind name, you can use them
5159 interchangeably in further declarations or the grammar rules.  The
5160 @code{yylex} function can use the token name or the literal string to obtain
5161 the token kind code (@pxref{Calling Convention}).
5163 String aliases allow for better error messages using the literal strings
5164 instead of the token names, such as @samp{syntax error, unexpected ||,
5165 expecting number or (} rather than @samp{syntax error, unexpected OR,
5166 expecting NUM or LPAREN}.
5168 String aliases may also be marked for internationalization (@pxref{Token
5169 I18n}):
5171 @example
5172 %token
5173     OR     "||"
5174     LPAREN "("
5175     RPAREN ")"
5176     '\n'   _("end of line")
5177   <double>
5178     NUM    _("number")
5179 @end example
5181 @noindent
5182 would produce in French @samp{erreur de syntaxe, || inattendu, attendait
5183 nombre ou (} rather than @samp{erreur de syntaxe, || inattendu, attendait
5184 number ou (}.
5186 @node Precedence Decl
5187 @subsection Operator Precedence
5188 @cindex precedence declarations
5189 @cindex declaring operator precedence
5190 @cindex operator precedence, declaring
5192 Use the @code{%left}, @code{%right}, @code{%nonassoc}, or @code{%precedence}
5193 declaration to declare a token and specify its precedence and associativity,
5194 all at once.  These are called @dfn{precedence declarations}.
5195 @xref{Precedence}, for general information on operator
5196 precedence.
5198 The syntax of a precedence declaration is nearly the same as that of
5199 @code{%token}: either
5201 @example
5202 %left @var{symbols}@dots{}
5203 @end example
5205 @noindent
5208 @example
5209 %left <@var{type}> @var{symbols}@dots{}
5210 @end example
5212 And indeed any of these declarations serves the purposes of @code{%token}.
5213 But in addition, they specify the associativity and relative precedence for
5214 all the @var{symbols}:
5216 @itemize @bullet
5217 @item
5218 The associativity of an operator @var{op} determines how repeated uses of
5219 the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op} @var{z}}
5220 is parsed by grouping @var{x} with @var{y} first or by grouping @var{y} with
5221 @var{z} first.  @code{%left} specifies left-associativity (grouping @var{x}
5222 with @var{y} first) and @code{%right} specifies right-associativity
5223 (grouping @var{y} with @var{z} first).  @code{%nonassoc} specifies no
5224 associativity, which means that @samp{@var{x} @var{op} @var{y} @var{op}
5225 @var{z}} is considered a syntax error.
5227 @code{%precedence} gives only precedence to the @var{symbols}, and defines
5228 no associativity at all.  Use this to define precedence only, and leave any
5229 potential conflict due to associativity enabled.
5231 @item
5232 The precedence of an operator determines how it nests with other operators.
5233 All the tokens declared in a single precedence declaration have equal
5234 precedence and nest together according to their associativity.  When two
5235 tokens declared in different precedence declarations associate, the one
5236 declared later has the higher precedence and is grouped first.
5237 @end itemize
5239 For backward compatibility, there is a confusing difference between the
5240 argument lists of @code{%token} and precedence declarations.  Only a
5241 @code{%token} can associate a literal string with a token kind name.  A
5242 precedence declaration always interprets a literal string as a reference to
5243 a separate token.  For example:
5245 @example
5246 %left  OR "<="         // Does not declare an alias.
5247 %left  OR 134 "<=" 135 // Declares 134 for OR and 135 for "<=".
5248 @end example
5250 @node Type Decl
5251 @subsection Nonterminal Symbols
5252 @cindex declaring value types, nonterminals
5253 @cindex value types, nonterminals, declaring
5254 @findex %nterm
5255 @findex %type
5257 @noindent
5258 When you use @code{%union} to specify multiple value types, you must
5259 declare the value type of each nonterminal symbol for which values are
5260 used.  This is done with a @code{%type} declaration, like this:
5262 @example
5263 %type <@var{type}> @var{nonterminal}@dots{}
5264 @end example
5266 @noindent
5267 Here @var{nonterminal} is the name of a nonterminal symbol, and @var{type}
5268 is the name given in the @code{%union} to the alternative that you want
5269 (@pxref{Union Decl}).  You can give any number of nonterminal symbols in the
5270 same @code{%type} declaration, if they have the same value type.  Use spaces
5271 to separate the symbol names.
5273 While POSIX Yacc allows @code{%type} only for nonterminals, Bison accepts
5274 that this directive be also applied to terminal symbols.  To declare
5275 exclusively nonterminal symbols, use the safer @code{%nterm}:
5277 @example
5278 %nterm <@var{type}> @var{nonterminal}@dots{}
5279 @end example
5282 @node Symbol Decls
5283 @subsection Syntax of Symbol Declarations
5284 @findex %left
5285 @findex %nterm
5286 @findex %token
5287 @findex %type
5289 The syntax of the various directives to declare symbols is as follows.
5291 @example
5292 %token @var{tag}? ( @var{id} @var{number}? @var{string}? )+ ( @var{tag} ( @var{id} @var{number}? @var{string}? )+ )*
5293 %left  @var{tag}? ( @var{id} @var{number}?)+ ( @var{tag} ( @var{id} @var{number}? )+ )*
5294 %type  @var{tag}? ( @var{id} | @var{char} | @var{string} )+ ( @var{tag} ( @var{id} | @var{char} | @var{string} )+ )*
5295 %nterm @var{tag}? @var{id}+ ( @var{tag} @var{id}+ )*
5296 @end example
5298 @noindent
5299 where @var{tag} denotes a type tag such as @samp{<ival>}, @var{id} denotes
5300 an identifier such as @samp{NUM}, @var{number} a decimal or hexadecimal
5301 integer such as @samp{300} or @samp{0x12d}, @var{char} a character literal
5302 such as @samp{'+'}, and @var{string} a string literal such as
5303 @samp{"number"}.  The postfix quantifiers are @samp{?} (zero or one),
5304 @samp{*} (zero or more) and @samp{+} (one or more).
5306 The directives @code{%precedence}, @code{%right} and @code{%nonassoc} behave
5307 like @code{%left}.
5309 @node Initial Action Decl
5310 @subsection Performing Actions before Parsing
5311 @findex %initial-action
5313 Sometimes your parser needs to perform some initializations before parsing.
5314 The @code{%initial-action} directive allows for such arbitrary code.
5316 @deffn {Directive} %initial-action @{ @var{code} @}
5317 @findex %initial-action
5318 Declare that the braced @var{code} must be invoked before parsing each time
5319 @code{yyparse} is called.  The @var{code} may use @code{$$} (or
5320 @code{$<@var{tag}>$}) and @code{@@$} --- initial value and location of the
5321 lookahead --- and the @code{%parse-param}.
5322 @end deffn
5324 For instance, if your locations use a file name, you may use
5326 @example
5327 %parse-param @{ char const *file_name @};
5328 %initial-action
5330   @@$.initialize (file_name);
5332 @end example
5335 @node Destructor Decl
5336 @subsection Freeing Discarded Symbols
5337 @cindex freeing discarded symbols
5338 @findex %destructor
5339 @findex <*>
5340 @findex <>
5341 During error recovery (@pxref{Error Recovery}), symbols already pushed on
5342 the stack and tokens coming from the rest of the file are discarded until
5343 the parser falls on its feet.  If the parser runs out of memory, or if it
5344 returns via @code{YYABORT}, @code{YYACCEPT} or @code{YYNOMEM}, all the
5345 symbols on the stack must be discarded.  Even if the parser succeeds, it
5346 must discard the start symbol.
5348 When discarded symbols convey heap based information, this memory is
5349 lost.  While this behavior can be tolerable for batch parsers, such as
5350 in traditional compilers, it is unacceptable for programs like shells or
5351 protocol implementations that may parse and execute indefinitely.
5353 The @code{%destructor} directive defines code that is called when a
5354 symbol is automatically discarded.
5356 @deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
5357 @findex %destructor
5358 Invoke the braced @var{code} whenever the parser discards one of the
5359 @var{symbols}.  Within @var{code}, @code{$$} (or @code{$<@var{tag}>$})
5360 designates the semantic value associated with the discarded symbol, and
5361 @code{@@$} designates its location.  The additional parser parameters are
5362 also available (@pxref{Parser Function}).
5364 When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
5365 per-symbol @code{%destructor}.
5366 You may also define a per-type @code{%destructor} by listing a semantic type
5367 tag among @var{symbols}.
5368 In that case, the parser will invoke this @var{code} whenever it discards any
5369 grammar symbol that has that semantic type tag unless that symbol has its own
5370 per-symbol @code{%destructor}.
5372 Finally, you can define two different kinds of default @code{%destructor}s.
5373 You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
5374 exactly one @code{%destructor} declaration in your grammar file.
5375 The parser will invoke the @var{code} associated with one of these whenever it
5376 discards any user-defined grammar symbol that has no per-symbol and no per-type
5377 @code{%destructor}.
5378 The parser uses the @var{code} for @code{<*>} in the case of such a grammar
5379 symbol for which you have formally declared a semantic type tag (@code{%token},
5380 @code{%nterm}, and @code{%type}
5381 count as such a declaration, but @code{$<tag>$} does not).
5382 The parser uses the @var{code} for @code{<>} in the case of such a grammar
5383 symbol that has no declared semantic type tag.
5384 @end deffn
5386 @noindent
5387 For example:
5389 @example
5390 %union @{ char *string; @}
5391 %token <string> STRING1 STRING2
5392 %nterm <string> string1 string2
5393 %union @{ char character; @}
5394 %token <character> CHR
5395 %nterm <character> chr
5396 %token TAGLESS
5398 %destructor @{ @} <character>
5399 %destructor @{ free ($$); @} <*>
5400 %destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
5401 %destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
5402 @end example
5404 @noindent
5405 guarantees that, when the parser discards any user-defined symbol that has a
5406 semantic type tag other than @code{<character>}, it passes its semantic value
5407 to @code{free} by default.
5408 However, when the parser discards a @code{STRING1} or a @code{string1},
5409 it uses the third @code{%destructor}, which frees it and
5410 prints its line number to @code{stdout} (@code{free} is invoked only once).
5411 Finally, the parser merely prints a message whenever it discards any symbol,
5412 such as @code{TAGLESS}, that has no semantic type tag.
5414 A Bison-generated parser invokes the default @code{%destructor}s only for
5415 user-defined as opposed to Bison-defined symbols.
5416 For example, the parser will not invoke either kind of default
5417 @code{%destructor} for the special Bison-defined symbols @code{$accept},
5418 @code{$undefined}, or @code{$end} (@pxref{Table of Symbols}),
5419 none of which you can reference in your grammar.
5420 It also will not invoke either for the @code{error} token (@pxref{Table of
5421 Symbols}), which is always defined by Bison regardless of whether you
5422 reference it in your grammar.
5423 However, it may invoke one of them for the end token (token 0) if you
5424 redefine it from @code{$end} to, for example, @code{END}:
5426 @example
5427 %token END 0
5428 @end example
5430 @cindex actions in midrule
5431 @cindex midrule actions
5432 Finally, Bison will never invoke a @code{%destructor} for an unreferenced
5433 midrule semantic value (@pxref{Midrule Actions}).
5434 That is, Bison does not consider a midrule to have a semantic value if you
5435 do not reference @code{$$} in the midrule's action or @code{$@var{n}}
5436 (where @var{n} is the right-hand side symbol position of the midrule) in
5437 any later action in that rule.  However, if you do reference either, the
5438 Bison-generated parser will invoke the @code{<>} @code{%destructor} whenever
5439 it discards the midrule symbol.
5441 @ignore
5442 @noindent
5443 In the future, it may be possible to redefine the @code{error} token as a
5444 nonterminal that captures the discarded symbols.
5445 In that case, the parser will invoke the default destructor for it as well.
5446 @end ignore
5448 @sp 1
5450 @cindex discarded symbols
5451 @dfn{Discarded symbols} are the following:
5453 @itemize
5454 @item
5455 stacked symbols popped during the first phase of error recovery,
5456 @item
5457 incoming terminals during the second phase of error recovery,
5458 @item
5459 the current lookahead and the entire stack (except the current
5460 right-hand side symbols) when the parser returns immediately, and
5461 @item
5462 the current lookahead and the entire stack (including the current right-hand
5463 side symbols) when the C++ parser (@file{lalr1.cc}) catches an exception in
5464 @code{parse},
5465 @item
5466 the start symbol, when the parser succeeds.
5467 @end itemize
5469 The parser can @dfn{return immediately} because of an explicit call to
5470 @code{YYABORT}, @code{YYACCEPT} or @code{YYNOMEM}, or failed error recovery,
5471 or memory exhaustion.
5473 Right-hand side symbols of a rule that explicitly triggers a syntax
5474 error via @code{YYERROR} are not discarded automatically.  As a rule
5475 of thumb, destructors are invoked only when user actions cannot manage
5476 the memory.
5478 @node Printer Decl
5479 @subsection Printing Semantic Values
5480 @cindex printing semantic values
5481 @findex %printer
5482 @findex <*>
5483 @findex <>
5484 When run-time traces are enabled (@pxref{Tracing}),
5485 the parser reports its actions, such as reductions.  When a symbol involved
5486 in an action is reported, only its kind is displayed, as the parser cannot
5487 know how semantic values should be formatted.
5489 The @code{%printer} directive defines code that is called when a symbol is
5490 reported.  Its syntax is the same as @code{%destructor} (@pxref{Destructor
5491 Decl}).
5493 @deffn {Directive} %printer @{ @var{code} @} @var{symbols}
5494 @findex %printer
5495 @vindex yyo
5496 @c This is the same text as for %destructor.
5497 Invoke the braced @var{code} whenever the parser displays one of the
5498 @var{symbols}.  Within @var{code}, @code{yyo} denotes the output stream (a
5499 @code{FILE*} in C, an @code{std::ostream&} in C++, and @code{stdout} in D), @code{$$} (or
5500 @code{$<@var{tag}>$}) designates the semantic value associated with the
5501 symbol, and @code{@@$} its location.  The additional parser parameters are
5502 also available (@pxref{Parser Function}).
5504 The @var{symbols} are defined as for @code{%destructor} (@pxref{Destructor
5505 Decl}.): they can be per-type (e.g.,
5506 @samp{<ival>}), per-symbol (e.g., @samp{exp}, @samp{NUM}, @samp{"float"}),
5507 typed per-default (i.e., @samp{<*>}, or untyped per-default (i.e.,
5508 @samp{<>}).
5509 @end deffn
5511 @noindent
5512 For example:
5514 @example
5515 %union @{ char *string; @}
5516 %token <string> STRING1 STRING2
5517 %nterm <string> string1 string2
5518 %union @{ char character; @}
5519 %token <character> CHR
5520 %nterm <character> chr
5521 %token TAGLESS
5523 %printer @{ fprintf (yyo, "'%c'", $$); @} <character>
5524 %printer @{ fprintf (yyo, "&%p", $$); @} <*>
5525 %printer @{ fprintf (yyo, "\"%s\"", $$); @} STRING1 string1
5526 %printer @{ fprintf (yyo, "<>"); @} <>
5527 @end example
5529 @noindent
5530 guarantees that, when the parser print any symbol that has a semantic type
5531 tag other than @code{<character>}, it display the address of the semantic
5532 value by default.  However, when the parser displays a @code{STRING1} or a
5533 @code{string1}, it formats it as a string in double quotes.  It performs
5534 only the second @code{%printer} in this case, so it prints only once.
5535 Finally, the parser print @samp{<>} for any symbol, such as @code{TAGLESS},
5536 that has no semantic type tag.  @xref{Mfcalc Traces}, for a complete example.
5540 @node Expect Decl
5541 @subsection Suppressing Conflict Warnings
5542 @cindex suppressing conflict warnings
5543 @cindex preventing warnings about conflicts
5544 @cindex warnings, preventing
5545 @cindex conflicts, suppressing warnings of
5546 @findex %expect
5547 @findex %expect-rr
5549 Bison normally warns if there are any conflicts in the grammar
5550 (@pxref{Shift/Reduce}), but most real grammars
5551 have harmless shift/reduce conflicts which are resolved in a predictable
5552 way and would be difficult to eliminate.  It is desirable to suppress
5553 the warning about these conflicts unless the number of conflicts
5554 changes.  You can do this with the @code{%expect} declaration.
5556 The declaration looks like this:
5558 @example
5559 %expect @var{n}
5560 @end example
5562 Here @var{n} is a decimal integer.  The declaration says there should
5563 be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
5564 Bison reports an error if the number of shift/reduce conflicts differs
5565 from @var{n}, or if there are any reduce/reduce conflicts.
5567 For deterministic parsers, reduce/reduce conflicts are more
5568 serious, and should be eliminated entirely.  Bison will always report
5569 reduce/reduce conflicts for these parsers.  With GLR
5570 parsers, however, both kinds of conflicts are routine; otherwise,
5571 there would be no need to use GLR parsing.  Therefore, it is
5572 also possible to specify an expected number of reduce/reduce conflicts
5573 in GLR parsers, using the declaration:
5575 @example
5576 %expect-rr @var{n}
5577 @end example
5579 You may wish to be more specific in your
5580 specification of expected conflicts.  To this end, you can also attach
5581 @code{%expect} and @code{%expect-rr} modifiers to individual rules.
5582 The interpretation of these modifiers differs from their use as
5583 declarations.  When attached to rules, they indicate the number of states
5584 in which the rule is involved in a conflict.  You will need to consult the
5585 output resulting from @option{-v} to determine appropriate numbers to use.
5586 For example, for the following grammar fragment, the first rule for
5587 @code{empty_dims} appears in two states in which the @samp{[} token is a
5588 lookahead.  Having determined that, you can document this fact with an
5589 @code{%expect} modifier as follows:
5591 @example
5592 dims:
5593   empty_dims
5594 | '[' expr ']' dims
5597 empty_dims:
5598   %empty   %expect 2
5599 | empty_dims '[' ']'
5601 @end example
5603 Mid-rule actions generate implicit rules that are also subject to conflicts
5604 (@pxref{Midrule Conflicts}). To attach
5605 an @code{%expect} or @code{%expect-rr} annotation to an implicit
5606 mid-rule action's rule, put it before the action.  For example,
5608 @example
5609 %glr-parser
5610 %expect-rr 1
5614 clause:
5615   "condition" %expect-rr 1 @{ value_mode(); @} '(' exprs ')'
5616 | "condition" %expect-rr 1 @{ class_mode(); @} '(' types ')'
5618 @end example
5620 @noindent
5621 Here, the appropriate mid-rule action will not be determined until after
5622 the @samp{(} token is shifted.  Thus,
5623 the two actions will clash with each other, and we should expect one
5624 reduce/reduce conflict for each.
5626 In general, using @code{%expect} involves these steps:
5628 @itemize @bullet
5629 @item
5630 Compile your grammar without @code{%expect}.  Use the @option{-v} option
5631 to get a verbose list of where the conflicts occur.  Bison will also
5632 print the number of conflicts.
5634 @item
5635 Check each of the conflicts to make sure that Bison's default
5636 resolution is what you really want.  If not, rewrite the grammar and
5637 go back to the beginning.
5639 @item
5640 Add an @code{%expect} declaration, copying the number @var{n} from the
5641 number that Bison printed.  With GLR parsers, add an
5642 @code{%expect-rr} declaration as well.
5644 @item
5645 Optionally, count up the number of states in which one or more
5646 conflicted reductions for particular rules appear and add these numbers
5647 to the affected rules as @code{%expect-rr} or @code{%expect} modifiers
5648 as appropriate.  Rules that are in conflict appear in the output listing
5649 surrounded by square brackets or, in the case of reduce/reduce conflicts,
5650 as reductions having the same lookahead symbol as a square-bracketed
5651 reduction in the same state.
5652 @end itemize
5654 Now Bison will report an error if you introduce an unexpected conflict,
5655 but will keep silent otherwise.
5657 @node Start Decl
5658 @subsection The Start-Symbol
5659 @cindex declaring the start symbol
5660 @cindex start symbol, declaring
5661 @cindex default start symbol
5662 @findex %start
5664 Bison assumes by default that the start symbol for the grammar is the first
5665 nonterminal specified in the grammar specification section.  The programmer
5666 may override this restriction with the @code{%start} declaration as follows:
5668 @example
5669 %start @var{symbol}
5670 @end example
5672 @node Pure Decl
5673 @subsection A Pure (Reentrant) Parser
5674 @cindex reentrant parser
5675 @cindex pure parser
5676 @findex %define api.pure
5678 A @dfn{reentrant} program is one which does not alter in the course of
5679 execution; in other words, it consists entirely of @dfn{pure} (read-only)
5680 code.  Reentrancy is important whenever asynchronous execution is possible;
5681 for example, a nonreentrant program may not be safe to call from a signal
5682 handler.  In systems with multiple threads of control, a nonreentrant
5683 program must be called only within interlocks.
5685 Normally, Bison generates a parser which is not reentrant.  This is
5686 suitable for most uses, and it permits compatibility with Yacc.  (The
5687 standard Yacc interfaces are inherently nonreentrant, because they use
5688 statically allocated variables for communication with @code{yylex},
5689 including @code{yylval} and @code{yylloc}.)
5691 Alternatively, you can generate a pure, reentrant parser.  The Bison
5692 declaration @samp{%define api.pure} says that you want the parser to be
5693 reentrant.  It looks like this:
5695 @example
5696 %define api.pure full
5697 @end example
5699 The result is that the communication variables @code{yylval} and
5700 @code{yylloc} become local variables in @code{yyparse}, and a different
5701 calling convention is used for the lexical analyzer function @code{yylex}.
5702 @xref{Pure Calling}, for the details of this.  The variable @code{yynerrs}
5703 becomes local in @code{yyparse} in pull mode but it becomes a member of
5704 @code{yypstate} in push mode.  (@pxref{Error Reporting Function}).  The
5705 convention for calling @code{yyparse} itself is unchanged.
5707 Whether the parser is pure has nothing to do with the grammar rules.
5708 You can generate either a pure parser or a nonreentrant parser from any
5709 valid grammar.
5711 @node Push Decl
5712 @subsection A Push Parser
5713 @cindex push parser
5714 @cindex push parser
5715 @findex %define api.push-pull
5717 A pull parser is called once and it takes control until all its input
5718 is completely parsed.  A push parser, on the other hand, is called
5719 each time a new token is made available.
5721 A push parser is typically useful when the parser is part of a
5722 main event loop in the client's application.  This is typically
5723 a requirement of a GUI, when the main event loop needs to be triggered
5724 within a certain time period.
5726 Normally, Bison generates a pull parser.
5727 The following Bison declaration says that you want the parser to be a push
5728 parser (@pxref{%define Summary}):
5730 @example
5731 %define api.push-pull push
5732 @end example
5734 In almost all cases, you want to ensure that your push parser is also
5735 a pure parser (@pxref{Pure Decl}).  The only
5736 time you should create an impure push parser is to have backwards
5737 compatibility with the impure Yacc pull mode interface.  Unless you know
5738 what you are doing, your declarations should look like this:
5740 @example
5741 %define api.pure full
5742 %define api.push-pull push
5743 @end example
5745 There is a major notable functional difference between the pure push parser
5746 and the impure push parser.  It is acceptable for a pure push parser to have
5747 many parser instances, of the same type of parser, in memory at the same time.
5748 An impure push parser should only use one parser at a time.
5750 When a push parser is selected, Bison will generate some new symbols in
5751 the generated parser.  @code{yypstate} is a structure that the generated
5752 parser uses to store the parser's state.  @code{yypstate_new} is the
5753 function that will create a new parser instance.  @code{yypstate_delete}
5754 will free the resources associated with the corresponding parser instance.
5755 Finally, @code{yypush_parse} is the function that should be called whenever a
5756 token is available to provide the parser.  A trivial example
5757 of using a pure push parser would look like this:
5759 @example
5760 int status;
5761 yypstate *ps = yypstate_new ();
5762 do @{
5763   status = yypush_parse (ps, yylex (), NULL);
5764 @} while (status == YYPUSH_MORE);
5765 yypstate_delete (ps);
5766 @end example
5768 If the user decided to use an impure push parser, a few things about the
5769 generated parser will change.  The @code{yychar} variable becomes a global
5770 variable instead of a local one in the @code{yypush_parse} function.  For
5771 this reason, the signature of the @code{yypush_parse} function is changed to
5772 remove the token as a parameter.  A nonreentrant push parser example would
5773 thus look like this:
5775 @example
5776 extern int yychar;
5777 int status;
5778 yypstate *ps = yypstate_new ();
5779 do @{
5780   yychar = yylex ();
5781   status = yypush_parse (ps);
5782 @} while (status == YYPUSH_MORE);
5783 yypstate_delete (ps);
5784 @end example
5786 That's it. Notice the next token is put into the global variable @code{yychar}
5787 for use by the next invocation of the @code{yypush_parse} function.
5789 Bison also supports both the push parser interface along with the pull parser
5790 interface in the same generated parser.  In order to get this functionality,
5791 you should replace the @samp{%define api.push-pull push} declaration with the
5792 @samp{%define api.push-pull both} declaration.  Doing this will create all of
5793 the symbols mentioned earlier along with the two extra symbols, @code{yyparse}
5794 and @code{yypull_parse}.  @code{yyparse} can be used exactly as it normally
5795 would be used.  However, the user should note that it is implemented in the
5796 generated parser by calling @code{yypull_parse}.
5797 This makes the @code{yyparse} function that is generated with the
5798 @samp{%define api.push-pull both} declaration slower than the normal
5799 @code{yyparse} function.  If the user
5800 calls the @code{yypull_parse} function it will parse the rest of the input
5801 stream.  It is possible to @code{yypush_parse} tokens to select a subgrammar
5802 and then @code{yypull_parse} the rest of the input stream.  If you would like
5803 to switch back and forth between between parsing styles, you would have to
5804 write your own @code{yypull_parse} function that knows when to quit looking
5805 for input.  An example of using the @code{yypull_parse} function would look
5806 like this:
5808 @example
5809 yypstate *ps = yypstate_new ();
5810 yypull_parse (ps); /* Will call the lexer */
5811 yypstate_delete (ps);
5812 @end example
5814 Adding the @samp{%define api.pure} declaration does exactly the same thing to
5815 the generated parser with @samp{%define api.push-pull both} as it did for
5816 @samp{%define api.push-pull push}.
5818 @node Decl Summary
5819 @subsection Bison Declaration Summary
5820 @cindex Bison declaration summary
5821 @cindex declaration summary
5822 @cindex summary, Bison declaration
5824 Here is a summary of the declarations used to define a grammar:
5826 @deffn {Directive} %union
5827 Declare the collection of data types that semantic values may have
5828 (@pxref{Union Decl}).
5829 @end deffn
5831 @deffn {Directive} %token
5832 Declare a terminal symbol (token kind name) with no precedence
5833 or associativity specified (@pxref{Token Decl}).
5834 @end deffn
5836 @deffn {Directive} %right
5837 Declare a terminal symbol (token kind name) that is right-associative
5838 (@pxref{Precedence Decl}).
5839 @end deffn
5841 @deffn {Directive} %left
5842 Declare a terminal symbol (token kind name) that is left-associative
5843 (@pxref{Precedence Decl}).
5844 @end deffn
5846 @deffn {Directive} %nonassoc
5847 Declare a terminal symbol (token kind name) that is nonassociative
5848 (@pxref{Precedence Decl}).
5849 Using it in a way that would be associative is a syntax error.
5850 @end deffn
5852 @ifset defaultprec
5853 @deffn {Directive} %default-prec
5854 Assign a precedence to rules lacking an explicit @code{%prec} modifier
5855 (@pxref{Contextual Precedence}).
5856 @end deffn
5857 @end ifset
5859 @deffn {Directive} %nterm
5860 Declare the type of semantic values for a nonterminal symbol (@pxref{Type
5861 Decl}).
5862 @end deffn
5864 @deffn {Directive} %type
5865 Declare the type of semantic values for a symbol (@pxref{Type Decl}).
5866 @end deffn
5868 @deffn {Directive} %start
5869 Specify the grammar's start symbol (@pxref{Start Decl}).
5870 @end deffn
5872 @deffn {Directive} %expect
5873 Declare the expected number of shift/reduce conflicts, either overall or
5874 for a given rule
5875 (@pxref{Expect Decl}).
5876 @end deffn
5878 @deffn {Directive} %expect-rr
5879 Declare the expected number of reduce/reduce conflicts, either overall or
5880 for a given rule
5881 (@pxref{Expect Decl}).
5882 @end deffn
5885 @sp 1
5886 @noindent
5887 In order to change the behavior of @command{bison}, use the following
5888 directives:
5890 @deffn {Directive} %code @{@var{code}@}
5891 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
5892 @findex %code
5893 Insert @var{code} verbatim into the output parser source at the
5894 default location or at the location specified by @var{qualifier}.
5895 @xref{%code Summary}.
5896 @end deffn
5898 @deffn {Directive} %debug
5899 Instrument the parser for traces.  Obsoleted by @samp{%define
5900 parse.trace}.
5901 @xref{Tracing}.
5902 @end deffn
5904 @deffn {Directive} %define @var{variable}
5905 @deffnx {Directive} %define @var{variable} @var{value}
5906 @deffnx {Directive} %define @var{variable} @{@var{value}@}
5907 @deffnx {Directive} %define @var{variable} "@var{value}"
5908 Define a variable to adjust Bison's behavior.  @xref{%define Summary}.
5909 @end deffn
5911 @deffn {Directive} %defines
5912 @deffnx {Directive} %defines @var{defines-file}
5913 Historical name for @code{%header}.  @xref{%header,,@code{%header}}.
5914 @end deffn
5916 @deffn {Directive} %destructor
5917 Specify how the parser should reclaim the memory associated to
5918 discarded symbols.  @xref{Destructor Decl}.
5919 @end deffn
5921 @deffn {Directive} %file-prefix "@var{prefix}"
5922 Specify a prefix to use for all Bison output file names.  The names
5923 are chosen as if the grammar file were named @file{@var{prefix}.y}.
5924 @end deffn
5926 @anchor{%header}
5927 @deffn {Directive} %header
5928 Write a parser header file containing definitions for the token kind names
5929 defined in the grammar as well as a few other declarations.  If the parser
5930 implementation file is named @file{@var{name}.c} then the parser header file
5931 is named @file{@var{name}.h}.
5933 For C parsers, the parser header file declares @code{YYSTYPE} unless
5934 @code{YYSTYPE} is already defined as a macro or you have used a
5935 @code{<@var{type}>} tag without using @code{%union}.  Therefore, if you are
5936 using a @code{%union} (@pxref{Multiple Types}) with components that require
5937 other definitions, or if you have defined a @code{YYSTYPE} macro or type
5938 definition (@pxref{Value Type}), you need to arrange for these definitions
5939 to be propagated to all modules, e.g., by putting them in a prerequisite
5940 header that is included both by your parser and by any other module that
5941 needs @code{YYSTYPE}.
5943 Unless your parser is pure, the parser header file declares
5944 @code{yylval} as an external variable.  @xref{Pure Decl}.
5946 If you have also used locations, the parser header file declares
5947 @code{YYLTYPE} and @code{yylloc} using a protocol similar to that of the
5948 @code{YYSTYPE} macro and @code{yylval}.  @xref{Tracking Locations}.
5950 This parser header file is normally essential if you wish to put the
5951 definition of @code{yylex} in a separate source file, because
5952 @code{yylex} typically needs to be able to refer to the
5953 above-mentioned declarations and to the token kind codes.  @xref{Token
5954 Values}.
5956 @findex %code requires
5957 @findex %code provides
5958 If you have declared @code{%code requires} or @code{%code provides}, the output
5959 header also contains their code.
5960 @xref{%code Summary}.
5962 @cindex Header guard
5963 The generated header is protected against multiple inclusions with a C
5964 preprocessor guard: @samp{YY_@var{PREFIX}_@var{FILE}_INCLUDED}, where
5965 @var{PREFIX} and @var{FILE} are the prefix (@pxref{Multiple Parsers}) and
5966 generated file name turned uppercase, with each series of non alphanumerical
5967 characters converted to a single underscore.
5969 For instance with @samp{%define api.prefix @{calc@}} and @samp{%header
5970 "lib/parse.h"}, the header will be guarded as follows.
5971 @example
5972 #ifndef YY_CALC_LIB_PARSE_H_INCLUDED
5973 # define YY_CALC_LIB_PARSE_H_INCLUDED
5975 #endif /* ! YY_CALC_LIB_PARSE_H_INCLUDED */
5976 @end example
5978 Introduced in Bison 3.8.
5979 @end deffn
5981 @deffn {Directive} %header @var{header-file}
5982 Same as above, but save in the file @file{@var{header-file}}.
5983 @end deffn
5985 @deffn {Directive} %language "@var{language}"
5986 Specify the programming language for the generated parser.  Currently
5987 supported languages include C, C++, D and Java.  @var{language} is
5988 case-insensitive.
5989 @end deffn
5991 @deffn {Directive} %locations
5992 Generate the code processing the locations (@pxref{Action Features}).  This
5993 mode is enabled as soon as the grammar uses the special @samp{@@@var{n}}
5994 tokens, but if your grammar does not use it, using @samp{%locations} allows
5995 for more accurate syntax error messages.
5996 @end deffn
5998 @deffn {Directive} %name-prefix "@var{prefix}"
5999 Obsoleted by @samp{%define api.prefix @{@var{prefix}@}}.  @xref{Multiple
6000 Parsers}.  For C++ parsers, see the
6001 @samp{%define api.namespace} documentation in this section.
6003 Rename the external symbols used in the parser so that they start with
6004 @var{prefix} instead of @samp{yy}.  The precise list of symbols renamed in C
6005 parsers is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
6006 @code{yylval}, @code{yychar}, @code{yydebug}, and (if locations are used)
6007 @code{yylloc}.  If you use a push parser, @code{yypush_parse},
6008 @code{yypull_parse}, @code{yypstate}, @code{yypstate_new} and
6009 @code{yypstate_delete} will also be renamed.  For example, if you use
6010 @samp{%name-prefix "c_"}, the names become @code{c_parse}, @code{c_lex}, and
6011 so on.
6013 Contrary to defining @code{api.prefix}, some symbols are @emph{not} renamed
6014 by @code{%name-prefix}, for instance @code{YYDEBUG}, @code{YYTOKENTYPE},
6015 @code{yytoken_kind_t}, @code{YYSTYPE}, @code{YYLTYPE}.
6016 @end deffn
6018 @ifset defaultprec
6019 @deffn {Directive} %no-default-prec
6020 Do not assign a precedence to rules lacking an explicit @code{%prec}
6021 modifier (@pxref{Contextual Precedence}).
6022 @end deffn
6023 @end ifset
6025 @deffn {Directive} %no-lines
6026 Don't generate any @code{#line} preprocessor commands in the parser
6027 implementation file.  Ordinarily Bison writes these commands in the parser
6028 implementation file so that the C compiler and debuggers will associate
6029 errors and object code with your source file (the grammar file).  This
6030 directive causes them to associate errors with the parser implementation
6031 file, treating it as an independent source file in its own right.
6032 @end deffn
6034 @deffn {Directive} %output "@var{file}"
6035 Generate the parser implementation in @file{@var{file}}.
6036 @end deffn
6038 @deffn {Directive} %pure-parser
6039 Deprecated version of @samp{%define api.pure} (@pxref{%define
6040 Summary}), for which Bison is more careful to warn about
6041 unreasonable usage.
6042 @end deffn
6044 @deffn {Directive} %require "@var{version}"
6045 Require version @var{version} or higher of Bison.  @xref{Require Decl}.
6046 @end deffn
6048 @deffn {Directive} %skeleton "@var{file}"
6049 Specify the skeleton to use.
6051 @c You probably don't need this option unless you are developing Bison.
6052 @c You should use @code{%language} if you want to specify the skeleton for a
6053 @c different language, because it is clearer and because it will always choose the
6054 @c correct skeleton for non-deterministic or push parsers.
6056 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
6057 file in the Bison installation directory.
6058 If it does, @var{file} is an absolute file name or a file name relative to the
6059 directory of the grammar file.
6060 This is similar to how most shells resolve commands.
6061 @end deffn
6063 @deffn {Directive} %token-table
6064 This feature is obsolescent, avoid it in new projects.
6066 Generate an array of token names in the parser implementation file.  The
6067 name of the array is @code{yytname}; @code{yytname[@var{i}]} is the name of
6068 the token whose internal Bison token code is @var{i}.  The first three
6069 elements of @code{yytname} correspond to the predefined tokens
6070 @code{"$end"}, @code{"error"}, and @code{"$undefined"}; after these come the
6071 symbols defined in the grammar file.
6073 The name in the table includes all the characters needed to represent the
6074 token in Bison.  For single-character literals and literal strings, this
6075 includes the surrounding quoting characters and any escape sequences.  For
6076 example, the Bison single-character literal @code{'+'} corresponds to a
6077 three-character name, represented in C as @code{"'+'"}; and the Bison
6078 two-character literal string @code{"\\/"} corresponds to a five-character
6079 name, represented in C as @code{"\"\\\\/\""}.
6081 When you specify @code{%token-table}, Bison also generates macro definitions
6082 for macros @code{YYNTOKENS}, @code{YYNNTS}, and @code{YYNRULES}, and
6083 @code{YYNSTATES}:
6085 @table @code
6086 @item YYNTOKENS
6087 The number of terminal symbols, i.e., the highest token code, plus one.
6088 @item YYNNTS
6089 The number of nonterminal symbols.
6090 @item YYNRULES
6091 The number of grammar rules,
6092 @item YYNSTATES
6093 The number of parser states (@pxref{Parser States}).
6094 @end table
6096 Here's code for looking up a multicharacter token in @code{yytname},
6097 assuming that the characters of the token are stored in @code{token_buffer},
6098 and assuming that the token does not contain any characters like @samp{"}
6099 that require escaping.
6101 @example
6102 for (int i = 0; i < YYNTOKENS; i++)
6103   if (yytname[i]
6104       && yytname[i][0] == '"'
6105       && ! strncmp (yytname[i] + 1, token_buffer,
6106                     strlen (token_buffer))
6107       && yytname[i][strlen (token_buffer) + 1] == '"'
6108       && yytname[i][strlen (token_buffer) + 2] == 0)
6109     break;
6110 @end example
6112 This method is discouraged: the primary purpose of string aliases is forging
6113 good error messages, not describing the spelling of keywords.  In addition,
6114 looking for the token kind at runtime incurs a (small but noticeable) cost.
6116 Finally, @code{%token-table} is incompatible with the @code{custom} and
6117 @code{detailed} values of the @code{parse.error} @code{%define} variable.
6118 @end deffn
6120 @deffn {Directive} %verbose
6121 Write an extra output file containing verbose descriptions of the parser
6122 states and what is done for each type of lookahead token in that state.
6123 @xref{Understanding}, for more information.
6124 @end deffn
6126 @deffn {Directive} %yacc
6127 Pretend the option @option{--yacc} was given
6128 (@pxref{option-yacc,,@option{--yacc}}), i.e., imitate Yacc, including its
6129 naming conventions.  Only makes sense with the @file{yacc.c}
6130 skeleton. @xref{Tuning the Parser}, for more.
6132 Of course, being a Bison extension, @code{%yacc} is somewhat
6133 self-contradictory@dots{}
6134 @end deffn
6137 @node %define Summary
6138 @subsection %define Summary
6140 There are many features of Bison's behavior that can be controlled by
6141 assigning the feature a single value.  For historical reasons, some such
6142 features are assigned values by dedicated directives, such as @code{%start},
6143 which assigns the start symbol.  However, newer such features are associated
6144 with variables, which are assigned by the @code{%define} directive:
6146 @deffn {Directive} %define @var{variable}
6147 @deffnx {Directive} %define @var{variable} @var{value}
6148 @deffnx {Directive} %define @var{variable} @{@var{value}@}
6149 @deffnx {Directive} %define @var{variable} "@var{value}"
6150 Define @var{variable} to @var{value}.
6152 The type of the values depend on the syntax.  Braces denote value in the
6153 target language (e.g., a namespace, a type, etc.).  Keyword values (no
6154 delimiters) denote finite choice (e.g., a variation of a feature).  String
6155 values denote remaining cases (e.g., a file name).
6157 It is an error if a @var{variable} is defined by @code{%define} multiple
6158 times, but see @ref{Tuning the Parser,,@option{-D @var{name}[=@var{value}]}}.
6159 @end deffn
6161 The rest of this section summarizes variables and values that @code{%define}
6162 accepts.
6164 Some @var{variable}s take Boolean values.  In this case, Bison will complain
6165 if the variable definition does not meet one of the following four
6166 conditions:
6168 @enumerate
6169 @item @code{@var{value}} is @code{true}
6171 @item @code{@var{value}} is omitted (or @code{""} is specified).
6172 This is equivalent to @code{true}.
6174 @item @code{@var{value}} is @code{false}.
6176 @item @var{variable} is never defined.
6177 In this case, Bison selects a default value.
6178 @end enumerate
6180 What @var{variable}s are accepted, as well as their meanings and default
6181 values, depend on the selected target language and/or the parser skeleton
6182 (@pxref{Decl Summary}, @pxref{Decl Summary}).
6183 Unaccepted @var{variable}s produce an error.  Some of the accepted
6184 @var{variable}s are described below.
6187 @c ================================================== api.filename.file
6188 @anchor{api-filename-type}
6189 @deffn {Directive} {%define api.filename.type} @{@var{type}@}
6191 @itemize @bullet
6192 @item Language(s): C++
6194 @item Purpose:
6195 Define the type of file names in Bison's default location and position
6196 types. @xref{Exposing the Location Classes}.
6198 @item Accepted Values:
6199 Any type that is printable (via streams) and comparable (with @code{==} and
6200 @code{!=}).
6202 @item Default Value: @code{const std::string}.
6204 @item History:
6205 Introduced in Bison 2.0 as @code{filename_type} (with @code{std::string} as
6206 default), renamed as @code{api.filename.type} in Bison 3.7 (with @code{const
6207 std::string} as default).
6208 @end itemize
6209 @end deffn
6212 @c ================================================== api.header.include
6213 @deffn Directive {%define api.header.include} @{"header.h"@}
6214 @deffnx Directive {%define api.header.include} @{<header.h>@}
6215 @itemize
6216 @item Languages(s): C (@file{yacc.c})
6218 @item Purpose: Specify how the generated parser should include the generated header.
6220 Historically, when option @option{-d} or @option{--header} was used,
6221 @command{bison} generated a header and pasted an exact copy of it into the
6222 generated parser implementation file.  Since Bison 3.6, it is
6223 @code{#include}d as @samp{"@var{basename}.h"}, instead of duplicated, unless
6224 @var{file} is @samp{y.tab}, see below.
6226 The @code{api.header.include} variable allows to control how the generated
6227 parser @code{#include}s the generated header.  For instance:
6229 @example
6230 %define api.header.include @{"parse.h"@}
6231 @end example
6233 @noindent
6236 @example
6237 %define api.header.include @{<parser/parse.h>@}
6238 @end example
6240 Using @code{api.header.include} does not change the name of the generated
6241 header, only how it is included.
6243 To work around limitations of Automake's @command{ylwrap} (which runs
6244 @command{bison} with @option{--yacc}), @code{api.header.include} is
6245 @emph{not} predefined when the output file is @file{y.tab.c}.  Define it to
6246 avoid the duplication.
6248 @item Accepted Values:
6249 An argument for @code{#include}.
6251 @item Default Value:
6252 @samp{"@var{header-basename}"}, unless the header file is @file{y.tab.h},
6253 where @var{header-basename} is the name of the generated header, without
6254 directory part.  For instance with @samp{bison -d calc/parse.y},
6255 @code{api.header.include} defaults to @samp{"parse.h"}, not
6256 @samp{"calc/parse.h"}.
6258 @item History:
6259 Introduced in Bison 3.4.  Defaults to @samp{"@var{basename}.h"} since Bison
6260 3.7, unless the header file is @file{y.tab.h}.
6261 @end itemize
6262 @end deffn
6263 @c api.header.include
6266 @c ================================================== api.location.file
6267 @deffn {Directive} {%define api.location.file} "@var{file}"
6268 @deffnx {Directive} {%define api.location.file} @code{none}
6270 @itemize @bullet
6271 @item Language(s): C++
6273 @item Purpose:
6274 Define the name of the file in which Bison's default location and position
6275 types are generated. @xref{Exposing the Location Classes}.
6277 @item Accepted Values:
6278 @table @asis
6279 @item @code{none}
6280 If locations are enabled, generate the definition of the @code{position} and
6281 @code{location} classes in the header file if @code{%header}, otherwise in
6282 the parser implementation.
6284 @item "@var{file}"
6285 Generate the definition of the @code{position} and @code{location} classes
6286 in @var{file}.  This file name can be relative (to where the parser file is
6287 output) or absolute.
6288 @end table
6290 @item Default Value:
6291 Not applicable if locations are not enabled, or if a user location type is
6292 specified (see @code{api.location.type}).  Otherwise, Bison's
6293 @code{location} is generated in @file{location.hh} (@pxref{C++ location}).
6295 @item History:
6296 Introduced in Bison 3.2.
6297 @end itemize
6298 @end deffn
6301 @c ================================================== api.location.file
6302 @deffn {Directive} {%define api.location.include} @{"@var{file}"@}
6303 @deffnx {Directive} {%define api.location.include} @{<@var{file}>@}
6305 @itemize @bullet
6306 @item Language(s): C++
6308 @item Purpose:
6309 Specify how the generated file that defines the @code{position} and
6310 @code{location} classes is included.  This makes sense when the
6311 @code{location} class is exposed to the rest of your application/library in
6312 another directory.  @xref{Exposing the Location Classes}.
6314 @item Accepted Values: Argument for @code{#include}.
6316 @item Default Value:
6317 @samp{"@var{dir}/location.hh"} where @var{dir} is the directory part of the
6318 output.  For instance @file{src/parse} if
6319 @option{--output=src/parse/parser.cc} was given.
6321 @item History:
6322 Introduced in Bison 3.2.
6323 @end itemize
6325 @end deffn
6328 @c ================================================== api.location.type
6329 @deffn {Directive} {%define api.location.type} @{@var{type}@}
6331 @itemize @bullet
6332 @item Language(s): C, C++, Java
6334 @item Purpose: Define the location type.
6335 @xref{Location Type}, and @ref{User Defined Location Type}.
6337 @item Accepted Values: String
6339 @item Default Value: none
6341 @item History:
6342 Introduced in Bison 2.7 for C++ and Java, in Bison 3.4 for C.  Was
6343 originally named @code{location_type} in Bison 2.5 and 2.6.
6344 @end itemize
6345 @end deffn
6348 @c ================================================== api.namespace
6349 @deffn Directive {%define api.namespace} @{@var{namespace}@}
6350 @itemize
6351 @item Languages(s): C++
6353 @item Purpose: Specify the namespace for the parser class.
6354 For example, if you specify:
6356 @example
6357 %define api.namespace @{foo::bar@}
6358 @end example
6360 Bison uses @code{foo::bar} verbatim in references such as:
6362 @example
6363 foo::bar::parser::value_type
6364 @end example
6366 However, to open a namespace, Bison removes any leading @code{::} and then
6367 splits on any remaining occurrences:
6369 @example
6370 namespace foo @{ namespace bar @{
6371   class position;
6372   class location;
6373 @} @}
6374 @end example
6376 @item Accepted Values:
6377 Any absolute or relative C++ namespace reference without a trailing
6378 @code{"::"}.  For example, @code{"foo"} or @code{"::foo::bar"}.
6380 @item Default Value:
6381 @code{yy}, unless you used the obsolete @samp{%name-prefix "@var{prefix}"}
6382 directive.
6383 @end itemize
6384 @end deffn
6385 @c api.namespace
6388 @c ================================================== api.parser.class
6389 @deffn Directive {%define api.parser.class} @{@var{name}@}
6390 @itemize @bullet
6391 @item Language(s):
6392 C++, Java, D
6394 @item Purpose:
6395 The name of the parser class.
6397 @item Accepted Values:
6398 Any valid identifier.
6400 @item Default Value:
6401 In C++, @code{parser}.  In D and Java, @code{YYParser} or
6402 @code{@var{api.prefix}Parser} (@pxref{Java Bison Interface}).
6404 @item History:
6405 Introduced in Bison 3.3 to replace @code{parser_class_name}.
6406 @end itemize
6407 @end deffn
6408 @c api.parser.class
6411 @c ================================================== api.prefix
6412 @deffn {Directive} {%define api.prefix} @{@var{prefix}@}
6414 @itemize @bullet
6415 @item Language(s): C, C++, Java
6417 @item Purpose: Rename exported symbols.
6418 @xref{Multiple Parsers}.
6420 @item Accepted Values: String
6422 @item Default Value: @code{YY} for Java, @code{yy} otherwise.
6424 @item History:
6425 introduced in Bison 2.6, with its argument in double quotes.  Uses braces
6426 since Bison 3.0 (double quotes are still supported for backward
6427 compatibility).
6428 @end itemize
6429 @end deffn
6432 @c ================================================== api.pure
6433 @deffn Directive {%define api.pure} @var{purity}
6435 @itemize @bullet
6436 @item Language(s): C
6438 @item Purpose: Request a pure (reentrant) parser program.
6439 @xref{Pure Decl}.
6441 @item Accepted Values: @code{true}, @code{false}, @code{full}
6443 The value may be omitted: this is equivalent to specifying @code{true}, as is
6444 the case for Boolean values.
6446 When @code{%define api.pure full} is used, the parser is made reentrant. This
6447 changes the signature for @code{yylex} (@pxref{Pure Calling}), and also that of
6448 @code{yyerror} when the tracking of locations has been activated, as shown
6449 below.
6451 The @code{true} value is very similar to the @code{full} value, the only
6452 difference is in the signature of @code{yyerror} on Yacc parsers without
6453 @code{%parse-param}, for historical reasons.
6455 I.e., if @samp{%locations %define api.pure} is passed then the prototypes for
6456 @code{yyerror} are:
6458 @example
6459 void yyerror (char const *msg);                 // Yacc parsers.
6460 void yyerror (YYLTYPE *locp, char const *msg);  // GLR parsers.
6461 @end example
6463 But if @samp{%locations %define api.pure %parse-param @{int *nastiness@}} is
6464 used, then both parsers have the same signature:
6466 @example
6467 void yyerror (YYLTYPE *llocp, int *nastiness, char const *msg);
6468 @end example
6470 (@pxref{Error Reporting Function})
6472 @item Default Value: @code{false}
6474 @item History:
6475 the @code{full} value was introduced in Bison 2.7
6476 @end itemize
6477 @end deffn
6478 @c api.pure
6482 @c ================================================== api.push-pull
6483 @deffn Directive {%define api.push-pull} @var{kind}
6485 @itemize @bullet
6486 @item Language(s): C (deterministic parsers only), D, Java
6488 @item Purpose: Request a pull parser, a push parser, or both.
6489 @xref{Push Decl}.
6491 @item Accepted Values: @code{pull}, @code{push}, @code{both}
6493 @item Default Value: @code{pull}
6494 @end itemize
6495 @end deffn
6496 @c api.push-pull
6500 @c ================================================== api.symbol.prefix
6501 @deffn Directive {%define api.symbol.prefix} @{@var{prefix}@}
6503 @itemize
6504 @item Languages(s): all
6506 @item Purpose:
6507 Add a prefix to the name of the symbol kinds.  For instance
6509 @example
6510 %define api.symbol.prefix @{S_@}
6511 %token FILE for ERROR
6513 start: FILE for ERROR;
6514 @end example
6516 @noindent
6517 generates this definition in C:
6519 @example
6520 /* Symbol kind.  */
6521 enum yysymbol_kind_t
6523   S_YYEMPTY = -2,   /* No symbol.  */
6524   S_YYEOF = 0,      /* $end  */
6525   S_YYERROR = 1,    /* error  */
6526   S_YYUNDEF = 2,    /* $undefined  */
6527   S_FILE = 3,       /* FILE  */
6528   S_for = 4,        /* for  */
6529   S_ERROR = 5,      /* ERROR  */
6530   S_YYACCEPT = 6,   /* $accept  */
6531   S_start = 7       /* start  */
6533 @end example
6535 @item Accepted Values:
6536 Any non empty string.  Must be a valid identifier in the target language
6537 (typically a non empty sequence of letters, underscores, and ---not at the
6538 beginning--- digits).
6540 The empty prefix is (generally) invalid:
6541 @itemize
6542 @item
6543 in C it would create collision with the @code{YYERROR} macro, and
6544 potentially token kind definitions and symbol kind definitions would
6545 collide;
6546 @item
6547 unnamed symbols (such as @samp{'+'}) have a name which starts with a digit;
6548 @item
6549 even in languages with scoped enumerations such as Java, an empty prefix is
6550 dangerous: symbol names may collide with the target language keywords, or
6551 with other members of the @code{SymbolKind} class.
6552 @end itemize
6555 @item Default Value:
6556 @code{YYSYMBOL_} in C, @code{S_} in C++ and Java, empty in D.
6557 @item History:
6558 introduced in Bison 3.6.
6559 @end itemize
6560 @end deffn
6561 @c api.symbol.prefix
6564 @c ================================================== api.token.constructor
6565 @deffn Directive {%define api.token.constructor}
6567 @itemize @bullet
6568 @item Language(s):
6569 C++, D
6571 @item Purpose:
6572 Request that symbols be handled as a whole (type, value, and possibly
6573 location) in the scanner. In the case of C++, it works only when
6574 variant-based semantic values are enabled (@pxref{C++ Variants}), see
6575 @ref{Complete Symbols}, for details. In D, token constructors work with both
6576 @samp{%union} and @samp{%define api.value.type union}.
6578 @item Accepted Values:
6579 Boolean.
6581 @item Default Value:
6582 @code{false}
6583 @item History:
6584 introduced in Bison 3.0.
6585 @end itemize
6586 @end deffn
6587 @c api.token.constructor
6590 @c ================================================== api.token.prefix
6591 @anchor{api-token-prefix}
6592 @deffn Directive {%define api.token.prefix} @{@var{prefix}@}
6593 @itemize
6594 @item Languages(s): all
6596 @item Purpose:
6597 Add a prefix to the token names when generating their definition in the
6598 target language.  For instance
6600 @example
6601 %define api.token.prefix @{TOK_@}
6602 %token FILE for ERROR
6604 start: FILE for ERROR;
6605 @end example
6607 @noindent
6608 generates the definition of the symbols @code{TOK_FILE}, @code{TOK_for}, and
6609 @code{TOK_ERROR} in the generated source files.  In particular, the scanner
6610 must use these prefixed token names, while the grammar itself may still use
6611 the short names (as in the sample rule given above).  The generated
6612 informational files (@file{*.output}, @file{*.xml}, @file{*.gv}) are not
6613 modified by this prefix.
6615 Bison also prefixes the generated member names of the semantic value union.
6616 @xref{Type Generation}, for more
6617 details.
6619 See @ref{Calc++ Parser} and @ref{Calc++ Scanner}, for a complete example.
6621 @item Accepted Values:
6622 Any string.  Must be a valid identifier prefix in the target language
6623 (typically, a possibly empty sequence of letters, underscores, and ---not at
6624 the beginning--- digits).
6626 @item Default Value:
6627 empty
6628 @item History:
6629 introduced in Bison 3.0.
6630 @end itemize
6631 @end deffn
6632 @c api.token.prefix
6635 @c ================================================== api.token.raw
6636 @deffn Directive {%define api.token.raw}
6638 @itemize @bullet
6639 @item Language(s):
6642 @item Purpose:
6643 The output files normally define the enumeration of the @emph{token kinds}
6644 with Yacc-compatible token codes: sequential numbers starting at 257 except
6645 for single character tokens which stand for themselves (e.g., in ASCII,
6646 @samp{'a'} is numbered 65).  The parser however uses @emph{symbol kinds}
6647 which are assigned numbers sequentially starting at 0.  Therefore each time
6648 the scanner returns an (external) token kind, it must be mapped to the
6649 (internal) symbol kind.
6651 When @code{api.token.raw} is set, the code of the token kinds are forced to
6652 coincide with the symbol kind.  This saves one table lookup per token to map
6653 them from the token kind to the symbol kind, and also saves the generation
6654 of the mapping table.  The gain is typically moderate, but in extreme cases
6655 (very simple user actions), a 10% improvement can be observed.
6657 When @code{api.token.raw} is set, the grammar cannot use character literals
6658 (such as @samp{'a'}).
6660 @item Accepted Values: Boolean.
6662 @item Default Value:
6663 @code{true} in D, @code{false} otherwise
6664 @item History:
6665 introduced in Bison 3.5.  Was initially introduced in Bison 1.25 as
6666 @samp{%raw}, but never worked and was removed in Bison 1.29.
6667 @end itemize
6668 @end deffn
6669 @c api.token.raw
6672 @c ================================================== api.value.automove
6673 @deffn Directive {%define api.value.automove}
6675 @itemize @bullet
6676 @item Language(s):
6679 @item Purpose:
6680 Let occurrences of semantic values of the right-hand sides of a rule be
6681 implicitly turned in rvalues.  When enabled, a grammar such as:
6683 @example
6684 exp:
6685   "number"     @{ $$ = make_number ($1); @}
6686 | exp "+" exp  @{ $$ = make_binary (add, $1, $3); @}
6687 | "(" exp ")"  @{ $$ = $2; @}
6688 @end example
6690 @noindent
6691 is actually compiled as if you had written:
6693 @example
6694 exp:
6695   "number"     @{ $$ = make_number (std::move ($1)); @}
6696 | exp "+" exp  @{ $$ = make_binary (add,
6697                                    std::move ($1),
6698                                    std::move ($3)); @}
6699 | "(" exp ")"  @{ $$ = std::move ($2); @}
6700 @end example
6702 Using a value several times with automove enabled is typically an error.
6703 For instance, instead of:
6705 @example
6706 exp: "twice" exp  @{ $$ = make_binary (add, $2, $2); @}
6707 @end example
6709 @noindent
6710 write:
6712 @example
6713 exp: "twice" exp @{ auto v = $2; $$ = make_binary (add, v, v); @}
6714 @end example
6716 @noindent
6717 It is tempting to use @code{std::move} on one of the @code{v}, but the
6718 argument evaluation order in C++ is unspecified.
6720 @item Accepted Values:
6721 Boolean.
6723 @item Default Value:
6724 @code{false}
6725 @item History:
6726 introduced in Bison 3.2
6727 @end itemize
6728 @end deffn
6729 @c api.value.automove
6732 @c ================================================== api.value.type
6733 @deffn Directive {%define api.value.type} @var{support}
6734 @deffnx Directive {%define api.value.type} @{@var{type}@}
6735 @itemize @bullet
6736 @item Language(s):
6739 @item Purpose:
6740 The type for semantic values.
6742 @item Accepted Values:
6743 @table @asis
6744 @item @samp{@{@}}
6745 This grammar has no semantic value at all.  This is not properly supported
6746 yet.
6747 @item @samp{union-directive} (C, C++, D)
6748 The type is defined thanks to the @code{%union} directive.  You don't have
6749 to define @code{api.value.type} in that case, using @code{%union} suffices.
6750 @xref{Union Decl}.
6751 For instance:
6752 @example
6753 %define api.value.type union-directive
6754 %union
6756   int ival;
6757   char *sval;
6759 %token <ival> INT "integer"
6760 %token <sval> STR "string"
6761 @end example
6763 @item @samp{union} (C, C++)
6764 The symbols are defined with type names, from which Bison will generate a
6765 @code{union}.  For instance:
6766 @example
6767 %define api.value.type union
6768 %token <int> INT "integer"
6769 %token <char *> STR "string"
6770 @end example
6771 Most C++ objects cannot be stored in a @code{union}, use @samp{variant}
6772 instead.
6774 @item @samp{variant} (C++)
6775 This is similar to @code{union}, but special storage techniques are used to
6776 allow any kind of C++ object to be used. For instance:
6777 @example
6778 %define api.value.type variant
6779 %token <int> INT "integer"
6780 %token <std::string> STR "string"
6781 @end example
6782 @xref{C++ Variants}.
6784 @item @samp{@{@var{type}@}}
6785 Use this @var{type} as semantic value.
6786 @example
6787 %code requires
6789   struct my_value
6790   @{
6791     enum
6792     @{
6793       is_int, is_str
6794     @} kind;
6795     union
6796     @{
6797       int ival;
6798       char *sval;
6799     @} u;
6800   @};
6802 %define api.value.type @{struct my_value@}
6803 %token <u.ival> INT "integer"
6804 %token <u.sval> STR "string"
6805 @end example
6806 @end table
6808 @item Default Value:
6809 @itemize @minus
6810 @item
6811 @code{union-directive} if @code{%union} is used, otherwise @dots{}
6812 @item
6813 @code{int} if type tags are used (i.e., @samp{%token <@var{type}>@dots{}} or
6814 @samp{%nterm <@var{type}>@dots{}} is used), otherwise @dots{}
6815 @item
6816 undefined.
6817 @end itemize
6819 @item History:
6820 introduced in Bison 3.0.  Was introduced for Java only in 2.3b as
6821 @code{stype}.
6822 @end itemize
6823 @end deffn
6824 @c api.value.type
6827 @c ================================================== api.value.union.name
6828 @deffn Directive {%define api.value.union.name} @var{name}
6829 @itemize @bullet
6830 @item Language(s):
6833 @item Purpose:
6834 The tag of the generated @code{union} (@emph{not} the name of the
6835 @code{typedef}).  This variable is set to @code{@var{id}} when @samp{%union
6836 @var{id}} is used.  There is no clear reason to give this union a name.
6838 @item Accepted Values:
6839 Any valid identifier.
6841 @item Default Value:
6842 @code{YYSTYPE}.
6844 @item History:
6845 Introduced in Bison 3.0.3.
6846 @end itemize
6847 @end deffn
6848 @c api.value.union.name
6851 @c ================================================== lr.default-reduction
6853 @deffn Directive {%define lr.default-reduction} @var{when}
6855 @itemize @bullet
6856 @item Language(s): all
6858 @item Purpose: Specify the kind of states that are permitted to
6859 contain default reductions.  @xref{Default Reductions}.
6861 @item Accepted Values: @code{most}, @code{consistent}, @code{accepting}
6862 @item Default Value:
6863 @itemize
6864 @item @code{accepting} if @code{lr.type} is @code{canonical-lr}.
6865 @item @code{most} otherwise.
6866 @end itemize
6867 @item History:
6868 introduced as @code{lr.default-reductions} in 2.5, renamed as
6869 @code{lr.default-reduction} in 3.0.
6870 @end itemize
6871 @end deffn
6874 @c ============================================ lr.keep-unreachable-state
6876 @deffn Directive {%define lr.keep-unreachable-state}
6878 @itemize @bullet
6879 @item Language(s): all
6880 @item Purpose: Request that Bison allow unreachable parser states to
6881 remain in the parser tables.  @xref{Unreachable States}.
6882 @item Accepted Values: Boolean
6883 @item Default Value: @code{false}
6884 @item History:
6885 introduced as @code{lr.keep_unreachable_states} in 2.3b, renamed as
6886 @code{lr.keep-unreachable-states} in 2.5, and as
6887 @code{lr.keep-unreachable-state} in 3.0.
6888 @end itemize
6889 @end deffn
6890 @c lr.keep-unreachable-state
6893 @c ================================================== lr.type
6895 @deffn Directive {%define lr.type} @var{type}
6897 @itemize @bullet
6898 @item Language(s): all
6900 @item Purpose: Specify the type of parser tables within the
6901 LR(1) family.  @xref{LR Table Construction}.
6903 @item Accepted Values: @code{lalr}, @code{ielr}, @code{canonical-lr}
6905 @item Default Value: @code{lalr}
6906 @end itemize
6907 @end deffn
6910 @c ================================================== namespace
6911 @deffn Directive %define namespace @{@var{namespace}@}
6912 Obsoleted by @code{api.namespace}
6913 @end deffn
6914 @c namespace
6917 @c ================================================== parse.assert
6918 @deffn Directive {%define parse.assert}
6920 @itemize
6921 @item Languages(s): C, C++
6923 @item Purpose: Issue runtime assertions to catch invalid uses.
6924 In C, some important invariants in the implementation of the parser are
6925 checked when this option is enabled.
6927 In C++, when variants are used (@pxref{C++ Variants}), symbols must be
6928 constructed and destroyed properly.  This option checks these constraints
6929 using runtime type information (RTTI).  Therefore the generated code cannot
6930 be compiled with RTTI disabled (via compiler options such as
6931 @option{-fno-rtti}).
6933 @item Accepted Values: Boolean
6935 @item Default Value: @code{false}
6936 @end itemize
6937 @end deffn
6938 @c parse.assert
6941 @c ================================================== parse.error
6942 @deffn Directive {%define parse.error} @var{verbosity}
6943 @itemize
6944 @item Languages(s):
6946 @item Purpose:
6947 Control the generation of syntax error messages.  @xref{Error Reporting}.
6948 @item Accepted Values:
6949 @itemize
6950 @item @code{simple}
6951 Error messages passed to @code{yyerror} are simply @w{@code{"syntax
6952 error"}}.
6954 @item @code{detailed}
6955 Error messages report the unexpected token, and possibly the expected ones.
6956 However, this report can often be incorrect when LAC is not enabled
6957 (@pxref{LAC}).  Token name internationalization is supported.
6959 @item @code{verbose}
6960 Similar (but inferior) to @code{detailed}. The D parser does not support this value.
6962 Error messages report the unexpected token, and possibly the expected ones.
6963 However, this report can often be incorrect when LAC is not enabled
6964 (@pxref{LAC}).
6966 Does not support token internationalization.  Using non-ASCII characters in
6967 token aliases is not portable.
6969 @item @code{custom}
6970 The user is in charge of generating the syntax error message by defining the
6971 @code{yyreport_syntax_error} function.  @xref{Syntax Error Reporting
6972 Function}.
6973 @end itemize
6975 @item Default Value:
6976 @code{simple}
6978 @item History:
6979 introduced in 3.0 with support for @code{simple} and @code{verbose}.  Values
6980 @code{custom} and @code{detailed} were introduced in 3.6.
6981 @end itemize
6982 @end deffn
6983 @c parse.error
6986 @c ================================================== parse.lac
6987 @deffn Directive {%define parse.lac} @var{when}
6989 @itemize
6990 @item Languages(s): C/C++ (deterministic parsers only), D and Java.
6992 @item Purpose: Enable LAC (lookahead correction) to improve
6993 syntax error handling.  @xref{LAC}.
6994 @item Accepted Values: @code{none}, @code{full}
6995 @item Default Value: @code{none}
6996 @end itemize
6997 @end deffn
6998 @c parse.lac
7001 @c ================================================== parse.trace
7002 @deffn Directive {%define parse.trace}
7004 @itemize
7005 @item Languages(s): C, C++, D, Java
7007 @item Purpose: Require parser instrumentation for tracing.
7008 @xref{Tracing}.
7010 In C/C++, define the macro @code{YYDEBUG} (or @code{@var{prefix}DEBUG} with
7011 @samp{%define api.prefix @{@var{prefix}@}}), see @ref{Multiple Parsers}) to
7012 1 (if it is not already defined) so that the debugging facilities are
7013 compiled.
7015 @item Accepted Values: Boolean
7017 @item Default Value: @code{false}
7018 @end itemize
7019 @end deffn
7020 @c parse.trace
7023 @c ================================================== parser_class_name
7024 @deffn Directive %define parser_class_name @{@var{name}@}
7025 Obsoleted by @code{api.parser.class}
7026 @end deffn
7027 @c parser_class_name
7034 @node %code Summary
7035 @subsection %code Summary
7036 @findex %code
7037 @cindex Prologue
7039 The @code{%code} directive inserts code verbatim into the output
7040 parser source at any of a predefined set of locations.  It thus serves
7041 as a flexible and user-friendly alternative to the traditional Yacc
7042 prologue, @code{%@{@var{code}%@}}.  This section summarizes the
7043 functionality of @code{%code} for the various target languages
7044 supported by Bison.  For a detailed discussion of how to use
7045 @code{%code} in place of @code{%@{@var{code}%@}} for C/C++ and why it
7046 is advantageous to do so, @pxref{Prologue Alternatives}.
7048 @deffn {Directive} %code @{@var{code}@}
7049 This is the unqualified form of the @code{%code} directive.  It
7050 inserts @var{code} verbatim at a language-dependent default location
7051 in the parser implementation.
7053 For C/C++, the default location is the parser implementation file
7054 after the usual contents of the parser header file.  Thus, the
7055 unqualified form replaces @code{%@{@var{code}%@}} for most purposes.
7057 For D and Java, the default location is inside the parser class.
7058 @end deffn
7060 @deffn {Directive} %code @var{qualifier} @{@var{code}@}
7061 This is the qualified form of the @code{%code} directive.
7062 @var{qualifier} identifies the purpose of @var{code} and thus the
7063 location(s) where Bison should insert it.  That is, if you need to
7064 specify location-sensitive @var{code} that does not belong at the
7065 default location selected by the unqualified @code{%code} form, use
7066 this form instead.
7067 @end deffn
7069 For any particular qualifier or for the unqualified form, if there are
7070 multiple occurrences of the @code{%code} directive, Bison concatenates
7071 the specified code in the order in which it appears in the grammar
7072 file.
7074 Not all qualifiers are accepted for all target languages.  Unaccepted
7075 qualifiers produce an error.  Some of the accepted qualifiers are:
7077 @table @code
7078 @item requires
7079 @findex %code requires
7081 @itemize @bullet
7082 @item Language(s): C, C++
7084 @item Purpose:
7085 This is the best place to write dependency code required for the value and
7086 location types (@code{YYSTYPE} and @code{YYLTYPE} in C).  In other words,
7087 it's the best place to define types referenced in @code{%union} directives.
7088 In C, if you use @code{#define} to override Bison's default @code{YYSTYPE}
7089 and @code{YYLTYPE} definitions, then it is also the best place.  However you
7090 should rather @code{%define} @code{api.value.type} and
7091 @code{api.location.type}.
7093 @item Location(s):
7094 The parser header file and the parser implementation file before the
7095 Bison-generated definitions of the value and location types (@code{YYSTYPE}
7096 and @code{YYLTYPE} in C).
7097 @end itemize
7099 @item provides
7100 @findex %code provides
7102 @itemize @bullet
7103 @item Language(s): C, C++
7105 @item Purpose: This is the best place to write additional definitions and
7106 declarations that should be provided to other modules.
7108 @item Location(s):
7109 The parser header file and the parser implementation file after the
7110 Bison-generated value and location types (@code{YYSTYPE} and @code{YYLTYPE}
7111 in C), and token definitions.
7112 @end itemize
7114 @item top
7115 @findex %code top
7117 @itemize @bullet
7118 @item Language(s): C, C++
7120 @item Purpose: The unqualified @code{%code} or @code{%code requires}
7121 should usually be more appropriate than @code{%code top}.  However,
7122 occasionally it is necessary to insert code much nearer the top of the
7123 parser implementation file.  For example:
7125 @example
7126 %code top @{
7127   #define _GNU_SOURCE
7128   #include <stdio.h>
7130 @end example
7132 @item Location(s): Near the top of the parser implementation file.
7133 @end itemize
7135 @item imports
7136 @findex %code imports
7138 @itemize @bullet
7139 @item Language(s): D, Java
7141 @item Purpose: This is the best place to write Java import directives. D syntax
7142 allows for import statements all throughout the code.
7144 @item Location(s): The parser Java file after any Java package directive and
7145 before any class definitions. The parser D file before any class definitions.
7146 @end itemize
7147 @end table
7149 Though we say the insertion locations are language-dependent, they are
7150 technically skeleton-dependent.  Writers of non-standard skeletons
7151 however should choose their locations consistently with the behavior
7152 of the standard Bison skeletons.
7155 @node Multiple Parsers
7156 @section Multiple Parsers in the Same Program
7158 Most programs that use Bison parse only one language and therefore contain
7159 only one Bison parser.  But what if you want to parse more than one language
7160 with the same program?  Then you need to avoid name conflicts between
7161 different definitions of functions and variables such as @code{yyparse},
7162 @code{yylval}.  To use different parsers from the same compilation unit, you
7163 also need to avoid conflicts on types and macros (e.g., @code{YYSTYPE})
7164 exported in the generated header.
7166 The easy way to do this is to define the @code{%define} variable
7167 @code{api.prefix}.  With different @code{api.prefix}s it is guaranteed that
7168 headers do not conflict when included together, and that compiled objects
7169 can be linked together too.  Specifying @samp{%define api.prefix
7170 @{@var{prefix}@}} (or passing the option @option{-Dapi.prefix=@{@var{prefix}@}}, see
7171 @ref{Invocation}) renames the interface functions and
7172 variables of the Bison parser to start with @var{prefix} instead of
7173 @samp{yy}, and all the macros to start by @var{PREFIX} (i.e., @var{prefix}
7174 upper-cased) instead of @samp{YY}.
7176 The renamed symbols include @code{yyparse}, @code{yylex}, @code{yyerror},
7177 @code{yynerrs}, @code{yylval}, @code{yylloc}, @code{yychar} and
7178 @code{yydebug}.  If you use a push parser, @code{yypush_parse},
7179 @code{yypull_parse}, @code{yypstate}, @code{yypstate_new} and
7180 @code{yypstate_delete} will also be renamed.  The renamed macros include
7181 @code{YYSTYPE}, @code{YYLTYPE}, and @code{YYDEBUG}, which is treated
7182 specifically --- more about this below.
7184 For example, if you use @samp{%define api.prefix @{c@}}, the names become
7185 @code{cparse}, @code{clex}, @dots{}, @code{CSTYPE}, @code{CLTYPE}, and so
7188 Users of Flex must update the signature of the generated @code{yylex}
7189 function.  Since the Flex scanner usually includes the generated header of
7190 the parser (to get the definitions of the tokens, etc.), the most convenient
7191 way is to insert the declaration of @code{yylex} in the @code{provides}
7192 section:
7194 @example
7195 %define api.prefix @{c@}
7196 // Emitted in the header file, after the definition of YYSTYPE.
7197 %code provides
7199   // Tell Flex the expected prototype of yylex.
7200   #define YY_DECL                             \
7201     int clex (CSTYPE *yylval, CLTYPE *yylloc)
7203   // Declare the scanner.
7204   YY_DECL;
7206 @end example
7208 @sp 1
7210 The @code{%define} variable @code{api.prefix} works in two different ways.
7211 In the implementation file, it works by adding macro definitions to the
7212 beginning of the parser implementation file, defining @code{yyparse} as
7213 @code{@var{prefix}parse}, and so on:
7215 @example
7216 #define YYSTYPE CTYPE
7217 #define yyparse cparse
7218 #define yylval  clval
7220 YYSTYPE yylval;
7221 int yyparse (void);
7222 @end example
7224 This effectively substitutes one name for the other in the entire parser
7225 implementation file, thus the ``original'' names (@code{yylex},
7226 @code{YYSTYPE}, @dots{}) are also usable in the parser implementation file.
7228 However, in the parser header file, the symbols are defined renamed, for
7229 instance:
7231 @example
7232 extern CSTYPE clval;
7233 int cparse (void);
7234 @end example
7236 The macro @code{YYDEBUG} is commonly used to enable the tracing support in
7237 parsers.  To comply with this tradition, when @code{api.prefix} is used,
7238 @code{YYDEBUG} (not renamed) is used as a default value:
7240 @example
7241 /* Debug traces. */
7242 #ifndef CDEBUG
7243 # if defined YYDEBUG
7244 #  if YYDEBUG
7245 #   define CDEBUG 1
7246 #  else
7247 #   define CDEBUG 0
7248 #  endif
7249 # else
7250 #  define CDEBUG 0
7251 # endif
7252 #endif
7253 #if CDEBUG
7254 extern int cdebug;
7255 #endif
7256 @end example
7258 @sp 2
7260 Prior to Bison 2.6, a feature similar to @code{api.prefix} was provided by
7261 the obsolete directive @code{%name-prefix} (@pxref{Table of Symbols}) and
7262 the option @option{--name-prefix} (@pxref{Output Files}).
7264 @node Interface
7265 @chapter Parser C-Language Interface
7266 @cindex C-language interface
7267 @cindex interface
7269 The Bison parser is actually a C function named @code{yyparse}.  Here we
7270 describe the interface conventions of @code{yyparse} and the other
7271 functions that it needs to use.
7273 Keep in mind that the parser uses many C identifiers starting with
7274 @samp{yy} and @samp{YY} for internal purposes.  If you use such an
7275 identifier (aside from those in this manual) in an action or in epilogue
7276 in the grammar file, you are likely to run into trouble.
7278 @menu
7279 * Parser Function::         How to call @code{yyparse} and what it returns.
7280 * Push Parser Interface::   How to create, use, and destroy push parsers.
7281 * Lexical::                 You must supply a function @code{yylex}
7282                               which reads tokens.
7283 * Error Reporting::         Passing error messages to the user.
7284 * Action Features::         Special features for use in actions.
7285 * Internationalization::    How to let the parser speak in the user's
7286                               native language.
7287 @end menu
7289 @node Parser Function
7290 @section The Parser Function @code{yyparse}
7291 @findex yyparse
7293 You call the function @code{yyparse} to cause parsing to occur.  This
7294 function reads tokens, executes actions, and ultimately returns when it
7295 encounters end-of-input or an unrecoverable syntax error.  You can also
7296 write an action which directs @code{yyparse} to return immediately
7297 without reading further.
7300 @deftypefun int yyparse (@code{void})
7301 The value returned by @code{yyparse} is 0 if parsing was successful (return
7302 is due to end-of-input).
7304 The value is 1 if parsing failed because of invalid input, i.e., input
7305 that contains a syntax error or that causes @code{YYABORT} to be
7306 invoked.
7308 The value is 2 if parsing failed due to memory exhaustion.
7309 @end deftypefun
7311 In an action, you can cause immediate return from @code{yyparse} by using
7312 these macros:
7314 @defmac YYACCEPT
7315 @findex YYACCEPT
7316 Return immediately with value 0 (to report success).
7317 @end defmac
7319 @defmac YYABORT
7320 @findex YYABORT
7321 Return immediately with value 1 (to report failure).
7322 @end defmac
7324 @defmac YYNOMEM
7325 @findex YYNOMEM
7326 Return immediately with value 2 (to report memory exhaustion).
7327 @end defmac
7329 If you use a reentrant parser, you can optionally pass additional
7330 parameter information to it in a reentrant way.  To do so, use the
7331 declaration @code{%parse-param}:
7333 @deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
7334 @findex %parse-param
7335 Declare that one or more
7336 @var{argument-declaration} are additional @code{yyparse} arguments.
7337 The @var{argument-declaration} is used when declaring
7338 functions or prototypes.  The last identifier in
7339 @var{argument-declaration} must be the argument name.
7340 @end deffn
7342 Here's an example.  Write this in the parser:
7344 @example
7345 %parse-param @{int *nastiness@} @{int *randomness@}
7346 @end example
7348 @noindent
7349 Then call the parser like this:
7351 @example
7353   int nastiness, randomness;
7354   @dots{}  /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
7355   value = yyparse (&nastiness, &randomness);
7356   @dots{}
7358 @end example
7360 @noindent
7361 In the grammar actions, use expressions like this to refer to the data:
7363 @example
7364 exp: @dots{}    @{ @dots{}; *randomness += 1; @dots{} @}
7365 @end example
7367 @noindent
7368 Using the following:
7369 @example
7370 %parse-param @{int *randomness@}
7371 @end example
7373 Results in these signatures:
7374 @example
7375 void yyerror (int *randomness, const char *msg);
7376 int  yyparse (int *randomness);
7377 @end example
7379 @noindent
7380 Or, if both @code{%define api.pure full} (or just @code{%define api.pure})
7381 and @code{%locations} are used:
7383 @example
7384 void yyerror (YYLTYPE *llocp, int *randomness, const char *msg);
7385 int  yyparse (int *randomness);
7386 @end example
7388 @node Push Parser Interface
7389 @section Push Parser Interface
7391 @findex yypstate_new
7392 You call the function @code{yypstate_new} to create a new parser instance.
7393 This function is available if either the @samp{%define api.push-pull push}
7394 or @samp{%define api.push-pull both} declaration is used.  @xref{Push Decl}.
7396 @anchor{yypstate_new}
7397 @deftypefun {yypstate*} yypstate_new (@code{void})
7398 Return a valid parser instance if there is memory available, 0 otherwise.
7399 In impure mode, it will also return 0 if a parser instance is currently
7400 allocated.
7401 @end deftypefun
7403 @findex yypstate_delete
7404 You call the function @code{yypstate_delete} to delete a parser instance.
7405 function is available if either the @samp{%define api.push-pull push} or
7406 @samp{%define api.push-pull both} declaration is used.
7407 @xref{Push Decl}.
7409 @anchor{yypstate_delete}
7410 @deftypefun void yypstate_delete (@code{yypstate *}@var{yyps})
7411 Reclaim the memory associated with a parser instance.  After this call, you
7412 should no longer attempt to use the parser instance.
7413 @end deftypefun
7415 @findex yypush_parse
7416 You call the function @code{yypush_parse} to parse a single token.  This
7417 function is available if either the @samp{%define api.push-pull push} or
7418 @samp{%define api.push-pull both} declaration is used.  @xref{Push Decl}.
7420 @anchor{yypush_parse}
7421 @deftypefun int yypush_parse (@code{yypstate *}@var{yyps})
7422 The value returned by @code{yypush_parse} is the same as for @code{yyparse}
7423 with the following exception: it returns @code{YYPUSH_MORE} if more input is
7424 required to finish parsing the grammar.
7426 After @code{yypush_parse} returned, the instance may be consulted.  For
7427 instance check @code{yynerrs} to see whether there were (possibly recovered)
7428 syntax errors.
7430 After @code{yypush_parse} returns a status other than @code{YYPUSH_MORE},
7431 the parser instance @code{yyps} may be reused for a new parse.
7432 @end deftypefun
7434 The fact that the parser state is reusable even after an error simplifies
7435 reuse.  For example, a calculator application which parses each input line
7436 as an expression can just keep reusing the same @code{yyps} even if an input
7437 was invalid.
7439 You call the function @code{yypull_parse} to parse the rest of the input
7440 stream.  This function is available if the @samp{%define api.push-pull both}
7441 declaration is used.  @xref{Push Decl}.
7443 @anchor{yypull_parse}
7444 @deftypefun int yypull_parse (@code{yypstate *}@var{yyps})
7445 The value returned by @code{yypull_parse} is the same as for @code{yyparse}.
7447 The parser instance @code{yyps} may be reused for new parses.
7448 @end deftypefun
7450 @deftypefun int yypstate_expected_tokens (@code{const yypstate *}yyps, @code{yysymbol_kind_t} @var{argv}@code{[]}, @code{int} @var{argc})
7451 Fill @var{argv} with the expected tokens, which never includes
7452 @code{YYSYMBOL_YYEMPTY}, @code{YYSYMBOL_YYerror}, or
7453 @code{YYSYMBOL_YYUNDEF}.
7455 Never put more than @var{argc} elements into @var{argv}, and on success
7456 return the number of tokens stored in @var{argv}.  If there are more
7457 expected tokens than @var{argc}, fill @var{argv} up to @var{argc} and return
7458 0.  If there are no expected tokens, also return 0, but set @code{argv[0]}
7459 to @code{YYSYMBOL_YYEMPTY}.
7461 When LAC is enabled, may return a negative number on errors,
7462 such as @code{YYENOMEM} on memory exhaustion.
7464 If @var{argv} is null, return the size needed to store all the possible
7465 values, which is always less than @code{YYNTOKENS}.
7466 @end deftypefun
7469 @node Lexical
7470 @section The Lexical Analyzer Function @code{yylex}
7471 @findex yylex
7472 @cindex lexical analyzer
7474 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
7475 the input stream and returns them to the parser.  Bison does not create
7476 this function automatically; you must write it so that @code{yyparse} can
7477 call it.  The function is sometimes referred to as a lexical scanner.
7479 In simple programs, @code{yylex} is often defined at the end of the Bison
7480 grammar file.  If @code{yylex} is defined in a separate source file, you
7481 need to arrange for the token-kind definitions to be available there.  To do
7482 this, use the @option{-d} option when you run Bison, so that it will write
7483 these definitions into the separate parser header file,
7484 @file{@var{name}.tab.h}, which you can include in the other source files
7485 that need it.  @xref{Invocation}.
7487 @menu
7488 * Calling Convention::  How @code{yyparse} calls @code{yylex}.
7489 * Special Tokens::      Signaling end-of-file and errors to the parser.
7490 * Tokens from Literals:: Finding token kinds from string aliases.
7491 * Token Values::        How @code{yylex} must return the semantic value
7492                           of the token it has read.
7493 * Token Locations::     How @code{yylex} must return the text location
7494                           (line number, etc.) of the token, if the
7495                           actions want that.
7496 * Pure Calling::        How the calling convention differs in a pure parser
7497                           (@pxref{Pure Decl}).
7498 @end menu
7500 @node Calling Convention
7501 @subsection Calling Convention for @code{yylex}
7503 The value that @code{yylex} returns must be the positive numeric code for
7504 the kind of token it has just found; a zero or negative value signifies
7505 end-of-input.
7507 When a token kind is referred to in the grammar rules by a name, that name
7508 in the parser implementation file becomes an enumerator of the enum
7509 @code{yytoken_kind_t} whose definition is the proper numeric code for that
7510 token kind.  So @code{yylex} should use the name to indicate that type.
7511 @xref{Symbols}.
7513 When a token is referred to in the grammar rules by a character literal, the
7514 numeric code for that character is also the code for the token kind.  So
7515 @code{yylex} can simply return that character code, possibly converted to
7516 @code{unsigned char} to avoid sign-extension.  The null character must not
7517 be used this way, because its code is zero and that signifies end-of-input.
7519 A simple program might use the following declaration:
7521 @example
7522 %code provides @{
7523   int yylex (void);
7525 @end example
7527 @noindent
7528 and the following definition, either in the grammar file itself or in some
7529 other module that has @code{#include "y.tab.h"}:
7531 @example
7532 #include <stdio.h>
7535 yylex (void)
7537   for (;;)
7538     @{
7539       int c = getchar ();
7540       if (c == EOF)
7541         return YYEOF;  /* Report end-of-input. */
7542       if (c == '+' || c == '-')
7543         return c;      /* Assume token kind for '+' is '+'. */
7544       if ('0' <= c && c <= '9')
7545         @{
7546           yylval = c - '0';
7547           while ('0' <= (c = getchar ()) && c <= '9')
7548             yylval = yylval * 10 + (c - '0');
7549           ungetc (c, stdin);
7550           return INT;  /* Return the kind of the token. */
7551         @}
7552       @dots{}
7553     @}
7555 @end example
7557 @noindent
7558 This interface has been designed so that the output from the @code{lex}
7559 utility can be used without change as the definition of @code{yylex}.
7562 @node Special Tokens
7563 @subsection Special Tokens
7565 In addition to the user defined tokens, Bison generates a few special tokens
7566 that @code{yylex} may return.
7568 @findex YYEOF
7569 The @code{YYEOF} token denotes the end of file, and signals to the parser
7570 that there is nothing left afterwards.  @xref{Calling Convention}, for an
7571 example.
7573 @findex YYUNDEF
7574 Returning @code{YYUNDEF} tells the parser that some lexical error was found.
7575 It will emit an error message about an ``invalid token'', and enter
7576 error-recovery (@pxref{Error Recovery}).  Returning an unknown token kind
7577 results in the exact same behavior.
7579 @findex YYerror
7580 Returning @code{YYerror} requires the parser to enter error-recovery
7581 @emph{without} emitting an error message.  This way the lexical analyzer can
7582 produce an accurate error messages about the invalid input (something the
7583 parser cannot do), and yet benefit from the error-recovery features of the
7584 parser.
7586 @example
7588 yylex (void)
7590   @dots{}
7591   switch (c)
7592     @{
7593       @dots{}
7594       case '0': case '1': case '2': case '3': case '4':
7595       case '5': case '6': case '7': case '8': case '9':
7596         @dots{}
7597         return TOK_NUM;
7598       @dots{}
7599       case EOF:
7600         return YYEOF;
7601       default:
7602         yyerror ("syntax error: invalid character: %c", c);
7603         return YYerror;
7604     @}
7606 @end example
7608 @node Tokens from Literals
7609 @subsection Finding Tokens by String Literals
7611 If the grammar uses literal string tokens, there are two ways that
7612 @code{yylex} can determine the token kind codes for them:
7614 @itemize @bullet
7615 @item
7616 If the grammar defines symbolic token names as aliases for the literal
7617 string tokens, @code{yylex} can use these symbolic names like all others.
7618 In this case, the use of the literal string tokens in the grammar file has
7619 no effect on @code{yylex}.
7621 This is the preferred approach.
7623 @item
7624 @code{yylex} can search for the multicharacter token in the @code{yytname}
7625 table.  This method is discouraged: the primary purpose of string aliases is
7626 forging good error messages, not describing the spelling of keywords.  In
7627 addition, looking for the token kind at runtime incurs a (small but
7628 noticeable) cost.
7630 The @code{yytname} table is generated only if you use the
7631 @code{%token-table} declaration.  @xref{Decl Summary}.
7632 @end itemize
7635 @node Token Values
7636 @subsection Semantic Values of Tokens
7638 @vindex yylval
7639 In an ordinary (nonreentrant) parser, the semantic value of the token must
7640 be stored into the global variable @code{yylval}.  When you are using just
7641 one data type for semantic values, @code{yylval} has that type.  Thus, if
7642 the type is @code{int} (the default), you might write this in @code{yylex}:
7644 @example
7645 @group
7646   @dots{}
7647   yylval = value;  /* Put value onto Bison stack. */
7648   return INT;      /* Return the kind of the token. */
7649   @dots{}
7650 @end group
7651 @end example
7653 When you are using multiple data types, @code{yylval}'s type is a union made
7654 from the @code{%union} declaration (@pxref{Union Decl}).  So when you store
7655 a token's value, you must use the proper member of the union.  If the
7656 @code{%union} declaration looks like this:
7658 @example
7659 @group
7660 %union @{
7661   int intval;
7662   double val;
7663   symrec *tptr;
7665 @end group
7666 @end example
7668 @noindent
7669 then the code in @code{yylex} might look like this:
7671 @example
7672 @group
7673   @dots{}
7674   yylval.intval = value; /* Put value onto Bison stack. */
7675   return INT;            /* Return the kind of the token. */
7676   @dots{}
7677 @end group
7678 @end example
7680 @node Token Locations
7681 @subsection Textual Locations of Tokens
7683 @vindex yylloc
7684 If you are using the @samp{@@@var{n}}-feature (@pxref{Tracking Locations})
7685 in actions to keep track of the textual locations of tokens and groupings,
7686 then you must provide this information in @code{yylex}.  The function
7687 @code{yyparse} expects to find the textual location of a token just parsed
7688 in the global variable @code{yylloc}.  So @code{yylex} must store the proper
7689 data in that variable.
7691 By default, the value of @code{yylloc} is a structure and you need only
7692 initialize the members that are going to be used by the actions.  The
7693 four members are called @code{first_line}, @code{first_column},
7694 @code{last_line} and @code{last_column}.  Note that the use of this
7695 feature makes the parser noticeably slower.
7697 @tindex YYLTYPE
7698 The data type of @code{yylloc} has the name @code{YYLTYPE}.
7700 @node Pure Calling
7701 @subsection Calling Conventions for Pure Parsers
7703 When you use the Bison declaration @code{%define api.pure full} to request a
7704 pure, reentrant parser, the global communication variables @code{yylval} and
7705 @code{yylloc} cannot be used.  (@xref{Pure Decl}.)  In such parsers the two
7706 global variables are replaced by pointers passed as arguments to
7707 @code{yylex}.  You must declare them as shown here, and pass the information
7708 back by storing it through those pointers.
7710 @example
7712 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
7714   @dots{}
7715   *lvalp = value;  /* Put value onto Bison stack. */
7716   return INT;      /* Return the kind of the token. */
7717   @dots{}
7719 @end example
7721 If the grammar file does not use the @samp{@@} constructs to refer to
7722 textual locations, then the type @code{YYLTYPE} will not be defined.  In
7723 this case, omit the second argument; @code{yylex} will be called with
7724 only one argument.
7726 If you wish to pass additional arguments to @code{yylex}, use
7727 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
7728 Function}).  To pass additional arguments to both @code{yylex} and
7729 @code{yyparse}, use @code{%param}.
7731 @deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
7732 @findex %lex-param
7733 Specify that @var{argument-declaration} are additional @code{yylex} argument
7734 declarations.  You may pass one or more such declarations, which is
7735 equivalent to repeating @code{%lex-param}.
7736 @end deffn
7738 @deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
7739 @findex %param
7740 Specify that @var{argument-declaration} are additional
7741 @code{yylex}/@code{yyparse} argument declaration.  This is equivalent to
7742 @samp{%lex-param @{@var{argument-declaration}@} @dots{} %parse-param
7743 @{@var{argument-declaration}@} @dots{}}.  You may pass one or more
7744 declarations, which is equivalent to repeating @code{%param}.
7745 @end deffn
7747 @noindent
7748 For instance:
7750 @example
7751 %lex-param   @{scanner_mode *mode@}
7752 %parse-param @{parser_mode *mode@}
7753 %param       @{environment_type *env@}
7754 @end example
7756 @noindent
7757 results in the following signatures:
7759 @example
7760 int yylex   (scanner_mode *mode, environment_type *env);
7761 int yyparse (parser_mode *mode, environment_type *env);
7762 @end example
7764 If @samp{%define api.pure full} is added:
7766 @example
7767 int yylex   (YYSTYPE *lvalp, scanner_mode *mode, environment_type *env);
7768 int yyparse (parser_mode *mode, environment_type *env);
7769 @end example
7771 @noindent
7772 and finally, if both @samp{%define api.pure full} and @code{%locations} are
7773 used:
7775 @example
7776 int yylex   (YYSTYPE *lvalp, YYLTYPE *llocp,
7777              scanner_mode *mode, environment_type *env);
7778 int yyparse (parser_mode *mode, environment_type *env);
7779 @end example
7782 @node Error Reporting
7783 @section Error Reporting
7785 During its execution the parser may have error messages to pass to the user,
7786 such as syntax error, or memory exhaustion.  How this message is delivered
7787 to the user must be specified by the developer.
7789 @menu
7790 * Error Reporting Function::         You must supply a @code{yyerror} function.
7791 * Syntax Error Reporting Function::  You can supply a @code{yyreport_syntax_error} function.
7792 @end menu
7794 @node Error Reporting Function
7795 @subsection The Error Reporting Function @code{yyerror}
7796 @cindex error reporting function
7797 @findex yyerror
7798 @cindex parse error
7799 @cindex syntax error
7801 The Bison parser detects a @dfn{syntax error} (or @dfn{parse error})
7802 whenever it reads a token which cannot satisfy any syntax rule.  An
7803 action in the grammar can also explicitly proclaim an error, using the
7804 macro @code{YYERROR} (@pxref{Action Features}).
7806 The Bison parser expects to report the error by calling an error
7807 reporting function named @code{yyerror}, which you must supply.  It is
7808 called by @code{yyparse} whenever a syntax error is found, and it
7809 receives one argument.  For a syntax error, the string is normally
7810 @w{@code{"syntax error"}}.
7812 @findex %define parse.error detailed
7813 @findex %define parse.error verbose
7814 If you invoke @samp{%define parse.error detailed} (or @samp{custom}) in the
7815 Bison declarations section (@pxref{Bison Declarations}), then Bison provides
7816 a more verbose and specific error message string instead of just plain
7817 @w{@code{"syntax error"}}.  However, that message sometimes contains
7818 incorrect information if LAC is not enabled (@pxref{LAC}).
7820 The parser can detect one other kind of error: memory exhaustion.  This
7821 can happen when the input contains constructions that are very deeply
7822 nested.  It isn't likely you will encounter this, since the Bison
7823 parser normally extends its stack automatically up to a very large limit.  But
7824 if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
7825 fashion, except that the argument string is @w{@code{"memory exhausted"}}.
7827 In some cases diagnostics like @w{@code{"syntax error"}} are
7828 translated automatically from English to some other language before
7829 they are passed to @code{yyerror}.  @xref{Internationalization}.
7831 A simple program might use the following declaration:
7833 @example
7834 %code provides @{
7835   void yyerror (char const *);
7837 @end example
7839 @noindent
7840 and the following definition, either in the grammar file itself or in some
7841 other module that has @code{#include "y.tab.h"}:
7843 @example
7844 @group
7845 #include <stdio.h>
7847 void
7848 yyerror (char const *s)
7850 @end group
7851 @group
7852   fprintf (stderr, "%s\n", s);
7854 @end group
7855 @end example
7857 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
7858 error recovery if you have written suitable error recovery grammar rules
7859 (@pxref{Error Recovery}).  If recovery is impossible, @code{yyparse} will
7860 immediately return 1.
7862 Obviously, in location tracking pure parsers, @code{yyerror} should have
7863 an access to the current location. With @code{%define api.pure}, this is
7864 indeed the case for the GLR parsers, but not for the Yacc parser, for
7865 historical reasons, and this is the why @code{%define api.pure full} should be
7866 preferred over @code{%define api.pure}.
7868 When @code{%locations %define api.pure full} is used, @code{yyerror} has the
7869 following signature:
7871 @example
7872 void yyerror (YYLTYPE *locp, char const *msg);
7873 @end example
7875 @noindent
7876 The prototypes are only indications of how the code produced by Bison
7877 uses @code{yyerror}.  Bison-generated code always ignores the returned
7878 value, so @code{yyerror} can return any type, including @code{void}.
7879 Also, @code{yyerror} can be a variadic function; that is why the
7880 message is always passed last.
7882 Traditionally @code{yyerror} returns an @code{int} that is always
7883 ignored, but this is purely for historical reasons, and @code{void} is
7884 preferable since it more accurately describes the return type for
7885 @code{yyerror}.
7887 @vindex yynerrs
7888 The variable @code{yynerrs} contains the number of syntax errors
7889 reported so far.  Normally this variable is global; but if you
7890 request a pure parser (@pxref{Pure Decl})
7891 then it is a local variable which only the actions can access.
7894 @node Syntax Error Reporting Function
7895 @subsection The Syntax Error Reporting Function @code{yyreport_syntax_error}
7897 @findex %define parse.error custom
7898 If you invoke @samp{%define parse.error custom} (@pxref{Bison
7899 Declarations}), then the parser no longer passes syntax error messages to
7900 @code{yyerror}, rather it delegates that task to the user by calling the
7901 @code{yyreport_syntax_error} function.
7903 The following functions and types are ``@code{static}'': they are defined in
7904 the implementation file (@file{*.c}) and available only from there.  They
7905 are meant to be used from the grammar's epilogue.
7907 @deftypefun {static int} yyreport_syntax_error (@code{const yypcontext_t *}@var{ctx})
7908 Report a syntax error to the user.  Return 0 on success, @code{YYENOMEM} on
7909 memory exhaustion.  Whether it uses @code{yyerror} is up to the user.
7910 @end deftypefun
7912 Use the following types and functions to build the error message.
7914 @deffn {Type} yypcontext_t
7915 An opaque type that captures the circumstances of the syntax error.
7916 @end deffn
7918 @deffn {Type} yysymbol_kind_t
7919 An enum of all the grammar symbols, tokens and nonterminals.  Its
7920 enumerators are forged from the symbol names:
7922 @example
7923 enum yysymbol_kind_t
7925   YYSYMBOL_YYEMPTY = -2,      /* No symbol.  */
7926   YYSYMBOL_YYEOF = 0,         /* "end of file"  */
7927   YYSYMBOL_YYerror = 1,       /* error  */
7928   YYSYMBOL_YYUNDEF = 2,       /* "invalid token"  */
7929   YYSYMBOL_PLUS = 3,          /* "+"  */
7930   YYSYMBOL_MINUS = 4,         /* "-"  */
7931   [...]
7932   YYSYMBOL_VAR = 14,          /* "variable"  */
7933   YYSYMBOL_NEG = 15,          /* NEG  */
7934   YYSYMBOL_YYACCEPT = 16,     /* $accept  */
7935   YYSYMBOL_exp = 17,          /* exp  */
7936   YYSYMBOL_input = 18         /* input  */
7938 typedef enum yysymbol_kind_t yysymbol_kind_t;
7939 @end example
7940 @end deffn
7942 @deftypefun {static yysymbol_kind_t} yypcontext_token (@code{const yypcontext_t *}@var{ctx})
7943 The ``unexpected'' token: the symbol kind of the lookahead token that caused
7944 the syntax error.  Returns @code{YYSYMBOL_YYEMPTY} if there is no lookahead.
7945 @end deftypefun
7947 @deftypefun {static YYLTYPE *} yypcontext_location (@code{const yypcontext_t *}@var{ctx})
7948 The location of the syntax error (that of the unexpected token).
7949 @end deftypefun
7951 @deftypefun {static int} yypcontext_expected_tokens (@code{const yypcontext_t *}ctx, @code{yysymbol_kind_t} @var{argv}@code{[]}, @code{int} @var{argc})
7952 Fill @var{argv} with the expected tokens, which never includes
7953 @code{YYSYMBOL_YYEMPTY}, @code{YYSYMBOL_YYerror}, or
7954 @code{YYSYMBOL_YYUNDEF}.
7956 Never put more than @var{argc} elements into @var{argv}, and on success
7957 return the number of tokens stored in @var{argv}.  If there are more
7958 expected tokens than @var{argc}, fill @var{argv} up to @var{argc} and return
7959 0.  If there are no expected tokens, also return 0, but set @code{argv[0]}
7960 to @code{YYSYMBOL_YYEMPTY}.
7962 When LAC is enabled, may return a negative number on errors,
7963 such as @code{YYENOMEM} on memory exhaustion.
7965 If @var{argv} is null, return the size needed to store all the possible
7966 values, which is always less than @code{YYNTOKENS}.
7967 @end deftypefun
7969 @deftypefun {static const char *} yysymbol_name (@code{symbol_kind_t} @var{symbol})
7970 The name of the symbol whose kind is @var{symbol}, possibly translated.
7971 @end deftypefun
7973 A custom syntax error function looks as follows.  This implementation is
7974 inappropriate for internationalization, see the @file{c/bistromathic}
7975 example for a better alternative.
7977 @example
7978 static int
7979 yyreport_syntax_error (const yypcontext_t *ctx)
7981   int res = 0;
7982   YYLOCATION_PRINT (stderr, *yypcontext_location (ctx));
7983   fprintf (stderr, ": syntax error");
7984   // Report the tokens expected at this point.
7985   @{
7986     enum @{ TOKENMAX = 5 @};
7987     yysymbol_kind_t expected[TOKENMAX];
7988     int n = yypcontext_expected_tokens (ctx, expected, TOKENMAX);
7989     if (n < 0)
7990       // Forward errors to yyparse.
7991       res = n;
7992     else
7993       for (int i = 0; i < n; ++i)
7994         fprintf (stderr, "%s %s",
7995                  i == 0 ? ": expected" : " or", yysymbol_name (expected[i]));
7996   @}
7997   // Report the unexpected token.
7998   @{
7999     yysymbol_kind_t lookahead = yypcontext_token (ctx);
8000     if (lookahead != YYSYMBOL_YYEMPTY)
8001       fprintf (stderr, " before %s", yysymbol_name (lookahead));
8002   @}
8003   fprintf (stderr, "\n");
8004   return res;
8006 @end example
8008 You still must provide a @code{yyerror} function, used for instance to
8009 report memory exhaustion.
8011 @node Action Features
8012 @section Special Features for Use in Actions
8013 @cindex summary, action features
8014 @cindex action features summary
8016 Here is a table of Bison constructs, variables and macros that are useful in
8017 actions.
8019 @deffn {Variable} $$
8020 Acts like a variable that contains the semantic value for the
8021 grouping made by the current rule.  @xref{Actions}.
8022 @end deffn
8024 @deffn {Variable} $@var{n}
8025 Acts like a variable that contains the semantic value for the
8026 @var{n}th component of the current rule.  @xref{Actions}.
8027 @end deffn
8029 @deffn {Variable} $<@var{typealt}>$
8030 Like @code{$$} but specifies alternative @var{typealt} in the union
8031 specified by the @code{%union} declaration.  @xref{Action Types}.
8032 @end deffn
8034 @deffn {Variable} $<@var{typealt}>@var{n}
8035 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
8036 union specified by the @code{%union} declaration.
8037 @xref{Action Types}.
8038 @end deffn
8040 @deffn {Macro} YYABORT @code{;}
8041 Return immediately from @code{yyparse}, indicating failure.
8042 @xref{Parser Function}.
8043 @end deffn
8045 @deffn {Macro} YYACCEPT @code{;}
8046 Return immediately from @code{yyparse}, indicating success.
8047 @xref{Parser Function}.
8048 @end deffn
8050 @deffn {Macro} YYBACKUP (@var{token}, @var{value})@code{;}
8051 @findex YYBACKUP
8052 Unshift a token.  This macro is allowed only for rules that reduce
8053 a single value, and only when there is no lookahead token.
8054 It is also disallowed in GLR parsers.
8055 It installs a lookahead token with token kind @var{token} and
8056 semantic value @var{value}; then it discards the value that was
8057 going to be reduced by this rule.
8059 If the macro is used when it is not valid, such as when there is
8060 a lookahead token already, then it reports a syntax error with
8061 a message @samp{cannot back up} and performs ordinary error
8062 recovery.
8064 In either case, the rest of the action is not executed.
8065 @end deffn
8067 @deffn {Value} YYEMPTY
8068 Value stored in @code{yychar} when there is no lookahead token.
8069 @end deffn
8071 @deffn {Value} YYEOF
8072 Value stored in @code{yychar} when the lookahead is the end of the input
8073 stream.
8074 @end deffn
8076 @deffn {Macro} YYERROR @code{;}
8077 Cause an immediate syntax error.  This statement initiates error
8078 recovery just as if the parser itself had detected an error; however, it
8079 does not call @code{yyerror}, and does not print any message.  If you
8080 want to print an error message, call @code{yyerror} explicitly before
8081 the @samp{YYERROR;} statement.  @xref{Error Recovery}.
8082 @end deffn
8084 @deffn {Macro} YYNOMEM @code{;}
8085 Return immediately from @code{yyparse}, indicating memory exhaustion.
8086 @xref{Parser Function}.
8087 @end deffn
8089 @deffn {Macro} YYRECOVERING
8090 @findex YYRECOVERING
8091 The expression @code{YYRECOVERING ()} yields 1 when the parser
8092 is recovering from a syntax error, and 0 otherwise.
8093 @xref{Error Recovery}.
8094 @end deffn
8096 @deffn {Variable} yychar
8097 Variable containing either the lookahead token, or @code{YYEOF} when the
8098 lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
8099 has been performed so the next token is not yet known.
8100 Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
8101 Actions}).
8102 @xref{Lookahead}.
8103 @end deffn
8105 @deffn {Macro} yyclearin @code{;}
8106 Discard the current lookahead token.  This is useful primarily in
8107 error rules.
8108 Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
8109 Semantic Actions}).
8110 @xref{Error Recovery}.
8111 @end deffn
8113 @deffn {Macro} yyerrok @code{;}
8114 Resume generating error messages immediately for subsequent syntax
8115 errors.  This is useful primarily in error rules.
8116 @xref{Error Recovery}.
8117 @end deffn
8119 @deffn {Variable} yylloc
8120 Variable containing the lookahead token location when @code{yychar} is not set
8121 to @code{YYEMPTY} or @code{YYEOF}.
8122 Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
8123 Actions}).
8124 @xref{Actions and Locations}.
8125 @end deffn
8127 @deffn {Variable} yylval
8128 Variable containing the lookahead token semantic value when @code{yychar} is
8129 not set to @code{YYEMPTY} or @code{YYEOF}.
8130 Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
8131 Actions}).
8132 @xref{Actions}.
8133 @end deffn
8135 @deffn {Value} @@$
8136 Acts like a structure variable containing information on the textual
8137 location of the grouping made by the current rule.  @xref{Tracking
8138 Locations}.
8140 @c Check if those paragraphs are still useful or not.
8142 @c @example
8143 @c struct @{
8144 @c   int first_line, last_line;
8145 @c   int first_column, last_column;
8146 @c @};
8147 @c @end example
8149 @c Thus, to get the starting line number of the third component, you would
8150 @c use @samp{@@3.first_line}.
8152 @c In order for the members of this structure to contain valid information,
8153 @c you must make @code{yylex} supply this information about each token.
8154 @c If you need only certain members, then @code{yylex} need only fill in
8155 @c those members.
8157 @c The use of this feature makes the parser noticeably slower.
8158 @end deffn
8160 @deffn {Value} @@@var{n}
8161 @findex @@@var{n}
8162 Acts like a structure variable containing information on the textual
8163 location of the @var{n}th component of the current rule.  @xref{Tracking
8164 Locations}.
8165 @end deffn
8167 @node Internationalization
8168 @section Parser Internationalization
8169 @cindex internationalization
8170 @cindex i18n
8171 @cindex NLS
8172 @cindex gettext
8173 @cindex bison-po
8175 A Bison-generated parser can print diagnostics, including error and
8176 tracing messages.  By default, they appear in English.  However, Bison
8177 also supports outputting diagnostics in the user's native language.  To
8178 make this work, the user should set the usual environment variables.
8179 @xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
8180 For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
8181 set the user's locale to French Canadian using the UTF-8
8182 encoding.  The exact set of available locales depends on the user's
8183 installation.
8185 @menu
8186 * Enabling I18n::    Preparing your project to support internationalization.
8187 * Token I18n::       Preparing tokens for internationalization in error messages.
8188 @end menu
8190 @node Enabling I18n
8191 @subsection Enabling Internationalization
8193 The maintainer of a package that uses a Bison-generated parser enables
8194 the internationalization of the parser's output through the following
8195 steps.  Here we assume a package that uses GNU Autoconf and
8196 GNU Automake.
8198 @enumerate
8199 @item
8200 @cindex bison-i18n.m4
8201 Into the directory containing the GNU Autoconf macros used
8202 by the package ---often called @file{m4}--- copy the
8203 @file{bison-i18n.m4} file installed by Bison under
8204 @samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
8205 For example:
8207 @example
8208 cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
8209 @end example
8211 @item
8212 @findex BISON_I18N
8213 @vindex BISON_LOCALEDIR
8214 @vindex YYENABLE_NLS
8215 In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
8216 invocation, add an invocation of @code{BISON_I18N}.  This macro is
8217 defined in the file @file{bison-i18n.m4} that you copied earlier.  It
8218 causes @code{configure} to find the value of the
8219 @code{BISON_LOCALEDIR} variable, and it defines the source-language
8220 symbol @code{YYENABLE_NLS} to enable translations in the
8221 Bison-generated parser.
8223 @item
8224 In the @code{main} function of your program, designate the directory
8225 containing Bison's runtime message catalog, through a call to
8226 @samp{bindtextdomain} with domain name @samp{bison-runtime}.
8227 For example:
8229 @example
8230 bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
8231 @end example
8233 Typically this appears after any other call @code{bindtextdomain
8234 (PACKAGE, LOCALEDIR)} that your package already has.  Here we rely on
8235 @samp{BISON_LOCALEDIR} to be defined as a string through the
8236 @file{Makefile}.
8238 @item
8239 In the @file{Makefile.am} that controls the compilation of the @code{main}
8240 function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
8241 either in @samp{DEFS} or in @samp{AM_CPPFLAGS}.  For example:
8243 @example
8244 DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
8245 @end example
8249 @example
8250 AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
8251 @end example
8253 @item
8254 Finally, invoke the command @command{autoreconf} to generate the build
8255 infrastructure.
8256 @end enumerate
8258 @node Token I18n
8259 @subsection Token Internationalization
8261 When the @code{%define} variable @code{parse.error} is set to @code{custom}
8262 or @code{detailed}, token aliases can be internationalized:
8264 @example
8265 %token
8266     '\n'   _("end of line")
8267   <double>
8268     NUM    _("number")
8269   <symrec*>
8270     FUN    _("function")
8271     VAR    _("variable")
8272 @end example
8274 The remainder of the grammar may freely use either the token symbol
8275 (@code{FUN}) or its alias (@code{"function"}), but not with the
8276 internationalization marker (@code{_("function")}).
8278 If at least one token alias is internationalized, then the generated parser
8279 will use both @code{N_} and @code{_}, that must be defined
8280 (@pxref{Programmers, , The Programmer’s View, gettext, GNU @code{gettext}
8281 utilities}).  They are used only on string aliases marked for translation.
8282 In other words, even if your catalog features a translation for
8283 ``function'', then with
8285 @example
8286 %token
8287   <symrec*>
8288     FUN      "function"
8289     VAR    _("variable")
8290 @end example
8292 @noindent
8293 ``function'' will appear untranslated in debug traces and error messages.
8295 Unless defined by the user, the end-of-file token, @code{YYEOF}, is provided
8296 ``end of file'' as an alias.  It is also internationalized if the user
8297 internationalized tokens.  To map it to another string, use:
8299 @example
8300 %token END 0 _("end of input")
8301 @end example
8304 @node Algorithm
8305 @chapter The Bison Parser Algorithm
8306 @cindex Bison parser algorithm
8307 @cindex algorithm of parser
8308 @cindex shifting
8309 @cindex reduction
8310 @cindex parser stack
8311 @cindex stack, parser
8313 As Bison reads tokens, it pushes them onto a stack along with their
8314 semantic values.  The stack is called the @dfn{parser stack}.  Pushing a
8315 token is traditionally called @dfn{shifting}.
8317 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
8318 @samp{3} to come.  The stack will have four elements, one for each token
8319 that was shifted.
8321 But the stack does not always have an element for each token read.  When
8322 the last @var{n} tokens and groupings shifted match the components of a
8323 grammar rule, they can be combined according to that rule.  This is called
8324 @dfn{reduction}.  Those tokens and groupings are replaced on the stack by a
8325 single grouping whose symbol is the result (left hand side) of that rule.
8326 Running the rule's action is part of the process of reduction, because this
8327 is what computes the semantic value of the resulting grouping.
8329 For example, if the infix calculator's parser stack contains this:
8331 @example
8332 1 + 5 * 3
8333 @end example
8335 @noindent
8336 and the next input token is a newline character, then the last three
8337 elements can be reduced to 15 via the rule:
8339 @example
8340 expr: expr '*' expr;
8341 @end example
8343 @noindent
8344 Then the stack contains just these three elements:
8346 @example
8347 1 + 15
8348 @end example
8350 @noindent
8351 At this point, another reduction can be made, resulting in the single value
8352 16.  Then the newline token can be shifted.
8354 The parser tries, by shifts and reductions, to reduce the entire input down
8355 to a single grouping whose symbol is the grammar's start-symbol
8356 (@pxref{Language and Grammar}).
8358 This kind of parser is known in the literature as a bottom-up parser.
8360 @menu
8361 * Lookahead::         Parser looks one token ahead when deciding what to do.
8362 * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
8363 * Precedence::        Operator precedence works by resolving conflicts.
8364 * Contextual Precedence::  When an operator's precedence depends on context.
8365 * Parser States::     The parser is a finite-state-machine with stack.
8366 * Reduce/Reduce::     When two rules are applicable in the same situation.
8367 * Mysterious Conflicts:: Conflicts that look unjustified.
8368 * Tuning LR::         How to tune fundamental aspects of LR-based parsing.
8369 * Generalized LR Parsing::  Parsing arbitrary context-free grammars.
8370 * Memory Management:: What happens when memory is exhausted.  How to avoid it.
8371 @end menu
8373 @node Lookahead
8374 @section Lookahead Tokens
8375 @cindex lookahead token
8377 The Bison parser does @emph{not} always reduce immediately as soon as the
8378 last @var{n} tokens and groupings match a rule.  This is because such a
8379 simple strategy is inadequate to handle most languages.  Instead, when a
8380 reduction is possible, the parser sometimes ``looks ahead'' at the next
8381 token in order to decide what to do.
8383 When a token is read, it is not immediately shifted; first it becomes the
8384 @dfn{lookahead token}, which is not on the stack.  Now the parser can
8385 perform one or more reductions of tokens and groupings on the stack, while
8386 the lookahead token remains off to the side.  When no more reductions
8387 should take place, the lookahead token is shifted onto the stack.  This
8388 does not mean that all possible reductions have been done; depending on the
8389 token kind of the lookahead token, some rules may choose to delay their
8390 application.
8392 Here is a simple case where lookahead is needed.  These three rules define
8393 expressions which contain binary addition operators and postfix unary
8394 factorial operators (@samp{!}), and allow parentheses for grouping.
8396 @example
8397 @group
8398 expr:
8399   term '+' expr
8400 | term
8402 @end group
8404 @group
8405 term:
8406   '(' expr ')'
8407 | term '!'
8408 | "number"
8410 @end group
8411 @end example
8413 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
8414 should be done?  If the following token is @samp{)}, then the first three
8415 tokens must be reduced to form an @code{expr}.  This is the only valid
8416 course, because shifting the @samp{)} would produce a sequence of symbols
8417 @w{@code{term ')'}}, and no rule allows this.
8419 If the following token is @samp{!}, then it must be shifted immediately so
8420 that @w{@samp{2 !}} can be reduced to make a @code{term}.  If instead the
8421 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
8422 @code{expr}.  It would then be impossible to shift the @samp{!} because
8423 doing so would produce on the stack the sequence of symbols @code{expr
8424 '!'}.  No rule allows that sequence.
8426 @vindex yychar
8427 @vindex yylval
8428 @vindex yylloc
8429 The lookahead token is stored in the variable @code{yychar}.  Its semantic
8430 value and location, if any, are stored in the variables @code{yylval} and
8431 @code{yylloc}.  @xref{Action Features}.
8433 @node Shift/Reduce
8434 @section Shift/Reduce Conflicts
8435 @cindex conflicts
8436 @cindex shift/reduce conflicts
8437 @cindex dangling @code{else}
8438 @cindex @code{else}, dangling
8440 Suppose we are parsing a language which has if-then and if-then-else
8441 statements, with a pair of rules like this:
8443 @example
8444 @group
8445 if_stmt:
8446   "if" expr "then" stmt
8447 | "if" expr "then" stmt "else" stmt
8449 @end group
8450 @end example
8452 @noindent
8453 Here @code{"if"}, @code{"then"} and @code{"else"} are terminal symbols for
8454 specific keyword tokens.
8456 When the @code{"else"} token is read and becomes the lookahead token, the
8457 contents of the stack (assuming the input is valid) are just right for
8458 reduction by the first rule.  But it is also legitimate to shift the
8459 @code{"else"}, because that would lead to eventual reduction by the second
8460 rule.
8462 This situation, where either a shift or a reduction would be valid, is
8463 called a @dfn{shift/reduce conflict}.  Bison is designed to resolve
8464 these conflicts by choosing to shift, unless otherwise directed by
8465 operator precedence declarations.  To see the reason for this, let's
8466 contrast it with the other alternative.
8468 Since the parser prefers to shift the @code{"else"}, the result is to attach
8469 the else-clause to the innermost if-statement, making these two inputs
8470 equivalent:
8472 @example
8473 if x then if y then win; else lose;
8475 if x then do; if y then win; else lose; end;
8476 @end example
8478 But if the parser chose to reduce when possible rather than shift, the
8479 result would be to attach the else-clause to the outermost if-statement,
8480 making these two inputs equivalent:
8482 @example
8483 if x then if y then win; else lose;
8485 if x then do; if y then win; end; else lose;
8486 @end example
8488 The conflict exists because the grammar as written is ambiguous: either
8489 parsing of the simple nested if-statement is legitimate.  The established
8490 convention is that these ambiguities are resolved by attaching the
8491 else-clause to the innermost if-statement; this is what Bison accomplishes
8492 by choosing to shift rather than reduce.  (It would ideally be cleaner to
8493 write an unambiguous grammar, but that is very hard to do in this case.)
8494 This particular ambiguity was first encountered in the specifications of
8495 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
8497 To assist the grammar author in understanding the nature of each conflict,
8498 Bison can be asked to generate ``counterexamples''.  In the present case it
8499 actually even proves that the grammar is ambiguous by exhibiting a string
8500 with two different parses:
8502 @macro danglingElseCex
8503 @group
8504 @ifnottex
8505   Example: @yellow{"if" expr "then"} @blue{"if" expr "then" stmt} @red{•} @blue{"else" stmt}
8506   Shift derivation
8507     @yellow{if_stmt}
8508     @yellow{↳ 3: "if" expr "then"} @green{stmt}
8509                            @green{↳ 2:} @blue{if_stmt}
8510                                  @blue{↳ 4: "if" expr "then" stmt} @red{•} @blue{"else" stmt}
8511   Example: @yellow{"if" expr "then"} @blue{"if" expr "then" stmt} @red{•} @yellow{"else" stmt}
8512   Reduce derivation
8513     @yellow{if_stmt}
8514     @yellow{↳ 4: "if" expr "then"} @green{stmt}                                @yellow{"else" stmt}
8515                            @green{↳ 2:} @blue{if_stmt}
8516                                  @blue{↳ 3: "if" expr "then" stmt} @red{•}
8517 @end ifnottex
8518 @iftex
8519   Example: @yellow{"if" expr "then"} @blue{"if" expr "then" stmt} @red{•} @blue{"else" stmt}
8520   Shift derivation
8521     @yellow{if_stmt}
8522     @yellow{@arrow{} 3: "if" expr "then"} @green{stmt}
8523                            @green{@arrow{} 2:} @blue{if_stmt}
8524                                  @blue{@arrow{} 4: "if" expr "then" stmt} @red{•} @blue{"else" stmt}
8525   Example: @yellow{"if" expr "then"} @blue{"if" expr "then" stmt} @red{•} @yellow{"else" stmt}
8526   Reduce derivation
8527     @yellow{if_stmt}
8528     @yellow{@arrow{} 4: "if" expr "then"} @green{stmt}                                @yellow{"else" stmt}
8529                            @green{@arrow{} 2:} @blue{if_stmt}
8530                                  @blue{@arrow{} 3: "if" expr "then" stmt} @red{•}
8531 @end iftex
8532 @end group
8533 @end macro
8534 @example
8535 @danglingElseCex
8536 @end example
8538 @noindent
8539 @xref{Counterexamples}, for more details.
8541 @sp 1
8543 To avoid warnings from Bison about predictable, @emph{legitimate} shift/reduce
8544 conflicts, you can use the @code{%expect @var{n}} declaration.
8545 There will be no warning as long as the number of shift/reduce conflicts
8546 is exactly @var{n}, and Bison will report an error if there is a
8547 different number.
8548 @xref{Expect Decl}.  However, we don't
8549 recommend the use of @code{%expect} (except @samp{%expect 0}!), as an equal
8550 number of conflicts does not mean that they are the @emph{same}.  When
8551 possible, you should rather use precedence directives to @emph{fix} the
8552 conflicts explicitly (@pxref{Non Operators}).
8554 The definition of @code{if_stmt} above is solely to blame for the
8555 conflict, but the conflict does not actually appear without additional
8556 rules.  Here is a complete Bison grammar file that actually manifests
8557 the conflict:
8559 @example
8561 @group
8562 stmt:
8563   expr
8564 | if_stmt
8566 @end group
8568 @group
8569 if_stmt:
8570   "if" expr "then" stmt
8571 | "if" expr "then" stmt "else" stmt
8573 @end group
8575 expr:
8576   "identifier"
8578 @end example
8580 @node Precedence
8581 @section Operator Precedence
8582 @cindex operator precedence
8583 @cindex precedence of operators
8585 Another situation where shift/reduce conflicts appear is in arithmetic
8586 expressions.  Here shifting is not always the preferred resolution; the
8587 Bison declarations for operator precedence allow you to specify when to
8588 shift and when to reduce.
8590 @menu
8591 * Why Precedence::    An example showing why precedence is needed.
8592 * Using Precedence::  How to specify precedence and associativity.
8593 * Precedence Only::   How to specify precedence only.
8594 * Precedence Examples::  How these features are used in the previous example.
8595 * How Precedence::    How they work.
8596 * Non Operators::     Using precedence for general conflicts.
8597 @end menu
8599 @node Why Precedence
8600 @subsection When Precedence is Needed
8602 Consider the following ambiguous grammar fragment (ambiguous because the
8603 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
8605 @example
8606 @group
8607 expr:
8608   expr '-' expr
8609 | expr '*' expr
8610 | expr '<' expr
8611 | '(' expr ')'
8612 @dots{}
8614 @end group
8615 @end example
8617 @noindent
8618 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
8619 should it reduce them via the rule for the subtraction operator?  It
8620 depends on the next token.  Of course, if the next token is @samp{)}, we
8621 must reduce; shifting is invalid because no single rule can reduce the
8622 token sequence @w{@samp{- 2 )}} or anything starting with that.  But if
8623 the next token is @samp{*} or @samp{<}, we have a choice: either
8624 shifting or reduction would allow the parse to complete, but with
8625 different results.
8627 To decide which one Bison should do, we must consider the results.  If
8628 the next operator token @var{op} is shifted, then it must be reduced
8629 first in order to permit another opportunity to reduce the difference.
8630 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}.  On the other
8631 hand, if the subtraction is reduced before shifting @var{op}, the result
8632 is @w{@samp{(1 - 2) @var{op} 3}}.  Clearly, then, the choice of shift or
8633 reduce should depend on the relative precedence of the operators
8634 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
8635 @samp{<}.
8637 @cindex associativity
8638 What about input such as @w{@samp{1 - 2 - 5}}; should this be
8639 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}?  For most
8640 operators we prefer the former, which is called @dfn{left association}.
8641 The latter alternative, @dfn{right association}, is desirable for
8642 assignment operators.  The choice of left or right association is a
8643 matter of whether the parser chooses to shift or reduce when the stack
8644 contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
8645 makes right-associativity.
8647 @node Using Precedence
8648 @subsection Specifying Operator Precedence
8649 @findex %left
8650 @findex %nonassoc
8651 @findex %precedence
8652 @findex %right
8654 Bison allows you to specify these choices with the operator precedence
8655 declarations @code{%left} and @code{%right}.  Each such declaration
8656 contains a list of tokens, which are operators whose precedence and
8657 associativity is being declared.  The @code{%left} declaration makes all
8658 those operators left-associative and the @code{%right} declaration makes
8659 them right-associative.  A third alternative is @code{%nonassoc}, which
8660 declares that it is a syntax error to find the same operator twice ``in a
8661 row''.
8662 The last alternative, @code{%precedence}, allows to define only
8663 precedence and no associativity at all.  As a result, any
8664 associativity-related conflict that remains will be reported as an
8665 compile-time error.  The directive @code{%nonassoc} creates run-time
8666 error: using the operator in a associative way is a syntax error.  The
8667 directive @code{%precedence} creates compile-time errors: an operator
8668 @emph{can} be involved in an associativity-related conflict, contrary to
8669 what expected the grammar author.
8671 The relative precedence of different operators is controlled by the
8672 order in which they are declared.  The first precedence/associativity
8673 declaration in the file declares the operators whose
8674 precedence is lowest, the next such declaration declares the operators
8675 whose precedence is a little higher, and so on.
8677 @node Precedence Only
8678 @subsection Specifying Precedence Only
8679 @findex %precedence
8681 Since POSIX Yacc defines only @code{%left}, @code{%right}, and
8682 @code{%nonassoc}, which all defines precedence and associativity, little
8683 attention is paid to the fact that precedence cannot be defined without
8684 defining associativity.  Yet, sometimes, when trying to solve a
8685 conflict, precedence suffices.  In such a case, using @code{%left},
8686 @code{%right}, or @code{%nonassoc} might hide future (associativity
8687 related) conflicts that would remain hidden.
8689 The dangling @code{else} ambiguity (@pxref{Shift/Reduce}) can be solved
8690 explicitly.  This shift/reduce conflicts occurs in the following situation,
8691 where the period denotes the current parsing state:
8693 @example
8694 if @var{e1} then if  @var{e2} then @var{s1} â€¢ else @var{s2}
8695 @end example
8697 The conflict involves the reduction of the rule @samp{IF expr THEN
8698 stmt}, which precedence is by default that of its last token
8699 (@code{THEN}), and the shifting of the token @code{ELSE}.  The usual
8700 disambiguation (attach the @code{else} to the closest @code{if}),
8701 shifting must be preferred, i.e., the precedence of @code{ELSE} must be
8702 higher than that of @code{THEN}.  But neither is expected to be involved
8703 in an associativity related conflict, which can be specified as follows.
8705 @example
8706 %precedence THEN
8707 %precedence ELSE
8708 @end example
8710 The unary-minus is another typical example where associativity is usually
8711 over-specified, see @ref{Infix Calc}.  The @code{%left} directive is
8712 traditionally used to declare the precedence of @code{NEG}, which is more
8713 than needed since it also defines its associativity.  While this is harmless
8714 in the traditional example, who knows how @code{NEG} might be used in future
8715 evolutions of the grammar@dots{}
8717 @node Precedence Examples
8718 @subsection Precedence Examples
8720 In our example, we would want the following declarations:
8722 @example
8723 %left '<'
8724 %left '-'
8725 %left '*'
8726 @end example
8728 In a more complete example, which supports other operators as well, we
8729 would declare them in groups of equal precedence.  For example, @code{'+'} is
8730 declared with @code{'-'}:
8732 @example
8733 %left '<' '>' '=' "!=" "<=" ">="
8734 %left '+' '-'
8735 %left '*' '/'
8736 @end example
8738 @node How Precedence
8739 @subsection How Precedence Works
8741 The first effect of the precedence declarations is to assign precedence
8742 levels to the terminal symbols declared.  The second effect is to assign
8743 precedence levels to certain rules: each rule gets its precedence from
8744 the last terminal symbol mentioned in the components.  (You can also
8745 specify explicitly the precedence of a rule.  @xref{Contextual
8746 Precedence}.)
8748 Finally, the resolution of conflicts works by comparing the precedence
8749 of the rule being considered with that of the lookahead token.  If the
8750 token's precedence is higher, the choice is to shift.  If the rule's
8751 precedence is higher, the choice is to reduce.  If they have equal
8752 precedence, the choice is made based on the associativity of that
8753 precedence level.  The verbose output file made by @option{-v}
8754 (@pxref{Invocation}) says how each conflict was
8755 resolved.
8757 Not all rules and not all tokens have precedence.  If either the rule or
8758 the lookahead token has no precedence, then the default is to shift.
8760 @node Non Operators
8761 @subsection Using Precedence For Non Operators
8763 Using properly precedence and associativity directives can help fixing
8764 shift/reduce conflicts that do not involve arithmetic-like operators.  For
8765 instance, the ``dangling @code{else}'' problem (@pxref{Shift/Reduce}) can be
8766 solved elegantly in two different ways.
8768 In the present case, the conflict is between the token @code{"else"} willing
8769 to be shifted, and the rule @samp{if_stmt: "if" expr "then" stmt}, asking
8770 for reduction.  By default, the precedence of a rule is that of its last
8771 token, here @code{"then"}, so the conflict will be solved appropriately
8772 by giving @code{"else"} a precedence higher than that of @code{"then"}, for
8773 instance as follows:
8775 @example
8776 @group
8777 %precedence "then"
8778 %precedence "else"
8779 @end group
8780 @end example
8782 Alternatively, you may give both tokens the same precedence, in which case
8783 associativity is used to solve the conflict.  To preserve the shift action,
8784 use right associativity:
8786 @example
8787 %right "then" "else"
8788 @end example
8790 Neither solution is perfect however.  Since Bison does not provide, so far,
8791 ``scoped'' precedence, both force you to declare the precedence
8792 of these keywords with respect to the other operators your grammar.
8793 Therefore, instead of being warned about new conflicts you would be unaware
8794 of (e.g., a shift/reduce conflict due to @samp{if test then 1 else 2 + 3}
8795 being ambiguous: @samp{if test then 1 else (2 + 3)} or @samp{(if test then 1
8796 else 2) + 3}?), the conflict will be already ``fixed''.
8798 @node Contextual Precedence
8799 @section Context-Dependent Precedence
8800 @cindex context-dependent precedence
8801 @cindex unary operator precedence
8802 @cindex precedence, context-dependent
8803 @cindex precedence, unary operator
8804 @findex %prec
8806 Often the precedence of an operator depends on the context.  This sounds
8807 outlandish at first, but it is really very common.  For example, a minus
8808 sign typically has a very high precedence as a unary operator, and a
8809 somewhat lower precedence (lower than multiplication) as a binary operator.
8811 The Bison precedence declarations
8812 can only be used once for a given token; so a token has
8813 only one precedence declared in this way.  For context-dependent
8814 precedence, you need to use an additional mechanism: the @code{%prec}
8815 modifier for rules.
8817 The @code{%prec} modifier declares the precedence of a particular rule by
8818 specifying a terminal symbol whose precedence should be used for that rule.
8819 It's not necessary for that symbol to appear otherwise in the rule.  The
8820 modifier's syntax is:
8822 @example
8823 %prec @var{terminal-symbol}
8824 @end example
8826 @noindent
8827 and it is written after the components of the rule.  Its effect is to
8828 assign the rule the precedence of @var{terminal-symbol}, overriding
8829 the precedence that would be deduced for it in the ordinary way.  The
8830 altered rule precedence then affects how conflicts involving that rule
8831 are resolved (@pxref{Precedence}).
8833 Here is how @code{%prec} solves the problem of unary minus.  First, declare
8834 a precedence for a fictitious terminal symbol named @code{UMINUS}.  There
8835 are no tokens of this type, but the symbol serves to stand for its
8836 precedence:
8838 @example
8839 @dots{}
8840 %left '+' '-'
8841 %left '*'
8842 %left UMINUS
8843 @end example
8845 Now the precedence of @code{UMINUS} can be used in specific rules:
8847 @example
8848 @group
8849 exp:
8850   @dots{}
8851 | exp '-' exp
8852   @dots{}
8853 | '-' exp %prec UMINUS
8854 @end group
8855 @end example
8857 @ifset defaultprec
8858 If you forget to append @code{%prec UMINUS} to the rule for unary
8859 minus, Bison silently assumes that minus has its usual precedence.
8860 This kind of problem can be tricky to debug, since one typically
8861 discovers the mistake only by testing the code.
8863 The @code{%no-default-prec;} declaration makes it easier to discover
8864 this kind of problem systematically.  It causes rules that lack a
8865 @code{%prec} modifier to have no precedence, even if the last terminal
8866 symbol mentioned in their components has a declared precedence.
8868 If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
8869 for all rules that participate in precedence conflict resolution.
8870 Then you will see any shift/reduce conflict until you tell Bison how
8871 to resolve it, either by changing your grammar or by adding an
8872 explicit precedence.  This will probably add declarations to the
8873 grammar, but it helps to protect against incorrect rule precedences.
8875 The effect of @code{%no-default-prec;} can be reversed by giving
8876 @code{%default-prec;}, which is the default.
8877 @end ifset
8879 @node Parser States
8880 @section Parser States
8881 @cindex finite-state machine
8882 @cindex parser state
8883 @cindex state (of parser)
8885 The function @code{yyparse} is implemented using a finite-state machine.
8886 The values pushed on the parser stack are not simply token kind codes; they
8887 represent the entire sequence of terminal and nonterminal symbols at or
8888 near the top of the stack.  The current state collects all the information
8889 about previous input which is relevant to deciding what to do next.
8891 Each time a lookahead token is read, the current parser state together with
8892 the kind of lookahead token are looked up in a table.  This table entry can
8893 say, ``Shift the lookahead token.''  In this case, it also specifies the new
8894 parser state, which is pushed onto the top of the parser stack.  Or it can
8895 say, ``Reduce using rule number @var{n}.''  This means that a certain number
8896 of tokens or groupings are taken off the top of the stack, and replaced by
8897 one grouping.  In other words, that number of states are popped from the
8898 stack, and one new state is pushed.
8900 There is one other alternative: the table can say that the lookahead token
8901 is erroneous in the current state.  This causes error processing to begin
8902 (@pxref{Error Recovery}).
8904 @node Reduce/Reduce
8905 @section Reduce/Reduce Conflicts
8906 @cindex reduce/reduce conflict
8907 @cindex conflicts, reduce/reduce
8909 A reduce/reduce conflict occurs if there are two or more rules that apply
8910 to the same sequence of input.  This usually indicates a serious error
8911 in the grammar.
8913 For example, here is an erroneous attempt to define a sequence
8914 of zero or more @code{word} groupings.
8916 @example
8917 @group
8918 sequence:
8919   %empty         @{ printf ("empty sequence\n"); @}
8920 | maybeword
8921 | sequence word  @{ printf ("added word %s\n", $2); @}
8923 @end group
8925 @group
8926 maybeword:
8927   %empty    @{ printf ("empty maybeword\n"); @}
8928 | word      @{ printf ("single word %s\n", $1); @}
8930 @end group
8931 @end example
8933 @noindent
8934 The error is an ambiguity: as counterexample generation would demonstrate
8935 (@pxref{Counterexamples}), there is more than one way to parse a single
8936 @code{word} into a @code{sequence}.  It could be reduced to a
8937 @code{maybeword} and then into a @code{sequence} via the second rule.
8938 Alternatively, nothing-at-all could be reduced into a @code{sequence}
8939 via the first rule, and this could be combined with the @code{word}
8940 using the third rule for @code{sequence}.
8942 There is also more than one way to reduce nothing-at-all into a
8943 @code{sequence}.  This can be done directly via the first rule,
8944 or indirectly via @code{maybeword} and then the second rule.
8946 You might think that this is a distinction without a difference, because it
8947 does not change whether any particular input is valid or not.  But it does
8948 affect which actions are run.  One parsing order runs the second rule's
8949 action; the other runs the first rule's action and the third rule's action.
8950 In this example, the output of the program changes.
8952 Bison resolves a reduce/reduce conflict by choosing to use the rule that
8953 appears first in the grammar, but it is very risky to rely on this.  Every
8954 reduce/reduce conflict must be studied and usually eliminated.  Here is the
8955 proper way to define @code{sequence}:
8957 @example
8958 @group
8959 sequence:
8960   %empty         @{ printf ("empty sequence\n"); @}
8961 | sequence word  @{ printf ("added word %s\n", $2); @}
8963 @end group
8964 @end example
8966 Here is another common error that yields a reduce/reduce conflict:
8968 @example
8969 @group
8970 sequence:
8971   %empty
8972 | sequence words
8973 | sequence redirects
8975 @end group
8977 @group
8978 words:
8979   %empty
8980 | words word
8982 @end group
8984 @group
8985 redirects:
8986   %empty
8987 | redirects redirect
8989 @end group
8990 @end example
8992 @noindent
8993 The intention here is to define a sequence which can contain either
8994 @code{word} or @code{redirect} groupings.  The individual definitions of
8995 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
8996 three together make a subtle ambiguity: even an empty input can be parsed
8997 in infinitely many ways!
8999 Consider: nothing-at-all could be a @code{words}.  Or it could be two
9000 @code{words} in a row, or three, or any number.  It could equally well be a
9001 @code{redirects}, or two, or any number.  Or it could be a @code{words}
9002 followed by three @code{redirects} and another @code{words}.  And so on.
9004 Here are two ways to correct these rules.  First, to make it a single level
9005 of sequence:
9007 @example
9008 sequence:
9009   %empty
9010 | sequence word
9011 | sequence redirect
9013 @end example
9015 Second, to prevent either a @code{words} or a @code{redirects}
9016 from being empty:
9018 @example
9019 @group
9020 sequence:
9021   %empty
9022 | sequence words
9023 | sequence redirects
9025 @end group
9027 @group
9028 words:
9029   word
9030 | words word
9032 @end group
9034 @group
9035 redirects:
9036   redirect
9037 | redirects redirect
9039 @end group
9040 @end example
9042 Yet this proposal introduces another kind of ambiguity!  The input
9043 @samp{word word} can be parsed as a single @code{words} composed of two
9044 @samp{word}s, or as two one-@code{word} @code{words} (and likewise for
9045 @code{redirect}/@code{redirects}).  However this ambiguity is now a
9046 shift/reduce conflict, and therefore it can now be addressed with precedence
9047 directives.
9049 To simplify the matter, we will proceed with @code{word} and @code{redirect}
9050 being tokens: @code{"word"} and @code{"redirect"}.
9052 To prefer the longest @code{words}, the conflict between the token
9053 @code{"word"} and the rule @samp{sequence: sequence words} must be resolved
9054 as a shift.  To this end, we use the same techniques as exposed above, see
9055 @ref{Non Operators}.  One solution
9056 relies on precedences: use @code{%prec} to give a lower precedence to the
9057 rule:
9059 @example
9060 %precedence "word"
9061 %precedence "sequence"
9063 @group
9064 sequence:
9065   %empty
9066 | sequence word      %prec "sequence"
9067 | sequence redirect  %prec "sequence"
9069 @end group
9071 @group
9072 words:
9073   word
9074 | words "word"
9076 @end group
9077 @end example
9079 Another solution relies on associativity: provide both the token and the
9080 rule with the same precedence, but make them right-associative:
9082 @example
9083 %right "word" "redirect"
9085 @group
9086 sequence:
9087   %empty
9088 | sequence word      %prec "word"
9089 | sequence redirect  %prec "redirect"
9091 @end group
9092 @end example
9094 @node Mysterious Conflicts
9095 @section Mysterious Conflicts
9096 @cindex Mysterious Conflicts
9098 Sometimes reduce/reduce conflicts can occur that don't look warranted.
9099 Here is an example:
9101 @example
9102 @group
9104 def: param_spec return_spec ',';
9105 param_spec:
9106   type
9107 | name_list ':' type
9109 @end group
9111 @group
9112 return_spec:
9113   type
9114 | name ':' type
9116 @end group
9118 type: "id";
9120 @group
9121 name: "id";
9122 name_list:
9123   name
9124 | name ',' name_list
9126 @end group
9127 @end example
9129 It would seem that this grammar can be parsed with only a single token of
9130 lookahead: when a @code{param_spec} is being read, an @code{"id"} is a
9131 @code{name} if a comma or colon follows, or a @code{type} if another
9132 @code{"id"} follows.  In other words, this grammar is LR(1).  Yet Bison
9133 finds one reduce/reduce conflict, for which counterexample generation
9134 (@pxref{Counterexamples}) would find a @emph{nonunifying} example.
9136 @cindex LR
9137 @cindex LALR
9138 This is because Bison does not handle all LR(1) grammars @emph{by default},
9139 for historical reasons.
9140 In this grammar, two contexts, that after an @code{"id"} at the beginning
9141 of a @code{param_spec} and likewise at the beginning of a
9142 @code{return_spec}, are similar enough that Bison assumes they are the
9143 same.
9144 They appear similar because the same set of rules would be
9145 active---the rule for reducing to a @code{name} and that for reducing to
9146 a @code{type}.  Bison is unable to determine at that stage of processing
9147 that the rules would require different lookahead tokens in the two
9148 contexts, so it makes a single parser state for them both.  Combining
9149 the two contexts causes a conflict later.  In parser terminology, this
9150 occurrence means that the grammar is not LALR(1).
9152 @cindex IELR
9153 @cindex canonical LR
9154 For many practical grammars (specifically those that fall into the non-LR(1)
9155 class), the limitations of LALR(1) result in difficulties beyond just
9156 mysterious reduce/reduce conflicts.  The best way to fix all these problems
9157 is to select a different parser table construction algorithm.  Either
9158 IELR(1) or canonical LR(1) would suffice, but the former is more efficient
9159 and easier to debug during development.  @xref{LR Table Construction}, for
9160 details.
9162 If you instead wish to work around LALR(1)'s limitations, you
9163 can often fix a mysterious conflict by identifying the two parser states
9164 that are being confused, and adding something to make them look
9165 distinct.  In the above example, adding one rule to
9166 @code{return_spec} as follows makes the problem go away:
9168 @example
9169 @group
9170 @dots{}
9171 return_spec:
9172   type
9173 | name ':' type
9174 | "id" "bogus"       /* This rule is never used. */
9176 @end group
9177 @end example
9179 This corrects the problem because it introduces the possibility of an
9180 additional active rule in the context after the @code{"id"} at the beginning of
9181 @code{return_spec}.  This rule is not active in the corresponding context
9182 in a @code{param_spec}, so the two contexts receive distinct parser states.
9183 As long as the token @code{"bogus"} is never generated by @code{yylex},
9184 the added rule cannot alter the way actual input is parsed.
9186 In this particular example, there is another way to solve the problem:
9187 rewrite the rule for @code{return_spec} to use @code{"id"} directly
9188 instead of via @code{name}.  This also causes the two confusing
9189 contexts to have different sets of active rules, because the one for
9190 @code{return_spec} activates the altered rule for @code{return_spec}
9191 rather than the one for @code{name}.
9193 @example
9194 @group
9195 param_spec:
9196   type
9197 | name_list ':' type
9199 @end group
9201 @group
9202 return_spec:
9203   type
9204 | "id" ':' type
9206 @end group
9207 @end example
9209 For a more detailed exposition of LALR(1) parsers and parser generators, see
9210 @tcite{DeRemer 1982}.
9212 @node Tuning LR
9213 @section Tuning LR
9215 The default behavior of Bison's LR-based parsers is chosen mostly for
9216 historical reasons, but that behavior is often not robust.  For example, in
9217 the previous section, we discussed the mysterious conflicts that can be
9218 produced by LALR(1), Bison's default parser table construction algorithm.
9219 Another example is Bison's @code{%define parse.error verbose} directive,
9220 which instructs the generated parser to produce verbose syntax error
9221 messages, which can sometimes contain incorrect information.
9223 In this section, we explore several modern features of Bison that allow you
9224 to tune fundamental aspects of the generated LR-based parsers.  Some of
9225 these features easily eliminate shortcomings like those mentioned above.
9226 Others can be helpful purely for understanding your parser.
9228 @menu
9229 * LR Table Construction:: Choose a different construction algorithm.
9230 * Default Reductions::    Disable default reductions.
9231 * LAC::                   Correct lookahead sets in the parser states.
9232 * Unreachable States::    Keep unreachable parser states for debugging.
9233 @end menu
9235 @node LR Table Construction
9236 @subsection LR Table Construction
9237 @cindex Mysterious Conflict
9238 @cindex LALR
9239 @cindex IELR
9240 @cindex canonical LR
9241 @findex %define lr.type
9243 For historical reasons, Bison constructs LALR(1) parser tables by default.
9244 However, LALR does not possess the full language-recognition power of LR.
9245 As a result, the behavior of parsers employing LALR parser tables is often
9246 mysterious.  We presented a simple example of this effect in @ref{Mysterious
9247 Conflicts}.
9249 As we also demonstrated in that example, the traditional approach to
9250 eliminating such mysterious behavior is to restructure the grammar.
9251 Unfortunately, doing so correctly is often difficult.  Moreover, merely
9252 discovering that LALR causes mysterious behavior in your parser can be
9253 difficult as well.
9255 Fortunately, Bison provides an easy way to eliminate the possibility of such
9256 mysterious behavior altogether.  You simply need to activate a more powerful
9257 parser table construction algorithm by using the @code{%define lr.type}
9258 directive.
9260 @deffn {Directive} {%define lr.type} @var{type}
9261 Specify the type of parser tables within the LR(1) family.  The accepted
9262 values for @var{type} are:
9264 @itemize
9265 @item @code{lalr} (default)
9266 @item @code{ielr}
9267 @item @code{canonical-lr}
9268 @end itemize
9269 @end deffn
9271 For example, to activate IELR, you might add the following directive to you
9272 grammar file:
9274 @example
9275 %define lr.type ielr
9276 @end example
9278 @noindent For the example in @ref{Mysterious Conflicts}, the mysterious
9279 conflict is then eliminated, so there is no need to invest time in
9280 comprehending the conflict or restructuring the grammar to fix it.  If,
9281 during future development, the grammar evolves such that all mysterious
9282 behavior would have disappeared using just LALR, you need not fear that
9283 continuing to use IELR will result in unnecessarily large parser tables.
9284 That is, IELR generates LALR tables when LALR (using a deterministic parsing
9285 algorithm) is sufficient to support the full language-recognition power of
9286 LR.  Thus, by enabling IELR at the start of grammar development, you can
9287 safely and completely eliminate the need to consider LALR's shortcomings.
9289 While IELR is almost always preferable, there are circumstances where LALR
9290 or the canonical LR parser tables described by Knuth @pcite{Knuth 1965} can
9291 be useful.  Here we summarize the relative advantages of each parser table
9292 construction algorithm within Bison:
9294 @itemize
9295 @item LALR
9297 There are at least two scenarios where LALR can be worthwhile:
9299 @itemize
9300 @item GLR without static conflict resolution.
9302 @cindex GLR with LALR
9303 When employing GLR parsers (@pxref{GLR Parsers}), if you do not resolve any
9304 conflicts statically (for example, with @code{%left} or @code{%precedence}),
9305 then
9306 the parser explores all potential parses of any given input.  In this case,
9307 the choice of parser table construction algorithm is guaranteed not to alter
9308 the language accepted by the parser.  LALR parser tables are the smallest
9309 parser tables Bison can currently construct, so they may then be preferable.
9310 Nevertheless, once you begin to resolve conflicts statically, GLR behaves
9311 more like a deterministic parser in the syntactic contexts where those
9312 conflicts appear, and so either IELR or canonical LR can then be helpful to
9313 avoid LALR's mysterious behavior.
9315 @item Malformed grammars.
9317 Occasionally during development, an especially malformed grammar with a
9318 major recurring flaw may severely impede the IELR or canonical LR parser
9319 table construction algorithm.  LALR can be a quick way to construct parser
9320 tables in order to investigate such problems while ignoring the more subtle
9321 differences from IELR and canonical LR.
9322 @end itemize
9324 @item IELR
9326 IELR (Inadequacy Elimination LR) is a minimal LR algorithm.  That is, given
9327 any grammar (LR or non-LR), parsers using IELR or canonical LR parser tables
9328 always accept exactly the same set of sentences.  However, like LALR, IELR
9329 merges parser states during parser table construction so that the number of
9330 parser states is often an order of magnitude less than for canonical LR.
9331 More importantly, because canonical LR's extra parser states may contain
9332 duplicate conflicts in the case of non-LR grammars, the number of conflicts
9333 for IELR is often an order of magnitude less as well.  This effect can
9334 significantly reduce the complexity of developing a grammar.
9336 @item Canonical LR
9338 @cindex delayed syntax error detection
9339 @cindex LAC
9340 @findex %nonassoc
9341 While inefficient, canonical LR parser tables can be an interesting means to
9342 explore a grammar because they possess a property that IELR and LALR tables
9343 do not.  That is, if @code{%nonassoc} is not used and default reductions are
9344 left disabled (@pxref{Default Reductions}), then, for every left context of
9345 every canonical LR state, the set of tokens accepted by that state is
9346 guaranteed to be the exact set of tokens that is syntactically acceptable in
9347 that left context.  It might then seem that an advantage of canonical LR
9348 parsers in production is that, under the above constraints, they are
9349 guaranteed to detect a syntax error as soon as possible without performing
9350 any unnecessary reductions.  However, IELR parsers that use LAC are also
9351 able to achieve this behavior without sacrificing @code{%nonassoc} or
9352 default reductions.  For details and a few caveats of LAC, @pxref{LAC}.
9353 @end itemize
9355 For a more detailed exposition of the mysterious behavior in LALR parsers
9356 and the benefits of IELR, see @tcite{Denny 2008}, and @tcite{Denny 2010
9357 November}.
9359 @node Default Reductions
9360 @subsection Default Reductions
9361 @cindex default reductions
9362 @findex %define lr.default-reduction
9363 @findex %nonassoc
9365 After parser table construction, Bison identifies the reduction with the
9366 largest lookahead set in each parser state.  To reduce the size of the
9367 parser state, traditional Bison behavior is to remove that lookahead set and
9368 to assign that reduction to be the default parser action.  Such a reduction
9369 is known as a @dfn{default reduction}.
9371 Default reductions affect more than the size of the parser tables.  They
9372 also affect the behavior of the parser:
9374 @itemize
9375 @item Delayed @code{yylex} invocations.
9377 @cindex delayed yylex invocations
9378 @cindex consistent states
9379 @cindex defaulted states
9380 A @dfn{consistent state} is a state that has only one possible parser
9381 action.  If that action is a reduction and is encoded as a default
9382 reduction, then that consistent state is called a @dfn{defaulted state}.
9383 Upon reaching a defaulted state, a Bison-generated parser does not bother to
9384 invoke @code{yylex} to fetch the next token before performing the reduction.
9385 In other words, whether default reductions are enabled in consistent states
9386 determines how soon a Bison-generated parser invokes @code{yylex} for a
9387 token: immediately when it @emph{reaches} that token in the input or when it
9388 eventually @emph{needs} that token as a lookahead to determine the next
9389 parser action.  Traditionally, default reductions are enabled, and so the
9390 parser exhibits the latter behavior.
9392 The presence of defaulted states is an important consideration when
9393 designing @code{yylex} and the grammar file.  That is, if the behavior of
9394 @code{yylex} can influence or be influenced by the semantic actions
9395 associated with the reductions in defaulted states, then the delay of the
9396 next @code{yylex} invocation until after those reductions is significant.
9397 For example, the semantic actions might pop a scope stack that @code{yylex}
9398 uses to determine what token to return.  Thus, the delay might be necessary
9399 to ensure that @code{yylex} does not look up the next token in a scope that
9400 should already be considered closed.
9402 @item Delayed syntax error detection.
9404 @cindex delayed syntax error detection
9405 When the parser fetches a new token by invoking @code{yylex}, it checks
9406 whether there is an action for that token in the current parser state.  The
9407 parser detects a syntax error if and only if either (1) there is no action
9408 for that token or (2) the action for that token is the error action (due to
9409 the use of @code{%nonassoc}).  However, if there is a default reduction in
9410 that state (which might or might not be a defaulted state), then it is
9411 impossible for condition 1 to exist.  That is, all tokens have an action.
9412 Thus, the parser sometimes fails to detect the syntax error until it reaches
9413 a later state.
9415 @cindex LAC
9416 @c If there's an infinite loop, default reductions can prevent an incorrect
9417 @c sentence from being rejected.
9418 While default reductions never cause the parser to accept syntactically
9419 incorrect sentences, the delay of syntax error detection can have unexpected
9420 effects on the behavior of the parser.  However, the delay can be caused
9421 anyway by parser state merging and the use of @code{%nonassoc}, and it can
9422 be fixed by another Bison feature, LAC.  We discuss the effects of delayed
9423 syntax error detection and LAC more in the next section (@pxref{LAC}).
9424 @end itemize
9426 For canonical LR, the only default reduction that Bison enables by default
9427 is the accept action, which appears only in the accepting state, which has
9428 no other action and is thus a defaulted state.  However, the default accept
9429 action does not delay any @code{yylex} invocation or syntax error detection
9430 because the accept action ends the parse.
9432 For LALR and IELR, Bison enables default reductions in nearly all states by
9433 default.  There are only two exceptions.  First, states that have a shift
9434 action on the @code{error} token do not have default reductions because
9435 delayed syntax error detection could then prevent the @code{error} token
9436 from ever being shifted in that state.  However, parser state merging can
9437 cause the same effect anyway, and LAC fixes it in both cases, so future
9438 versions of Bison might drop this exception when LAC is activated.  Second,
9439 GLR parsers do not record the default reduction as the action on a lookahead
9440 token for which there is a conflict.  The correct action in this case is to
9441 split the parse instead.
9443 To adjust which states have default reductions enabled, use the
9444 @code{%define lr.default-reduction} directive.
9446 @deffn {Directive} {%define lr.default-reduction} @var{where}
9447 Specify the kind of states that are permitted to contain default reductions.
9448 The accepted values of @var{where} are:
9449 @itemize
9450 @item @code{most} (default for LALR and IELR)
9451 @item @code{consistent}
9452 @item @code{accepting} (default for canonical LR)
9453 @end itemize
9454 @end deffn
9456 @node LAC
9457 @subsection LAC
9458 @findex %define parse.lac
9459 @cindex LAC
9460 @cindex lookahead correction
9462 Canonical LR, IELR, and LALR can suffer from a couple of problems upon
9463 encountering a syntax error.  First, the parser might perform additional
9464 parser stack reductions before discovering the syntax error.  Such
9465 reductions can perform user semantic actions that are unexpected because
9466 they are based on an invalid token, and they cause error recovery to begin
9467 in a different syntactic context than the one in which the invalid token was
9468 encountered.  Second, when verbose error messages are enabled (@pxref{Error
9469 Reporting}), the expected token list in the syntax error message can both
9470 contain invalid tokens and omit valid tokens.
9472 The culprits for the above problems are @code{%nonassoc}, default reductions
9473 in inconsistent states (@pxref{Default Reductions}), and parser state
9474 merging.  Because IELR and LALR merge parser states, they suffer the most.
9475 Canonical LR can suffer only if @code{%nonassoc} is used or if default
9476 reductions are enabled for inconsistent states.
9478 LAC (Lookahead Correction) is a new mechanism within the parsing algorithm
9479 that solves these problems for canonical LR, IELR, and LALR without
9480 sacrificing @code{%nonassoc}, default reductions, or state merging.  You can
9481 enable LAC with the @code{%define parse.lac} directive.
9483 @deffn {Directive} {%define parse.lac} @var{value}
9484 Enable LAC to improve syntax error handling.
9485 @itemize
9486 @item @code{none} (default)
9487 @item @code{full}
9488 @end itemize
9489 This feature is currently only available for deterministic parsers in C and C++.
9490 @end deffn
9492 Conceptually, the LAC mechanism is straight-forward.  Whenever the parser
9493 fetches a new token from the scanner so that it can determine the next
9494 parser action, it immediately suspends normal parsing and performs an
9495 exploratory parse using a temporary copy of the normal parser state stack.
9496 During this exploratory parse, the parser does not perform user semantic
9497 actions.  If the exploratory parse reaches a shift action, normal parsing
9498 then resumes on the normal parser stacks.  If the exploratory parse reaches
9499 an error instead, the parser reports a syntax error.  If verbose syntax
9500 error messages are enabled, the parser must then discover the list of
9501 expected tokens, so it performs a separate exploratory parse for each token
9502 in the grammar.
9504 There is one subtlety about the use of LAC.  That is, when in a consistent
9505 parser state with a default reduction, the parser will not attempt to fetch
9506 a token from the scanner because no lookahead is needed to determine the
9507 next parser action.  Thus, whether default reductions are enabled in
9508 consistent states (@pxref{Default Reductions}) affects how soon the parser
9509 detects a syntax error: immediately when it @emph{reaches} an erroneous
9510 token or when it eventually @emph{needs} that token as a lookahead to
9511 determine the next parser action.  The latter behavior is probably more
9512 intuitive, so Bison currently provides no way to achieve the former behavior
9513 while default reductions are enabled in consistent states.
9515 Thus, when LAC is in use, for some fixed decision of whether to enable
9516 default reductions in consistent states, canonical LR and IELR behave almost
9517 exactly the same for both syntactically acceptable and syntactically
9518 unacceptable input.  While LALR still does not support the full
9519 language-recognition power of canonical LR and IELR, LAC at least enables
9520 LALR's syntax error handling to correctly reflect LALR's
9521 language-recognition power.
9523 There are a few caveats to consider when using LAC:
9525 @itemize
9526 @item Infinite parsing loops.
9528 IELR plus LAC does have one shortcoming relative to canonical LR.  Some
9529 parsers generated by Bison can loop infinitely.  LAC does not fix infinite
9530 parsing loops that occur between encountering a syntax error and detecting
9531 it, but enabling canonical LR or disabling default reductions sometimes
9532 does.
9534 @item Verbose error message limitations.
9536 Because of internationalization considerations, Bison-generated parsers
9537 limit the size of the expected token list they are willing to report in a
9538 verbose syntax error message.  If the number of expected tokens exceeds that
9539 limit, the list is simply dropped from the message.  Enabling LAC can
9540 increase the size of the list and thus cause the parser to drop it.  Of
9541 course, dropping the list is better than reporting an incorrect list.
9543 @item Performance.
9545 Because LAC requires many parse actions to be performed twice, it can have a
9546 performance penalty.  However, not all parse actions must be performed
9547 twice.  Specifically, during a series of default reductions in consistent
9548 states and shift actions, the parser never has to initiate an exploratory
9549 parse.  Moreover, the most time-consuming tasks in a parse are often the
9550 file I/O, the lexical analysis performed by the scanner, and the user's
9551 semantic actions, but none of these are performed during the exploratory
9552 parse.  Finally, the base of the temporary stack used during an exploratory
9553 parse is a pointer into the normal parser state stack so that the stack is
9554 never physically copied.  In our experience, the performance penalty of LAC
9555 has proved insignificant for practical grammars.
9556 @end itemize
9558 While the LAC algorithm shares techniques that have been recognized in the
9559 parser community for years, for the publication that introduces LAC, see
9560 @tcite{Denny 2010 May}.
9562 @node Unreachable States
9563 @subsection Unreachable States
9564 @findex %define lr.keep-unreachable-state
9565 @cindex unreachable states
9567 If there exists no sequence of transitions from the parser's start state to
9568 some state @var{s}, then Bison considers @var{s} to be an @dfn{unreachable
9569 state}.  A state can become unreachable during conflict resolution if Bison
9570 disables a shift action leading to it from a predecessor state.
9572 By default, Bison removes unreachable states from the parser after conflict
9573 resolution because they are useless in the generated parser.  However,
9574 keeping unreachable states is sometimes useful when trying to understand the
9575 relationship between the parser and the grammar.
9577 @deffn {Directive} {%define lr.keep-unreachable-state} @var{value}
9578 Request that Bison allow unreachable states to remain in the parser tables.
9579 @var{value} must be a Boolean.  The default is @code{false}.
9580 @end deffn
9582 There are a few caveats to consider:
9584 @itemize @bullet
9585 @item Missing or extraneous warnings.
9587 Unreachable states may contain conflicts and may use rules not used in any
9588 other state.  Thus, keeping unreachable states may induce warnings that are
9589 irrelevant to your parser's behavior, and it may eliminate warnings that are
9590 relevant.  Of course, the change in warnings may actually be relevant to a
9591 parser table analysis that wants to keep unreachable states, so this
9592 behavior will likely remain in future Bison releases.
9594 @item Other useless states.
9596 While Bison is able to remove unreachable states, it is not guaranteed to
9597 remove other kinds of useless states.  Specifically, when Bison disables
9598 reduce actions during conflict resolution, some goto actions may become
9599 useless, and thus some additional states may become useless.  If Bison were
9600 to compute which goto actions were useless and then disable those actions,
9601 it could identify such states as unreachable and then remove those states.
9602 However, Bison does not compute which goto actions are useless.
9603 @end itemize
9605 @node Generalized LR Parsing
9606 @section Generalized LR (GLR) Parsing
9607 @cindex GLR parsing
9608 @cindex generalized LR (GLR) parsing
9609 @cindex ambiguous grammars
9610 @cindex nondeterministic parsing
9612 Bison produces @emph{deterministic} parsers that choose uniquely
9613 when to reduce and which reduction to apply
9614 based on a summary of the preceding input and on one extra token of lookahead.
9615 As a result, normal Bison handles a proper subset of the family of
9616 context-free languages.
9617 Ambiguous grammars, since they have strings with more than one possible
9618 sequence of reductions cannot have deterministic parsers in this sense.
9619 The same is true of languages that require more than one symbol of
9620 lookahead, since the parser lacks the information necessary to make a
9621 decision at the point it must be made in a shift/reduce parser.
9622 Finally, as previously mentioned (@pxref{Mysterious Conflicts}),
9623 there are languages where Bison's default choice of how to
9624 summarize the input seen so far loses necessary information.
9626 When you use the @samp{%glr-parser} declaration in your grammar file,
9627 Bison generates a parser that uses a different algorithm, called
9628 Generalized LR (or GLR).  A Bison GLR
9629 parser uses the same basic
9630 algorithm for parsing as an ordinary Bison parser, but behaves
9631 differently in cases where there is a shift/reduce conflict that has not
9632 been resolved by precedence rules (@pxref{Precedence}) or a
9633 reduce/reduce conflict.  When a GLR parser encounters such a
9634 situation, it
9635 effectively @emph{splits} into a several parsers, one for each possible
9636 shift or reduction.  These parsers then proceed as usual, consuming
9637 tokens in lock-step.  Some of the stacks may encounter other conflicts
9638 and split further, with the result that instead of a sequence of states,
9639 a Bison GLR parsing stack is what is in effect a tree of states.
9641 In effect, each stack represents a guess as to what the proper parse
9642 is.  Additional input may indicate that a guess was wrong, in which case
9643 the appropriate stack silently disappears.  Otherwise, the semantics
9644 actions generated in each stack are saved, rather than being executed
9645 immediately.  When a stack disappears, its saved semantic actions never
9646 get executed.  When a reduction causes two stacks to become equivalent,
9647 their sets of semantic actions are both saved with the state that
9648 results from the reduction.  We say that two stacks are equivalent
9649 when they both represent the same sequence of states,
9650 and each pair of corresponding states represents a
9651 grammar symbol that produces the same segment of the input token
9652 stream.
9654 Whenever the parser makes a transition from having multiple
9655 states to having one, it reverts to the normal deterministic parsing
9656 algorithm, after resolving and executing the saved-up actions.
9657 At this transition, some of the states on the stack will have semantic
9658 values that are sets (actually multisets) of possible actions.  The
9659 parser tries to pick one of the actions by first finding one whose rule
9660 has the highest dynamic precedence, as set by the @samp{%dprec}
9661 declaration.  Otherwise, if the alternative actions are not ordered by
9662 precedence, but there the same merging function is declared for both
9663 rules by the @samp{%merge} declaration,
9664 Bison resolves and evaluates both and then calls the merge function on
9665 the result.  Otherwise, it reports an ambiguity.
9667 It is possible to use a data structure for the GLR parsing tree that
9668 permits the processing of any LR(1) grammar in linear time (in the
9669 size of the input), any unambiguous (not necessarily
9670 LR(1)) grammar in
9671 quadratic worst-case time, and any general (possibly ambiguous)
9672 context-free grammar in cubic worst-case time.  However, Bison currently
9673 uses a simpler data structure that requires time proportional to the
9674 length of the input times the maximum number of stacks required for any
9675 prefix of the input.  Thus, really ambiguous or nondeterministic
9676 grammars can require exponential time and space to process.  Such badly
9677 behaving examples, however, are not generally of practical interest.
9678 Usually, nondeterminism in a grammar is local---the parser is ``in
9679 doubt'' only for a few tokens at a time.  Therefore, the current data
9680 structure should generally be adequate.  On LR(1) portions of a
9681 grammar, in particular, it is only slightly slower than with the
9682 deterministic LR(1) Bison parser.
9684 For a more detailed exposition of GLR parsers, see @tcite{Scott 2000}.
9686 @node Memory Management
9687 @section Memory Management, and How to Avoid Memory Exhaustion
9688 @cindex memory exhaustion
9689 @cindex memory management
9690 @cindex stack overflow
9691 @cindex parser stack overflow
9692 @cindex overflow of parser stack
9694 The Bison parser stack can run out of memory if too many tokens are shifted and
9695 not reduced.  When this happens, the parser function @code{yyparse}
9696 calls @code{yyerror} and then returns 2.
9698 Because Bison parsers have growing stacks, hitting the upper limit
9699 usually results from using a right recursion instead of a left
9700 recursion, see @ref{Recursion}.
9702 @vindex YYMAXDEPTH
9703 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
9704 parser stack can become before memory is exhausted.  Define the
9705 macro with a value that is an integer.  This value is the maximum number
9706 of tokens that can be shifted (and not reduced) before overflow.
9708 The stack space allowed is not necessarily allocated.  If you specify a
9709 large value for @code{YYMAXDEPTH}, the parser normally allocates a small
9710 stack at first, and then makes it bigger by stages as needed.  This
9711 increasing allocation happens automatically and silently.  Therefore,
9712 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
9713 space for ordinary inputs that do not need much stack.
9715 However, do not allow @code{YYMAXDEPTH} to be a value so large that
9716 arithmetic overflow could occur when calculating the size of the stack
9717 space.  Also, do not allow @code{YYMAXDEPTH} to be less than
9718 @code{YYINITDEPTH}.
9720 @cindex default stack limit
9721 The default value of @code{YYMAXDEPTH}, if you do not define it, is
9722 10000.
9724 @vindex YYINITDEPTH
9725 You can control how much stack is allocated initially by defining the
9726 macro @code{YYINITDEPTH} to a positive integer.  For the deterministic
9727 parser in C, this value must be a compile-time constant
9728 unless you are assuming C99 or some other target language or compiler
9729 that allows variable-length arrays.  The default is 200.
9731 Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
9733 You can generate a deterministic parser containing C++ user code from the
9734 default (C) skeleton, as well as from the C++ skeleton (@pxref{C++
9735 Parsers}).  However, if you do use the default skeleton and want to allow
9736 the parsing stack to grow, be careful not to use semantic types or location
9737 types that require non-trivial copy constructors.  The C skeleton bypasses
9738 these constructors when copying data to new, larger stacks.
9740 @node Error Recovery
9741 @chapter Error Recovery
9742 @cindex error recovery
9743 @cindex recovery from errors
9745 It is not usually acceptable to have a program terminate on a syntax
9746 error.  For example, a compiler should recover sufficiently to parse the
9747 rest of the input file and check it for errors; a calculator should accept
9748 another expression.
9750 In a simple interactive command parser where each input is one line, it may
9751 be sufficient to allow @code{yyparse} to return 1 on error and have the
9752 caller ignore the rest of the input line when that happens (and then call
9753 @code{yyparse} again).  But this is inadequate for a compiler, because it
9754 forgets all the syntactic context leading up to the error.  A syntax error
9755 deep within a function in the compiler input should not cause the compiler
9756 to treat the following line like the beginning of a source file.
9758 @findex error
9759 You can define how to recover from a syntax error by writing rules to
9760 recognize the special token @code{error}.  This is a terminal symbol that
9761 is always defined (you need not declare it) and reserved for error
9762 handling.  The Bison parser generates an @code{error} token whenever a
9763 syntax error happens; if you have provided a rule to recognize this token
9764 in the current context, the parse can continue.
9766 For example:
9768 @example
9769 stmts:
9770   %empty
9771 | stmts '\n'
9772 | stmts exp '\n'
9773 | stmts error '\n'
9774 @end example
9776 The fourth rule in this example says that an error followed by a newline
9777 makes a valid addition to any @code{stmts}.
9779 What happens if a syntax error occurs in the middle of an @code{exp}?  The
9780 error recovery rule, interpreted strictly, applies to the precise sequence
9781 of a @code{stmts}, an @code{error} and a newline.  If an error occurs in
9782 the middle of an @code{exp}, there will probably be some additional tokens
9783 and subexpressions on the stack after the last @code{stmts}, and there
9784 will be tokens to read before the next newline.  So the rule is not
9785 applicable in the ordinary way.
9787 But Bison can force the situation to fit the rule, by discarding part of the
9788 semantic context and part of the input.  First it discards states and
9789 objects from the stack until it gets back to a state in which the
9790 @code{error} token is acceptable.  (This means that the subexpressions
9791 already parsed are discarded, back to the last complete @code{stmts}.)  At
9792 this point the @code{error} token can be shifted.  Then, if the old
9793 lookahead token is not acceptable to be shifted next, the parser reads
9794 tokens and discards them until it finds a token which is acceptable.  In
9795 this example, Bison reads and discards input until the next newline so that
9796 the fourth rule can apply.  Note that discarded symbols are possible sources
9797 of memory leaks, see @ref{Destructor Decl}, for a means to reclaim this
9798 memory.
9800 The choice of error rules in the grammar is a choice of strategies for
9801 error recovery.  A simple and useful strategy is simply to skip the rest of
9802 the current input line or current statement if an error is detected:
9804 @example
9805 stmt: error ';'  /* On error, skip until ';' is read. */
9806 @end example
9808 It is also useful to recover to the matching close-delimiter of an
9809 opening-delimiter that has already been parsed.  Otherwise the
9810 close-delimiter will probably appear to be unmatched, and generate another,
9811 spurious error message:
9813 @example
9814 primary:
9815   '(' expr ')'
9816 | '(' error ')'
9817 @dots{}
9819 @end example
9821 Error recovery strategies are necessarily guesses.  When they guess wrong,
9822 one syntax error often leads to another.  In the above example, the error
9823 recovery rule guesses that an error is due to bad input within one
9824 @code{stmt}.  Suppose that instead a spurious semicolon is inserted in the
9825 middle of a valid @code{stmt}.  After the error recovery rule recovers from
9826 the first error, another syntax error will be found straight away, since the
9827 text following the spurious semicolon is also an invalid @code{stmt}.
9829 To prevent an outpouring of error messages, the parser will output no error
9830 message for another syntax error that happens shortly after the first; only
9831 after three consecutive input tokens have been successfully shifted will
9832 error messages resume.
9834 Note that rules which accept the @code{error} token may have actions, just
9835 as any other rules can.
9837 @findex yyerrok
9838 You can make error messages resume immediately by using the macro
9839 @code{yyerrok} in an action.  If you do this in the error rule's action, no
9840 error messages will be suppressed.  This macro requires no arguments;
9841 @samp{yyerrok;} is a valid C statement.
9843 @findex yyclearin
9844 The previous lookahead token is reanalyzed immediately after an error.  If
9845 this is unacceptable, then the macro @code{yyclearin} may be used to clear
9846 this token.  Write the statement @samp{yyclearin;} in the error rule's
9847 action.
9848 @xref{Action Features}.
9850 For example, suppose that on a syntax error, an error handling routine is
9851 called that advances the input stream to some point where parsing should
9852 once again commence.  The next symbol returned by the lexical scanner is
9853 probably correct.  The previous lookahead token ought to be discarded
9854 with @samp{yyclearin;}.
9856 @vindex YYRECOVERING
9857 The expression @code{YYRECOVERING ()} yields 1 when the parser
9858 is recovering from a syntax error, and 0 otherwise.
9859 Syntax error diagnostics are suppressed while recovering from a syntax
9860 error.
9862 @node Context Dependency
9863 @chapter Handling Context Dependencies
9865 The Bison paradigm is to parse tokens first, then group them into larger
9866 syntactic units.  In many languages, the meaning of a token is affected by
9867 its context.  Although this violates the Bison paradigm, certain techniques
9868 (known as @dfn{kludges}) may enable you to write Bison parsers for such
9869 languages.
9871 @menu
9872 * Semantic Tokens::   Token parsing can depend on the semantic context.
9873 * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
9874 * Tie-in Recovery::   Lexical tie-ins have implications for how
9875                         error recovery rules must be written.
9876 @end menu
9878 (Actually, ``kludge'' means any technique that gets its job done but is
9879 neither clean nor robust.)
9881 @node Semantic Tokens
9882 @section Semantic Info in Token Kinds
9884 The C language has a context dependency: the way an identifier is used
9885 depends on what its current meaning is.  For example, consider this:
9887 @example
9888 foo (x);
9889 @end example
9891 This looks like a function call statement, but if @code{foo} is a typedef
9892 name, then this is actually a declaration of @code{x}.  How can a Bison
9893 parser for C decide how to parse this input?
9895 The method used in GNU C is to have two different token kinds,
9896 @code{IDENTIFIER} and @code{TYPENAME}.  When @code{yylex} finds an
9897 identifier, it looks up the current declaration of the identifier in order
9898 to decide which token kind to return: @code{TYPENAME} if the identifier is
9899 declared as a typedef, @code{IDENTIFIER} otherwise.
9901 The grammar rules can then express the context dependency by the choice of
9902 token kind to recognize.  @code{IDENTIFIER} is accepted as an expression,
9903 but @code{TYPENAME} is not.  @code{TYPENAME} can start a declaration, but
9904 @code{IDENTIFIER} cannot.  In contexts where the meaning of the identifier
9905 is @emph{not} significant, such as in declarations that can shadow a
9906 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
9907 accepted---there is one rule for each of the two token kinds.
9909 This technique is simple to use if the decision of which kinds of
9910 identifiers to allow is made at a place close to where the identifier is
9911 parsed.  But in C this is not always so: C allows a declaration to
9912 redeclare a typedef name provided an explicit type has been specified
9913 earlier:
9915 @example
9916 typedef int foo, bar;
9917 int baz (void)
9918 @group
9920   static bar (bar);      /* @r{redeclare @code{bar} as static variable} */
9921   extern foo foo (foo);  /* @r{redeclare @code{foo} as function} */
9922   return foo (bar);
9924 @end group
9925 @end example
9927 Unfortunately, the name being declared is separated from the declaration
9928 construct itself by a complicated syntactic structure---the ``declarator''.
9930 As a result, part of the Bison parser for C needs to be duplicated, with
9931 all the nonterminal names changed: once for parsing a declaration in
9932 which a typedef name can be redefined, and once for parsing a
9933 declaration in which that can't be done.  Here is a part of the
9934 duplication, with actions omitted for brevity:
9936 @example
9937 @group
9938 initdcl:
9939   declarator maybeasm '=' init
9940 | declarator maybeasm
9942 @end group
9944 @group
9945 notype_initdcl:
9946   notype_declarator maybeasm '=' init
9947 | notype_declarator maybeasm
9949 @end group
9950 @end example
9952 @noindent
9953 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
9954 cannot.  The distinction between @code{declarator} and
9955 @code{notype_declarator} is the same sort of thing.
9957 There is some similarity between this technique and a lexical tie-in
9958 (described next), in that information which alters the lexical analysis is
9959 changed during parsing by other parts of the program.  The difference is
9960 here the information is global, and is used for other purposes in the
9961 program.  A true lexical tie-in has a special-purpose flag controlled by
9962 the syntactic context.
9964 @node Lexical Tie-ins
9965 @section Lexical Tie-ins
9966 @cindex lexical tie-in
9968 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
9969 which is set by Bison actions, whose purpose is to alter the way tokens are
9970 parsed.
9972 For example, suppose we have a language vaguely like C, but with a special
9973 construct @samp{hex (@var{hex-expr})}.  After the keyword @code{hex} comes
9974 an expression in parentheses in which all integers are hexadecimal.  In
9975 particular, the token @samp{a1b} must be treated as an integer rather than
9976 as an identifier if it appears in that context.  Here is how you can do it:
9978 @example
9979 @group
9981   int hexflag;
9982   int yylex (void);
9983   void yyerror (char const *);
9986 @dots{}
9987 @end group
9988 @group
9989 expr:
9990   IDENTIFIER
9991 | constant
9992 | HEX '('        @{ hexflag = 1; @}
9993     expr ')'     @{ hexflag = 0; $$ = $4; @}
9994 | expr '+' expr  @{ $$ = make_sum ($1, $3); @}
9995 @dots{}
9997 @end group
9999 @group
10000 constant:
10001   INTEGER
10002 | STRING
10004 @end group
10005 @end example
10007 @noindent
10008 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
10009 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
10010 with letters are parsed as integers if possible.
10012 The declaration of @code{hexflag} shown in the prologue of the grammar file
10013 is needed to make it accessible to the actions (@pxref{Prologue}).  You must
10014 also write the code in @code{yylex} to obey the flag.
10016 @node Tie-in Recovery
10017 @section Lexical Tie-ins and Error Recovery
10019 Lexical tie-ins make strict demands on any error recovery rules you have.
10020 @xref{Error Recovery}.
10022 The reason for this is that the purpose of an error recovery rule is to
10023 abort the parsing of one construct and resume in some larger construct.
10024 For example, in C-like languages, a typical error recovery rule is to skip
10025 tokens until the next semicolon, and then start a new statement, like this:
10027 @example
10028 stmt:
10029   expr ';'
10030 | IF '(' expr ')' stmt @{ @dots{} @}
10031 @dots{}
10032 | error ';'  @{ hexflag = 0; @}
10034 @end example
10036 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
10037 construct, this error rule will apply, and then the action for the
10038 completed @samp{hex (@var{expr})} will never run.  So @code{hexflag} would
10039 remain set for the entire rest of the input, or until the next @code{hex}
10040 keyword, causing identifiers to be misinterpreted as integers.
10042 To avoid this problem the error recovery rule itself clears @code{hexflag}.
10044 There may also be an error recovery rule that works within expressions.
10045 For example, there could be a rule which applies within parentheses
10046 and skips to the close-parenthesis:
10048 @example
10049 @group
10050 expr:
10051   @dots{}
10052 | '(' expr ')'   @{ $$ = $2; @}
10053 | '(' error ')'
10054 @dots{}
10055 @end group
10056 @end example
10058 If this rule acts within the @code{hex} construct, it is not going to abort
10059 that construct (since it applies to an inner level of parentheses within
10060 the construct).  Therefore, it should not clear the flag: the rest of
10061 the @code{hex} construct should be parsed with the flag still in effect.
10063 What if there is an error recovery rule which might abort out of the
10064 @code{hex} construct or might not, depending on circumstances?  There is no
10065 way you can write the action to determine whether a @code{hex} construct is
10066 being aborted or not.  So if you are using a lexical tie-in, you had better
10067 make sure your error recovery rules are not of this kind.  Each rule must
10068 be such that you can be sure that it always will, or always won't, have to
10069 clear the flag.
10071 @c ================================================== Debugging Your Parser
10073 @node Debugging
10074 @chapter Debugging Your Parser
10076 Developing a parser can be a challenge, especially if you don't understand
10077 the algorithm (@pxref{Algorithm}).  This chapter explains how to understand
10078 and debug a parser.
10080 The most frequent issue users face is solving their conflicts.  To fix them,
10081 the first step is understanding how they arise in a given grammar.  This is
10082 made much easier by automated generation of counterexamples, cover in the
10083 first section (@pxref{Counterexamples}).
10085 In most cases though, looking at the structure of the automaton is still
10086 needed.  The following sections explain how to generate and read the
10087 detailed structural description of the automaton.  There are several formats
10088 available:
10089 @itemize @minus
10090 @item
10091 as text, see @ref{Understanding};
10093 @item
10094 as a graph, see @ref{Graphviz};
10096 @item
10097 or as a markup report that can be turned, for instance, into HTML, see
10098 @ref{Xml}.
10099 @end itemize
10101 The last section focuses on the dynamic part of the parser: how to enable
10102 and understand the parser run-time traces (@pxref{Tracing}).
10104 @menu
10105 * Counterexamples::   Understanding conflicts.
10106 * Understanding::     Understanding the structure of your parser.
10107 * Graphviz::          Getting a visual representation of the parser.
10108 * Xml::               Getting a markup representation of the parser.
10109 * Tracing::           Tracing the execution of your parser.
10110 @end menu
10112 @node Counterexamples
10113 @section Generation of Counterexamples
10114 @cindex cex
10115 @cindex counterexamples
10116 @cindex conflict counterexamples
10118 Solving conflicts is probably the most delicate part of the design of an LR
10119 parser, as demonstrated by the number of sections devoted to them in this
10120 very documentation.  To solve a conflict, one must understand it: when does
10121 it occur?  Is it because of a flaw in the grammar?  Is it rather because
10122 LR(1) cannot cope with this grammar?
10124 One difficulty is that conflicts occur in the @emph{automaton}, and it can
10125 be tricky to relate them to issues in the @emph{grammar} itself.  With
10126 experience and patience, analysis of the detailed description of the
10127 automaton (@pxref{Understanding}) allows one to find example strings that
10128 reach these conflicts.
10130 That task is made much easier thanks to the generation of counterexamples,
10131 initially developed by Chinawat Isradisaikul and Andrew Myers
10132 @pcite{Isradisaikul 2015}.
10134 As a first example, see the grammar of @ref{Shift/Reduce}, which features
10135 one shift/reduce conflict:
10137 @c see doc/else.y
10138 @example
10139 $ @kbd{bison else.y}
10140 else.y: @dwarning{warning}: 1 shift/reduce conflict [@dwarning{-Wconflicts-sr}]
10141 else.y: @dnotice{note}: rerun with option '-Wcounterexamples' to generate conflict counterexamples
10142 @end example
10144 @noindent
10145 Let's rerun @command{bison} with the option
10146 @option{-Wcex}/@option{-Wcounterexamples}@inlinefmt{info, (the following
10147 output is actually in color)}:
10149 @example
10150 else.y: @dwarning{warning}: 1 shift/reduce conflict [@dwarning{-Wconflicts-sr}]
10151 else.y: @dwarning{warning}: shift/reduce conflict on token "else" [@dwarning{-Wcounterexamples}]
10152 @danglingElseCex
10153 @end example
10155 This shows two different derivations for one single expression, which proves
10156 that the grammar is ambiguous.
10158 @sp 1
10160 As a more delicate example, consider the example grammar of
10161 @ref{Reduce/Reduce}, which features a reduce/reduce conflict:
10163 @c doc/sequence.y
10164 @example
10166 sequence:
10167   %empty
10168 | maybeword
10169 | sequence "word"
10171 maybeword:
10172   %empty
10173 | "word"
10175 @end example
10177 Bison generates the following counterexamples:
10179 @example
10180 @group
10181 $ @kbd{bison -Wcex sequence.y}
10182 sequence.y: @dwarning{warning}: 1 shift/reduce conflict [@dwarning{-Wconflicts-sr}]
10183 sequence.y: @dwarning{warning}: 2 reduce/reduce conflicts [@dwarning{-Wconflicts-rr}]
10184 @end group
10185 @ifnottex
10186 @group
10187 sequence.y: @dwarning{warning}: shift/reduce conflict on token "word" [@dwarning{-Wcounterexamples}]
10188   Example: @red{•} @green{"word"}
10189   Shift derivation
10190     @yellow{sequence}
10191     @yellow{↳ 2:} @green{maybeword}
10192           @green{↳ 5:} @red{•} @green{"word"}
10193   Example: @red{•} @yellow{"word"}
10194   Reduce derivation
10195     @yellow{sequence}
10196     @yellow{↳ 3:} @green{sequence} @yellow{"word"}
10197           @green{↳ 1:} @red{•}
10198 @end group
10199 @group
10200 sequence.y: @dwarning{warning}: reduce/reduce conflict on tokens $end, "word" [@dwarning{-Wcounterexamples}]
10201   Example: @red{•}
10202   First reduce derivation
10203     @yellow{sequence}
10204     @yellow{↳ 1:} @red{•}
10205   Example: @red{•}
10206   Second reduce derivation
10207     @yellow{sequence}
10208     @yellow{↳ 2:} @green{maybeword}
10209           @green{↳ 4:} @red{•}
10210 @end group
10211 @group
10212 sequence.y: @dwarning{warning}: shift/reduce conflict on token "word" [@dwarning{-Wcounterexamples}]
10213   Example: @red{•} @green{"word"}
10214   Shift derivation
10215     @yellow{sequence}
10216     @yellow{↳ 2:} @green{maybeword}
10217           @green{↳ 5:} @red{•} @green{"word"}
10218   Example: @red{•} @yellow{"word"}
10219   Reduce derivation
10220     @yellow{sequence}
10221     @yellow{↳ 3:} @green{sequence}        @yellow{"word"}
10222           @green{↳ 2:} @blue{maybeword}
10223                 @blue{↳ 4:} @red{•}
10224 @end group
10225 @group
10226 sequence.y:8.3-45: @dwarning{warning}: rule useless in parser due to conflicts [@dwarning{-Wother}]
10227     8 |   @dwarning{%empty    @{ printf ("empty maybeword\n"); @}}
10228       |   @dwarning{^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
10229 @end group
10230 @end ifnottex
10231 @iftex
10232 @group
10233 sequence.y: @dwarning{warning}: shift/reduce conflict on token "word" [@dwarning{-Wcounterexamples}]
10234   Example: @red{•} @green{"word"}
10235   Shift derivation
10236     @yellow{sequence}
10237     @yellow{@arrow{} 2:} @green{maybeword}
10238           @green{@arrow{} 5:} @red{•} @green{"word"}
10239   Example: @red{•} @yellow{"word"}
10240   Reduce derivation
10241     @yellow{sequence}
10242     @yellow{@arrow{} 3:} @green{sequence} @yellow{"word"}
10243           @green{@arrow{} 1:} @red{•}
10244 @end group
10245 @group
10246 sequence.y: @dwarning{warning}: reduce/reduce conflict on tokens $end, "word" [@dwarning{-Wcounterexamples}]
10247   Example: @red{•}
10248   First reduce derivation
10249     @yellow{sequence}
10250     @yellow{@arrow{} 1:} @red{•}
10251   Example: @red{•}
10252   Second reduce derivation
10253     @yellow{sequence}
10254     @yellow{@arrow{} 2:} @green{maybeword}
10255           @green{@arrow{}: 4} @red{•}
10256 @end group
10257 @group
10258 sequence.y: @dwarning{warning}: shift/reduce conflict on token "word" [@dwarning{-Wcounterexamples}]
10259   Example: @red{•} @green{"word"}
10260   Shift derivation
10261     @yellow{sequence}
10262     @yellow{@arrow{} 2:} @green{maybeword}
10263           @green{@arrow{} 5:} @red{•} @green{"word"}
10264   Example: @red{•} @yellow{"word"}
10265   Reduce derivation
10266     @yellow{sequence}
10267     @yellow{@arrow{} 3:} @green{sequence}        @yellow{"word"}
10268           @green{@arrow{} 2:} @blue{maybeword}
10269                 @blue{@arrow{} 4:} @red{•}
10270 @end group
10271 @group
10272 sequence.y:8.3-45: @dwarning{warning}: rule useless in parser due to conflicts [@dwarning{-Wother}]
10273     8 |   @dwarning{%empty    @{ printf ("empty maybeword\n"); @}}
10274       |   @dwarning{^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
10275 @end group
10276 @end iftex
10277 @end example
10279 Each of these three conflicts, again, prove that the grammar is ambiguous.
10280 For instance, the second conflict (the reduce/reduce one) shows that the
10281 grammar accepts the empty input in two different ways.
10283 @sp 1
10285 Sometimes, the search will not find an example that can be derived in two
10286 ways.  In these cases, counterexample generation will provide two examples
10287 that are the same up until the dot.  Most notably, this will happen when
10288 your grammar requires a stronger parser (more lookahead, LR instead of
10289 LALR).  The following example isn't LR(1):
10291 @c doc/ids.y
10292 @example
10293 %token ID
10295 s: a ID
10296 a: expr
10297 expr: %empty | expr ID ','
10298 @end example
10300 @command{bison} reports:
10302 @example
10303 ids.y: @dwarning{warning}: 1 shift/reduce conflict [@dwarning{-Wconflicts-sr}]
10304 ids.y: @dwarning{warning}: shift/reduce conflict on token ID [@dwarning{-Wcounterexamples}]
10305 @ifnottex
10306 @group
10307   First example: @purple{expr} @red{•} @purple{ID ','} @green{ID} @yellow{$end}
10308   Shift derivation
10309     @yellow{$accept}
10310     @yellow{↳ 0:} @green{s}                                 @yellow{$end}
10311          @green{↳ 1:} @blue{a}                        @green{ID}
10312               @blue{↳ 2:} @purple{expr}
10313                     @purple{↳ 4: expr} @red{•} @purple{ID ','}
10314   Second example: @blue{expr} @red{•} @green{ID} @yellow{$end}
10315   Reduce derivation
10316     @yellow{$accept}
10317     @yellow{↳ 0:} @green{s}                   @yellow{$end}
10318          @green{↳ 1:} @blue{a}           @green{ID}
10319               @blue{↳ 2: expr} @red{•}
10320 @end group
10321 @group
10322 ids.y:4.4-7: @dwarning{warning}: rule useless in parser due to conflicts [@dwarning{-Wother}]
10323     4 | a: expr
10324       |    ^~~~
10325 @end group
10326 @end ifnottex
10327 @iftex
10328 @group
10329   First example: @purple{expr} @red{•} @purple{ID ','} @green{ID} @yellow{$end}
10330   Shift derivation
10331     @yellow{$accept}
10332     @yellow{@arrow{} 0:} @green{s}                                   @yellow{$end}
10333           @green{@arrow{} 1:} @blue{a}                         @green{ID}
10334                 @blue{@arrow{} 2:} @purple{expr}
10335                       @purple{@arrow{} 4: expr} @red{•} @purple{ID ','}
10336   Second example: @blue{expr} @red{•} @green{ID} @yellow{$end}
10337   Reduce derivation
10338     @yellow{$accept}
10339     @yellow{@arrow{} 0:} @green{s}                     @yellow{$end}
10340           @green{@arrow{} 1:} @blue{a}            @green{ID}
10341                 @blue{@arrow{} 2: expr} @red{•}
10342 @end group
10343 @group
10344 ids.y:4.4-7: @dwarning{warning}: rule useless in parser due to conflicts [@dwarning{-Wother}]
10345     4 | a: expr
10346       |    ^~~~
10347 @end group
10348 @end iftex
10349 @end example
10351 This conflict is caused by the parser not having enough information to know
10352 the difference between these two examples.  The parser would need an
10353 additional lookahead token to know whether or not a comma follows the
10354 @code{ID} after @code{expr}.  These types of conflicts tend to be more
10355 difficult to fix, and usually need a rework of the grammar.  In this case,
10356 it can be fixed by changing around the recursion: @code{expr: ID | ',' expr
10357 ID}.
10359 Alternatively, you might also want to consider using a GLR parser
10360 (@pxref{GLR Parsers}).
10362 @sp 1
10364 On occasions, it is useful to look at counterexamples @emph{in situ}: with
10365 the automaton report (@xref{Understanding}, in particular @ref{state-8,,
10366 State 8}).
10368 @node Understanding
10369 @section Understanding Your Parser
10371 Bison parsers are @dfn{shift/reduce automata} (@pxref{Algorithm}).  In some
10372 cases (much more frequent than one would hope), looking at this automaton is
10373 required to tune or simply fix a parser.
10375 The textual file is generated when the options @option{--report} or
10376 @option{--verbose} are specified, see @ref{Invocation}.  Its name is made by
10377 removing @samp{.tab.c} or @samp{.c} from the parser implementation file
10378 name, and adding @samp{.output} instead.  Therefore, if the grammar file is
10379 @file{foo.y}, then the parser implementation file is called @file{foo.tab.c}
10380 by default.  As a consequence, the verbose output file is called
10381 @file{foo.output}.
10383 The following grammar file, @file{calc.y}, will be used in the sequel:
10385 @c doc/calc.y
10386 @example
10387 @group
10388 %union
10390   int ival;
10391   const char *sval;
10393 @end group
10394 @group
10395 %token <ival> NUM
10396 %nterm <ival> exp
10397 @end group
10398 @group
10399 %token <sval> STR
10400 %nterm <sval> useless
10401 @end group
10402 @group
10403 %left '+' '-'
10404 %left '*'
10405 @end group
10407 @group
10408 exp:
10409   exp '+' exp
10410 | exp '-' exp
10411 | exp '*' exp
10412 | exp '/' exp
10413 | NUM
10415 @end group
10416 useless: STR;
10418 @end example
10420 @command{bison} reports:
10422 @smallexample
10423 calc.y: @dwarning{warning}: 1 nonterminal useless in grammar [@dwarning{-Wother}]
10424 calc.y: @dwarning{warning}: 1 rule useless in grammar [@dwarning{-Wother}]
10425 calc.y:19.1-7: @dwarning{warning}: nonterminal useless in grammar: useless [@dwarning{-Wother}]
10426    19 | @dwarning{useless: STR;}
10427       | @dwarning{^~~~~~~}
10428 calc.y: @dwarning{warning}: 7 shift/reduce conflicts [@dwarning{-Wconflicts-sr}]
10429 calc.y: @dnotice{note}: rerun with option '-Wcounterexamples' to generate conflict counterexamples
10430 @end smallexample
10432 Going back to the calc example, when given @option{--report=state},
10433 in addition to @file{calc.tab.c}, it creates a file @file{calc.output}
10434 with contents detailed below.  The order of the output and the exact
10435 presentation might vary, but the interpretation is the same.
10437 @noindent
10438 @cindex token, useless
10439 @cindex useless token
10440 @cindex nonterminal, useless
10441 @cindex useless nonterminal
10442 @cindex rule, useless
10443 @cindex useless rule
10444 The first section reports useless tokens, nonterminals and rules.  Useless
10445 nonterminals and rules are removed in order to produce a smaller parser, but
10446 useless tokens are preserved, since they might be used by the scanner (note
10447 the difference between ``useless'' and ``unused'' below):
10449 @example
10450 Nonterminals useless in grammar
10451    useless
10453 Terminals unused in grammar
10454    STR
10456 Rules useless in grammar
10457     6 useless: STR
10458 @end example
10460 @noindent
10461 The next section lists states that still have conflicts.
10463 @example
10464 State 8 conflicts: 1 shift/reduce
10465 State 9 conflicts: 1 shift/reduce
10466 State 10 conflicts: 1 shift/reduce
10467 State 11 conflicts: 4 shift/reduce
10468 @end example
10470 @noindent
10471 Then Bison reproduces the exact grammar it used:
10473 @example
10474 Grammar
10476     0 $accept: exp $end
10478     1 exp: exp '+' exp
10479     2    | exp '-' exp
10480     3    | exp '*' exp
10481     4    | exp '/' exp
10482     5    | NUM
10483 @end example
10485 @noindent
10486 and reports the uses of the symbols:
10488 @example
10489 @group
10490 Terminals, with rules where they appear
10492     $end (0) 0
10493     '*' (42) 3
10494     '+' (43) 1
10495     '-' (45) 2
10496     '/' (47) 4
10497     error (256)
10498     NUM <ival> (258) 5
10499     STR <sval> (259)
10500 @end group
10502 @group
10503 Nonterminals, with rules where they appear
10505     $accept (9)
10506         on left: 0
10507     exp <ival> (10)
10508         on left: 1 2 3 4 5
10509         on right: 0 1 2 3 4
10510 @end group
10511 @end example
10513 @noindent
10514 @cindex item
10515 @cindex dotted rule
10516 @cindex rule, dotted
10517 Bison then proceeds onto the automaton itself, describing each state with
10518 its set of @dfn{items}, also known as @dfn{dotted rules}.  Each item is a
10519 production rule together with a point (@samp{.}) marking the location of the
10520 input cursor.
10522 @example
10523 State 0
10525     0 $accept: â€¢ exp $end
10527     NUM  shift, and go to state 1
10529     exp  go to state 2
10530 @end example
10532 This reads as follows: ``state 0 corresponds to being at the very
10533 beginning of the parsing, in the initial rule, right before the start
10534 symbol (here, @code{exp}).  When the parser returns to this state right
10535 after having reduced a rule that produced an @code{exp}, the control
10536 flow jumps to state 2.  If there is no such transition on a nonterminal
10537 symbol, and the lookahead is a @code{NUM}, then this token is shifted onto
10538 the parse stack, and the control flow jumps to state 1.  Any other
10539 lookahead triggers a syntax error.''
10541 @cindex core, item set
10542 @cindex item set core
10543 @cindex kernel, item set
10544 @cindex item set core
10545 Even though the only active rule in state 0 seems to be rule 0, the
10546 report lists @code{NUM} as a lookahead token because @code{NUM} can be
10547 at the beginning of any rule deriving an @code{exp}.  By default Bison
10548 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
10549 you want to see more detail you can invoke @command{bison} with
10550 @option{--report=itemset} to list the derived items as well:
10552 @example
10553 State 0
10555     0 $accept: â€¢ exp $end
10556     1 exp: â€¢ exp '+' exp
10557     2    | â€¢ exp '-' exp
10558     3    | â€¢ exp '*' exp
10559     4    | â€¢ exp '/' exp
10560     5    | â€¢ NUM
10562     NUM  shift, and go to state 1
10564     exp  go to state 2
10565 @end example
10567 @noindent
10568 In the state 1@dots{}
10570 @example
10571 State 1
10573     5 exp: NUM â€¢
10575     $default  reduce using rule 5 (exp)
10576 @end example
10578 @noindent
10579 the rule 5, @samp{exp: NUM;}, is completed.  Whatever the lookahead token
10580 (@samp{$default}), the parser will reduce it.  If it was coming from State
10581 0, then, after this reduction it will return to state 0, and will jump to
10582 state 2 (@samp{exp: go to state 2}).
10584 @example
10585 State 2
10587     0 $accept: exp â€¢ $end
10588     1 exp: exp â€¢ '+' exp
10589     2    | exp â€¢ '-' exp
10590     3    | exp â€¢ '*' exp
10591     4    | exp â€¢ '/' exp
10593     $end  shift, and go to state 3
10594     '+'   shift, and go to state 4
10595     '-'   shift, and go to state 5
10596     '*'   shift, and go to state 6
10597     '/'   shift, and go to state 7
10598 @end example
10600 @noindent
10601 In state 2, the automaton can only shift a symbol.  For instance, because of
10602 the item @samp{exp: exp â€¢ '+' exp}, if the lookahead is @samp{+} it is
10603 shifted onto the parse stack, and the automaton jumps to state 4,
10604 corresponding to the item @samp{exp: exp '+' â€¢ exp}.  Since there is no
10605 default action, any lookahead not listed triggers a syntax error.
10607 @cindex accepting state
10608 The state 3 is named the @dfn{final state}, or the @dfn{accepting
10609 state}:
10611 @example
10612 State 3
10614     0 $accept: exp $end â€¢
10616     $default  accept
10617 @end example
10619 @noindent
10620 the initial rule is completed (the start symbol and the end-of-input were
10621 read), the parsing exits successfully.
10623 The interpretation of states 4 to 7 is straightforward, and is left to
10624 the reader.
10626 @example
10627 State 4
10629     1 exp: exp '+' â€¢ exp
10631     NUM  shift, and go to state 1
10633     exp  go to state 8
10636 State 5
10638     2 exp: exp '-' â€¢ exp
10640     NUM  shift, and go to state 1
10642     exp  go to state 9
10645 State 6
10647     3 exp: exp '*' â€¢ exp
10649     NUM  shift, and go to state 1
10651     exp  go to state 10
10654 State 7
10656     4 exp: exp '/' â€¢ exp
10658     NUM  shift, and go to state 1
10660     exp  go to state 11
10661 @end example
10663 @anchor{state-8}
10664 As was announced in beginning of the report, @samp{State 8 conflicts:
10665 1 shift/reduce}:
10667 @example
10668 State 8
10670     1 exp: exp â€¢ '+' exp
10671     1    | exp '+' exp â€¢
10672     2    | exp â€¢ '-' exp
10673     3    | exp â€¢ '*' exp
10674     4    | exp â€¢ '/' exp
10676     '*'  shift, and go to state 6
10677     '/'  shift, and go to state 7
10679     '/'       [reduce using rule 1 (exp)]
10680     $default  reduce using rule 1 (exp)
10681 @end example
10683 Indeed, there are two actions associated to the lookahead @samp{/}:
10684 either shifting (and going to state 7), or reducing rule 1.  The
10685 conflict means that either the grammar is ambiguous, or the parser lacks
10686 information to make the right decision.  Indeed the grammar is
10687 ambiguous, as, since we did not specify the precedence of @samp{/}, the
10688 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
10689 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
10690 NUM}, which corresponds to reducing rule 1.
10692 Because in deterministic parsing a single decision can be made, Bison
10693 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce}.
10694 Discarded actions are reported between square brackets.
10696 Note that all the previous states had a single possible action: either
10697 shifting the next token and going to the corresponding state, or
10698 reducing a single rule.  In the other cases, i.e., when shifting
10699 @emph{and} reducing is possible or when @emph{several} reductions are
10700 possible, the lookahead is required to select the action.  State 8 is
10701 one such state: if the lookahead is @samp{*} or @samp{/} then the action
10702 is shifting, otherwise the action is reducing rule 1.  In other words,
10703 the first two items, corresponding to rule 1, are not eligible when the
10704 lookahead token is @samp{*}, since we specified that @samp{*} has higher
10705 precedence than @samp{+}.  More generally, some items are eligible only
10706 with some set of possible lookahead tokens.  When run with
10707 @option{--report=lookahead}, Bison specifies these lookahead tokens:
10709 @example
10710 State 8
10712     1 exp: exp â€¢ '+' exp
10713     1    | exp '+' exp â€¢  [$end, '+', '-', '/']
10714     2    | exp â€¢ '-' exp
10715     3    | exp â€¢ '*' exp
10716     4    | exp â€¢ '/' exp
10718     '*'  shift, and go to state 6
10719     '/'  shift, and go to state 7
10721     '/'       [reduce using rule 1 (exp)]
10722     $default  reduce using rule 1 (exp)
10723 @end example
10725 Note however that while @samp{NUM + NUM / NUM} is ambiguous (which results in
10726 the conflicts on @samp{/}), @samp{NUM + NUM * NUM} is not: the conflict was
10727 solved thanks to associativity and precedence directives.  If invoked with
10728 @option{--report=solved}, Bison includes information about the solved
10729 conflicts in the report:
10731 @example
10732 Conflict between rule 1 and token '+' resolved as reduce (%left '+').
10733 Conflict between rule 1 and token '-' resolved as reduce (%left '-').
10734 Conflict between rule 1 and token '*' resolved as shift ('+' < '*').
10735 @end example
10737 When given @option{--report=counterexamples}, @command{bison} will generate
10738 counterexamples within the report, augmented with the corresponding items
10739 (@pxref{Counterexamples}).
10741 @ifnottex
10742 @example
10743 shift/reduce conflict on token '/':
10744     1 exp: exp '+' exp â€¢
10745     4 exp: exp â€¢ '/' exp
10746 @group
10747   Example: exp '+' exp â€¢ '/' exp
10748   Shift derivation
10749     exp
10750     â†³ 1: exp '+' exp
10751                  â†³ 4: exp â€¢ '/' exp
10752   Example: exp '+' exp â€¢ '/' exp
10753   Reduce derivation
10754     exp
10755     â†³ 4: exp                 '/' exp
10756          â†³ 1: exp '+' exp â€¢
10757 @end group
10758 @end example
10759 @end ifnottex
10760 @iftex
10761 @example
10762 shift/reduce conflict on token '/':
10763     1 exp: exp '+' exp â€¢
10764     4 exp: exp â€¢ '/' exp
10765 @group
10766   Example: exp '+' exp â€¢ '/' exp
10767   Shift derivation
10768     exp
10769     @arrow{} 1: exp '+' exp
10770                   @arrow{} 4: exp â€¢ '/' exp
10771   Example: exp '+' exp â€¢ '/' exp
10772   Reduce derivation
10773     exp
10774     @arrow{} 4: exp                '/' exp
10775           @arrow{} 1: exp '+' exp â€¢
10776 @end group
10777 @end example
10778 @end iftex
10780 This shows two separate derivations in the grammar for the same @code{exp}:
10781 @samp{e1 + e2 / e3}.  The derivations show how your rules would parse the
10782 given example. Here, the first derivation completes a reduction when seeing
10783 @samp{/}, causing @samp{e1 + e2} to be grouped as an @code{exp}. The second
10784 derivation shifts on @samp{/}, resulting in @samp{e2 / e3} being grouped as
10785 an @code{exp}.  Therefore, it is easy to see that adding
10786 precedence/associativity directives would fix this conflict.
10788 The remaining states are similar:
10790 @example
10791 @group
10792 State 9
10794     1 exp: exp â€¢ '+' exp
10795     2    | exp â€¢ '-' exp
10796     2    | exp '-' exp â€¢
10797     3    | exp â€¢ '*' exp
10798     4    | exp â€¢ '/' exp
10800     '*'  shift, and go to state 6
10801     '/'  shift, and go to state 7
10803     '/'       [reduce using rule 2 (exp)]
10804     $default  reduce using rule 2 (exp)
10805 @end group
10807 @group
10808 State 10
10810     1 exp: exp â€¢ '+' exp
10811     2    | exp â€¢ '-' exp
10812     3    | exp â€¢ '*' exp
10813     3    | exp '*' exp â€¢
10814     4    | exp â€¢ '/' exp
10816     '/'  shift, and go to state 7
10818     '/'       [reduce using rule 3 (exp)]
10819     $default  reduce using rule 3 (exp)
10820 @end group
10822 @group
10823 State 11
10825     1 exp: exp â€¢ '+' exp
10826     2    | exp â€¢ '-' exp
10827     3    | exp â€¢ '*' exp
10828     4    | exp â€¢ '/' exp
10829     4    | exp '/' exp â€¢
10831     '+'  shift, and go to state 4
10832     '-'  shift, and go to state 5
10833     '*'  shift, and go to state 6
10834     '/'  shift, and go to state 7
10836     '+'       [reduce using rule 4 (exp)]
10837     '-'       [reduce using rule 4 (exp)]
10838     '*'       [reduce using rule 4 (exp)]
10839     '/'       [reduce using rule 4 (exp)]
10840     $default  reduce using rule 4 (exp)
10841 @end group
10842 @end example
10844 @noindent
10845 Observe that state 11 contains conflicts not only due to the lack of
10846 precedence of @samp{/} with respect to @samp{+}, @samp{-}, and @samp{*}, but
10847 also because the associativity of @samp{/} is not specified.
10849 Bison may also produce an HTML version of this output, via an XML file and
10850 XSLT processing (@pxref{Xml}).
10852 @c ================================================= Graphical Representation
10854 @node Graphviz
10855 @section Visualizing Your Parser
10856 @cindex dot
10858 As another means to gain better understanding of the shift/reduce
10859 automaton corresponding to the Bison parser, a DOT file can be generated. Note
10860 that debugging a real grammar with this is tedious at best, and impractical
10861 most of the times, because the generated files are huge (the generation of
10862 a PDF or PNG file from it will take very long, and more often than not it will
10863 fail due to memory exhaustion). This option was rather designed for beginners,
10864 to help them understand LR parsers.
10866 This file is generated when the @option{--graph} option is specified
10867 (@pxref{Invocation}).  Its name is made by removing
10868 @samp{.tab.c} or @samp{.c} from the parser implementation file name, and
10869 adding @samp{.gv} instead.  If the grammar file is @file{foo.y}, the
10870 Graphviz output file is called @file{foo.gv}.  A DOT file may also be
10871 produced via an XML file and XSLT processing (@pxref{Xml}).
10874 The following grammar file, @file{rr.y}, will be used in the sequel:
10876 @example
10878 @group
10879 exp: a ";" | b ".";
10880 a: "0";
10881 b: "0";
10882 @end group
10883 @end example
10885 The graphical output
10886 @ifnotinfo
10887 (see @ref{fig:graph})
10888 @end ifnotinfo
10889 is very similar to the textual one, and as such it is easier understood by
10890 making direct comparisons between them.  @xref{Debugging}, for a detailed
10891 analysis of the textual report.
10893 @ifnotinfo
10894 @float Figure,fig:graph
10895 @center @image{figs/example, 430pt,,,.svg}
10896 @caption{A graphical rendering of the parser.}
10897 @end float
10898 @end ifnotinfo
10900 @subheading Graphical Representation of States
10902 The items (dotted rules) for each state are grouped together in graph nodes.
10903 Their numbering is the same as in the verbose file. See the following
10904 points, about transitions, for examples
10906 When invoked with @option{--report=lookaheads}, the lookahead tokens, when
10907 needed, are shown next to the relevant rule between square brackets as a
10908 comma separated list. This is the case in the figure for the representation of
10909 reductions, below.
10911 @sp 1
10913 The transitions are represented as directed edges between the current and
10914 the target states.
10916 @subheading Graphical Representation of Shifts
10918 Shifts are shown as solid arrows, labeled with the lookahead token for that
10919 shift. The following describes a reduction in the @file{rr.output} file:
10921 @example
10922 @group
10923 State 3
10925     1 exp: a â€¢ ";"
10927     ";"  shift, and go to state 6
10928 @end group
10929 @end example
10931 A Graphviz rendering of this portion of the graph could be:
10933 @center @image{figs/example-shift, 100pt,,,.svg}
10935 @subheading Graphical Representation of Reductions
10937 Reductions are shown as solid arrows, leading to a diamond-shaped node
10938 bearing the number of the reduction rule. The arrow is labeled with the
10939 appropriate comma separated lookahead tokens. If the reduction is the default
10940 action for the given state, there is no such label.
10942 This is how reductions are represented in the verbose file @file{rr.output}:
10943 @example
10944 State 1
10946     3 a: "0" â€¢  [";"]
10947     4 b: "0" â€¢  ["."]
10949     "."       reduce using rule 4 (b)
10950     $default  reduce using rule 3 (a)
10951 @end example
10953 A Graphviz rendering of this portion of the graph could be:
10955 @center @image{figs/example-reduce, 120pt,,,.svg}
10957 When unresolved conflicts are present, because in deterministic parsing
10958 a single decision can be made, Bison can arbitrarily choose to disable a
10959 reduction, see @ref{Shift/Reduce}.  Discarded actions
10960 are distinguished by a red filling color on these nodes, just like how they are
10961 reported between square brackets in the verbose file.
10963 The reduction corresponding to the rule number 0 is the acceptation
10964 state. It is shown as a blue diamond, labeled ``Acc''.
10966 @subheading Graphical Representation of Gotos
10968 The @samp{go to} jump transitions are represented as dotted lines bearing
10969 the name of the rule being jumped to.
10971 @c ================================================= XML
10973 @node Xml
10974 @section Visualizing your parser in multiple formats
10975 @cindex xml
10977 Bison supports two major report formats: textual output
10978 (@pxref{Understanding}) when invoked
10979 with option @option{--verbose}, and DOT
10980 (@pxref{Graphviz}) when invoked with
10981 option @option{--graph}. However,
10982 another alternative is to output an XML file that may then be, with
10983 @command{xsltproc}, rendered as either a raw text format equivalent to the
10984 verbose file, or as an HTML version of the same file, with clickable
10985 transitions, or even as a DOT. The @file{.output} and DOT files obtained via
10986 XSLT have no difference whatsoever with those obtained by invoking
10987 @command{bison} with options @option{--verbose} or @option{--graph}.
10989 The XML file is generated when the options @option{-x} or
10990 @option{--xml[=FILE]} are specified, see @ref{Invocation}.
10991 If not specified, its name is made by removing @samp{.tab.c} or @samp{.c}
10992 from the parser implementation file name, and adding @samp{.xml} instead.
10993 For instance, if the grammar file is @file{foo.y}, the default XML output
10994 file is @file{foo.xml}.
10996 Bison ships with a @file{data/xslt} directory, containing XSL Transformation
10997 files to apply to the XML file. Their names are non-ambiguous:
10999 @table @file
11000 @item xml2dot.xsl
11001 Used to output a copy of the DOT visualization of the automaton.
11002 @item xml2text.xsl
11003 Used to output a copy of the @samp{.output} file.
11004 @item xml2xhtml.xsl
11005 Used to output an xhtml enhancement of the @samp{.output} file.
11006 @end table
11008 Sample usage (requires @command{xsltproc}):
11009 @example
11010 $ @kbd{bison -x gr.y}
11011 @group
11012 $ @kbd{bison --print-datadir}
11013 /usr/local/share/bison
11014 @end group
11015 $ @kbd{xsltproc /usr/local/share/bison/xslt/xml2xhtml.xsl gr.xml >gr.html}
11016 @end example
11018 @c ================================================= Tracing
11020 @node Tracing
11021 @section Tracing Your Parser
11022 @findex yydebug
11023 @cindex debugging
11024 @cindex tracing the parser
11026 When a Bison grammar compiles properly but parses ``incorrectly'', the
11027 @code{yydebug} parser-trace feature helps figuring out why.
11029 @menu
11030 * Enabling Traces::    Activating run-time trace support
11031 * Mfcalc Traces::      Extending @code{mfcalc} to support traces
11032 @end menu
11034 @node Enabling Traces
11035 @subsection  Enabling Traces
11036 There are several means to enable compilation of trace facilities, in
11037 decreasing order of preference:
11039 @table @asis
11040 @item the variable @samp{parse.trace}
11041 @findex %define parse.trace
11042 Add the @samp{%define parse.trace} directive (@pxref{%define
11043 Summary}), or pass the @option{-Dparse.trace} option
11044 (@pxref{Tuning the Parser}).  This is a Bison extension.  Unless POSIX and
11045 Yacc portability matter to you, this is the preferred solution.
11047 @item the option @option{-t} (POSIX Yacc compliant)
11048 @itemx the option @option{--debug} (Bison extension)
11049 Use the @option{-t} option when you run Bison (@pxref{Invocation}).  With
11050 @samp{%define api.prefix @{c@}}, it defines @code{CDEBUG} to 1, otherwise it
11051 defines @code{YYDEBUG} to 1.
11053 @item the directive @samp{%debug} (deprecated)
11054 @findex %debug
11055 Add the @code{%debug} directive (@pxref{Decl Summary}).  This Bison
11056 extension is maintained for backward compatibility; use @code{%define
11057 parse.trace} instead.
11059 @item the macro @code{YYDEBUG} (C/C++ only)
11060 @findex YYDEBUG
11061 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
11062 parser.  This is compliant with POSIX Yacc.  You could use
11063 @option{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
11064 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue}).
11066 If the @code{%define} variable @code{api.prefix} is used (@pxref{Multiple
11067 Parsers}), for instance @samp{%define
11068 api.prefix @{c@}}, then if @code{CDEBUG} is defined, its value controls the
11069 tracing feature (enabled if and only if nonzero); otherwise tracing is
11070 enabled if and only if @code{YYDEBUG} is nonzero.
11072 In C++, where POSIX compliance makes no sense, avoid this option, and prefer
11073 @samp{%define parse.trace}.  If you @code{#define} the @code{YYDEBUG} macro
11074 at the wrong place (e.g., in @samp{%code top} instead of @samp{%code
11075 require}), the parser class will have two different definitions, thus
11076 leading to ODR violations and happy debugging times.
11077 @end table
11079 We suggest that you always enable the trace option so that debugging is
11080 always possible.
11082 @findex YYFPRINTF
11083 In C the trace facility outputs messages with macro calls of the form
11084 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where @var{format} and
11085 @var{args} are the usual @code{printf} format and variadic arguments.  If
11086 you define @code{YYDEBUG} to a nonzero value but do not define
11087 @code{YYFPRINTF}, @code{<stdio.h>} is automatically included and
11088 @code{YYFPRINTF} is defined to @code{fprintf}.
11090 Once you have compiled the program with trace facilities, the way to request
11091 a trace is to store a nonzero value in the variable @code{yydebug}.  You can
11092 do this by making the C code do it (in @code{main}, perhaps), or you can
11093 alter the value with a C debugger.
11095 Each step taken by the parser when @code{yydebug} is nonzero produces a line
11096 or two of trace information, written on @code{stderr}.  The trace messages
11097 tell you these things:
11099 @itemize @bullet
11100 @item
11101 Each time the parser calls @code{yylex}, what kind of token was read.
11103 @item
11104 Each time a token is shifted, the depth and complete contents of the state
11105 stack (@pxref{Parser States}).
11107 @item
11108 Each time a rule is reduced, which rule it is, and the complete contents of
11109 the state stack afterward.
11110 @end itemize
11112 To make sense of this information, it helps to refer to the automaton
11113 description file (@pxref{Understanding}).  This
11114 file shows the meaning of each state in terms of positions in various rules,
11115 and also what each state will do with each possible input token.  As you
11116 read the successive trace messages, you can see that the parser is
11117 functioning according to its specification in the listing file.  Eventually
11118 you will arrive at the place where something undesirable happens, and you
11119 will see which parts of the grammar are to blame.
11121 The parser implementation file is a C/C++/D/Java program and you can use
11122 debuggers on it, but it's not easy to interpret what it is doing.  The
11123 parser function is a finite-state machine interpreter, and aside from the
11124 actions it executes the same code over and over.  Only the values of
11125 variables show where in the grammar it is working.
11127 @node Mfcalc Traces
11128 @subsection Enabling Debug Traces for @code{mfcalc}
11130 The debugging information normally gives the token kind of each token read,
11131 but not its semantic value.  The @code{%printer} directive allows specify
11132 how semantic values are reported, see @ref{Printer Decl}.
11134 As a demonstration of @code{%printer}, consider the multi-function
11135 calculator, @code{mfcalc} (@pxref{Multi-function Calc}).  To enable run-time
11136 traces, and semantic value reports, insert the following directives in its
11137 prologue:
11139 @comment file: c/mfcalc/mfcalc.y: 2
11140 @example
11141 /* Generate the parser description file. */
11142 %verbose
11143 /* Enable run-time traces (yydebug). */
11144 %define parse.trace
11146 /* Formatting semantic values. */
11147 %printer @{ fprintf (yyo, "%s", $$->name); @} VAR;
11148 %printer @{ fprintf (yyo, "%s()", $$->name); @} FUN;
11149 %printer @{ fprintf (yyo, "%g", $$); @} <double>;
11150 @end example
11152 The @code{%define} directive instructs Bison to generate run-time trace
11153 support.  Then, activation of these traces is controlled at run-time by the
11154 @code{yydebug} variable, which is disabled by default.  Because these traces
11155 will refer to the ``states'' of the parser, it is helpful to ask for the
11156 creation of a description of that parser; this is the purpose of (admittedly
11157 ill-named) @code{%verbose} directive.
11159 The set of @code{%printer} directives demonstrates how to format the
11160 semantic value in the traces.  Note that the specification can be done
11161 either on the symbol type (e.g., @code{VAR} or @code{FUN}), or on the type
11162 tag: since @code{<double>} is the type for both @code{NUM} and @code{exp},
11163 this printer will be used for them.
11165 Here is a sample of the information provided by run-time traces.  The traces
11166 are sent onto standard error.
11168 @example
11169 $ @kbd{echo 'sin(1-1)' | ./mfcalc -p}
11170 Starting parse
11171 Entering state 0
11172 Reducing stack by rule 1 (line 34):
11173 -> $$ = nterm input ()
11174 Stack now 0
11175 Entering state 1
11176 @end example
11178 @noindent
11179 This first batch shows a specific feature of this grammar: the first rule
11180 (which is in line 34 of @file{mfcalc.y} can be reduced without even having
11181 to look for the first token.  The resulting left-hand symbol (@code{$$}) is
11182 a valueless (@samp{()}) @code{input} nonterminal (@code{nterm}).
11184 Then the parser calls the scanner.
11185 @example
11186 Reading a token
11187 Next token is token FUN (sin())
11188 Shifting token FUN (sin())
11189 Entering state 6
11190 @end example
11192 @noindent
11193 That token (@code{token}) is a function (@code{FUN}) whose value is
11194 @samp{sin} as formatted per our @code{%printer} specification: @samp{sin()}.
11195 The parser stores (@code{Shifting}) that token, and others, until it can do
11196 something about it.
11198 @example
11199 Reading a token
11200 Next token is token '(' ()
11201 Shifting token '(' ()
11202 Entering state 14
11203 Reading a token
11204 Next token is token NUM (1.000000)
11205 Shifting token NUM (1.000000)
11206 Entering state 4
11207 Reducing stack by rule 6 (line 44):
11208    $1 = token NUM (1.000000)
11209 -> $$ = nterm exp (1.000000)
11210 Stack now 0 1 6 14
11211 Entering state 24
11212 @end example
11214 @noindent
11215 The previous reduction demonstrates the @code{%printer} directive for
11216 @code{<double>}: both the token @code{NUM} and the resulting nonterminal
11217 @code{exp} have @samp{1} as value.
11219 @example
11220 Reading a token
11221 Next token is token '-' ()
11222 Shifting token '-' ()
11223 Entering state 17
11224 Reading a token
11225 Next token is token NUM (1.000000)
11226 Shifting token NUM (1.000000)
11227 Entering state 4
11228 Reducing stack by rule 6 (line 44):
11229    $1 = token NUM (1.000000)
11230 -> $$ = nterm exp (1.000000)
11231 Stack now 0 1 6 14 24 17
11232 Entering state 26
11233 Reading a token
11234 Next token is token ')' ()
11235 Reducing stack by rule 11 (line 49):
11236    $1 = nterm exp (1.000000)
11237    $2 = token '-' ()
11238    $3 = nterm exp (1.000000)
11239 -> $$ = nterm exp (0.000000)
11240 Stack now 0 1 6 14
11241 Entering state 24
11242 @end example
11244 @noindent
11245 The rule for the subtraction was just reduced.  The parser is about to
11246 discover the end of the call to @code{sin}.
11248 @example
11249 Next token is token ')' ()
11250 Shifting token ')' ()
11251 Entering state 31
11252 Reducing stack by rule 9 (line 47):
11253    $1 = token FUN (sin())
11254    $2 = token '(' ()
11255    $3 = nterm exp (0.000000)
11256    $4 = token ')' ()
11257 -> $$ = nterm exp (0.000000)
11258 Stack now 0 1
11259 Entering state 11
11260 @end example
11262 @noindent
11263 Finally, the end-of-line allow the parser to complete the computation, and
11264 display its result.
11266 @example
11267 Reading a token
11268 Next token is token '\n' ()
11269 Shifting token '\n' ()
11270 Entering state 22
11271 Reducing stack by rule 4 (line 40):
11272    $1 = nterm exp (0.000000)
11273    $2 = token '\n' ()
11274 @result{} 0
11275 -> $$ = nterm line ()
11276 Stack now 0 1
11277 Entering state 10
11278 Reducing stack by rule 2 (line 35):
11279    $1 = nterm input ()
11280    $2 = nterm line ()
11281 -> $$ = nterm input ()
11282 Stack now 0
11283 Entering state 1
11284 @end example
11286 The parser has returned into state 1, in which it is waiting for the next
11287 expression to evaluate, or for the end-of-file token, which causes the
11288 completion of the parsing.
11290 @example
11291 Reading a token
11292 Now at end of input.
11293 Shifting token $end ()
11294 Entering state 2
11295 Stack now 0 1 2
11296 Cleanup: popping token $end ()
11297 Cleanup: popping nterm input ()
11298 @end example
11301 @c ================================================= Invoking Bison
11303 @node Invocation
11304 @chapter Invoking Bison
11305 @cindex invoking Bison
11306 @cindex Bison invocation
11307 @cindex options for invoking Bison
11309 The usual way to invoke Bison is as follows:
11311 @example
11312 $ @kbd{bison @var{file}}
11313 @end example
11315 Here @var{file} is the grammar file name, which usually ends in @samp{.y}.
11316 The parser implementation file's name is made by replacing the @samp{.y}
11317 with @samp{.tab.c} and removing any leading directory.  Thus, the
11318 @samp{bison foo.y} file name yields @file{foo.tab.c}, and the @samp{bison
11319 hack/foo.y} file name yields @file{foo.tab.c}.  It's also possible, in case
11320 you are writing C++ code instead of C in your grammar file, to name it
11321 @file{foo.ypp} or @file{foo.y++}.  Then, the output files will take an
11322 extension like the given one as input (respectively @file{foo.tab.cpp} and
11323 @file{foo.tab.c++}).  This feature takes effect with all options that
11324 manipulate file names like @option{-o} or @option{-d}.
11326 For example:
11328 @example
11329 $ @kbd{bison -d @var{file.yxx}}
11330 @end example
11331 @noindent
11332 will produce @file{file.tab.cxx} and @file{file.tab.hxx}, and
11334 @example
11335 $ @kbd{bison -d -o @var{output.c++} @var{file.y}}
11336 @end example
11337 @noindent
11338 will produce @file{output.c++} and @file{output.h++}.
11340 For compatibility with POSIX, the standard Bison distribution also contains
11341 a shell script called @command{yacc} that invokes Bison with the @option{-y}
11342 option.
11344 @sp 1
11346 The exit status of @command{bison} is:
11347 @table @asis
11348 @item 0 (success)
11349 when there were no errors.  Warnings, which are diagnostics about dubious
11350 constructs, do not change the exit status, unless they are turned into
11351 errors (@pxref{Werror,,@option{-Werror}}).
11353 @item 1 (failure)
11354 when there were errors.  No file was generated (except the reports generated
11355 by @option{--verbose}, etc.).  In particular, the output files that possibly
11356 existed were not changed.
11358 @item 63 (mismatch)
11359 when @command{bison} does not meet the version requirements of the grammar
11360 file. @xref{Require Decl}.  No file was generated or changed.
11361 @end table
11364 @menu
11365 * Bison Options::     All the options described in detail,
11366                         in alphabetical order by short options.
11367 * Option Cross Key::  Alphabetical list of long options.
11368 * Yacc Library::      Yacc-compatible @code{yylex} and @code{main}.
11369 @end menu
11371 @node Bison Options
11372 @section Bison Options
11374 Bison supports both traditional single-letter options and mnemonic long
11375 option names.  Long option names are indicated with @option{--} instead of
11376 @option{-}.  Abbreviations for option names are allowed as long as they
11377 are unique.  When a long option takes an argument, like
11378 @option{--file-prefix}, connect the option name and the argument with
11379 @samp{=}.
11381 Here is a list of options that can be used with Bison.  It is followed by a
11382 cross key alphabetized by long option.
11384 @menu
11385 * Operation Modes::    Options controlling the global behavior of @command{bison}
11386 * Diagnostics::        Options controlling the diagnostics
11387 * Tuning the Parser::  Options changing the generated parsers
11388 * Output Files::       Options controlling the output
11389 @end menu
11391 @node Operation Modes
11392 @subsection Operation Modes
11394 Options controlling the global behavior of @command{bison}.
11396 @c Please, keep this ordered as in 'bison --help'.
11397 @table @option
11398 @item -h
11399 @itemx --help
11400 Print a summary of the command-line options to Bison and exit.
11402 @item -V
11403 @itemx --version
11404 Print the version number of Bison and exit.
11406 @item --print-localedir
11407 Print the name of the directory containing locale-dependent data.
11409 @item --print-datadir
11410 Print the name of the directory containing skeletons, CSS and XSLT.
11412 @item -u
11413 @item --update
11414 Update the grammar file (remove duplicates, update deprecated directives,
11415 etc.) and exit (i.e., do not generate any of the output files).  Leaves a
11416 backup of the original file with a @code{~} appended.  For instance:
11418 @example
11419 @group
11420 $ @kbd{cat foo.y}
11421 %error-verbose
11422 %define parse.error verbose
11424 exp:;
11425 @end group
11426 @group
11427 $ @kbd{bison -u foo.y}
11428 foo.y:1.1-14: @dwarning{warning}: deprecated directive, use '%define parse.error verbose' [@dwarning{-Wdeprecated}]
11429     1 | @dwarning{%error-verbose}
11430       | @dwarning{^~~~~~~~~~~~~~}
11431 foo.y:2.1-27: @dwarning{warning}: %define variable 'parse.error' redefined [@dwarning{-Wother}]
11432     2 | @dwarning{%define parse.error verbose}
11433       | @dwarning{^~~~~~~~~~~~~~~~~~~~~~~~~~~}
11434 foo.y:1.1-14:     previous definition
11435     1 | @dnotice{%error-verbose}
11436       | @dnotice{^~~~~~~~~~~~~~}
11437 bison: file 'foo.y' was updated (backup: 'foo.y~')
11438 @end group
11439 @group
11440 $ @kbd{cat foo.y}
11441 %define parse.error verbose
11443 exp:;
11444 @end group
11445 @end example
11447 See the documentation of @option{--feature=fixit} below for more details.
11449 @item -f [@var{feature}]
11450 @itemx --feature[=@var{feature}]
11451 Activate miscellaneous @var{feature}s. @var{Feature} can be one of:
11452 @table @code
11453 @item caret
11454 @itemx diagnostics-show-caret
11455 Show caret errors, in a manner similar to GCC's
11456 @option{-fdiagnostics-show-caret}, or Clang's
11457 @option{-fcaret-diagnostics}. The location provided with the message is used
11458 to quote the corresponding line of the source file, underlining the
11459 important part of it with carets (@samp{^}). Here is an example, using the
11460 following file @file{in.y}:
11462 @example
11463 %nterm <ival> exp
11465 exp: exp '+' exp @{ $exp = $1 + $2; @};
11466 @end example
11468 When invoked with @option{-fcaret} (or nothing), Bison will report:
11470 @example
11471 @group
11472 in.y:3.20-23: @derror{error}: ambiguous reference: '$exp'
11473     3 | exp: exp '+' exp @{ @derror{$exp} = $1 + $2; @};
11474       |                    @derror{^~~~}
11475 @end group
11476 @group
11477 in.y:3.1-3:       refers to: $exp at $$
11478     3 | @dnotice{exp}: exp '+' exp @{ $exp = $1 + $2; @};
11479       | @dnotice{^~~}
11480 @end group
11481 @group
11482 in.y:3.6-8:       refers to: $exp at $1
11483     3 | exp: @dnotice{exp} '+' exp @{ $exp = $1 + $2; @};
11484       |      @dnotice{^~~}
11485 @end group
11486 @group
11487 in.y:3.14-16:     refers to: $exp at $3
11488     3 | exp: exp '+' @dnotice{exp} @{ $exp = $1 + $2; @};
11489       |              @dnotice{^~~}
11490 @end group
11491 @group
11492 in.y:3.32-33: @derror{error}: $2 of 'exp' has no declared type
11493     3 | exp: exp '+' exp @{ $exp = $1 + @derror{$2}; @};
11494       |                                @derror{^~}
11495 @end group
11496 @end example
11498 Whereas, when invoked with @option{-fno-caret}, Bison will only report:
11500 @example
11501 @group
11502 in.y:3.20-23: @derror{error}: ambiguous reference: '$exp'
11503 in.y:3.1-3:       refers to: $exp at $$
11504 in.y:3.6-8:       refers to: $exp at $1
11505 in.y:3.14-16:     refers to: $exp at $3
11506 in.y:3.32-33: @derror{error}: $2 of 'exp' has no declared type
11507 @end group
11508 @end example
11510 This option is activated by default.
11512 @item fixit
11513 @itemx diagnostics-parseable-fixits
11514 Show machine-readable fixes, in a manner similar to GCC's and Clang's
11515 @option{-fdiagnostics-parseable-fixits}.
11517 Fix-its are generated for duplicate directives:
11519 @example
11520 @group
11521 $ @kbd{cat foo.y}
11522 %define api.prefix @{foo@}
11523 %define api.prefix @{bar@}
11525 exp:;
11526 @end group
11528 @group
11529 $ @kbd{bison -ffixit foo.y}
11530 foo.y:2.1-24: @derror{error}: %define variable 'api.prefix' redefined
11531     2 | @derror{%define api.prefix @{bar@}}
11532       | @derror{^~~~~~~~~~~~~~~~~~~~~~~~}
11533 foo.y:1.1-24:     previous definition
11534     1 | @dnotice{%define api.prefix @{foo@}}
11535       | @dnotice{^~~~~~~~~~~~~~~~~~~~~~~~}
11536 fix-it:"foo.y":@{2:1-2:25@}:""
11537 foo.y: @dwarning{warning}: fix-its can be applied.  Rerun with option '--update'. [@dwarning{-Wother}]
11538 @end group
11539 @end example
11541 They are also generated to update deprecated directives, unless
11542 @option{-Wno-deprecated} was given:
11544 @example
11545 @group
11546 $ @kbd{cat /tmp/foo.yy}
11547 %error-verbose
11548 %name-prefix "foo"
11550 exp:;
11551 @end group
11552 @group
11553 $ @kbd{bison foo.y}
11554 foo.y:1.1-14: @dwarning{warning}: deprecated directive, use '%define parse.error verbose' [@dwarning{-Wdeprecated}]
11555     1 | @dwarning{%error-verbose}
11556       | @dwarning{^~~~~~~~~~~~~~}
11557 foo.y:2.1-18: @dwarning{warning}: deprecated directive, use '%define api.prefix @{foo@}' [@dwarning{-Wdeprecated}]
11558     2 | @dwarning{%name-prefix "foo"}
11559       | @dwarning{^~~~~~~~~~~~~~~~~~}
11560 foo.y: @dwarning{warning}: fix-its can be applied.  Rerun with option '--update'. [@dwarning{-Wother}]
11561 @end group
11562 @end example
11564 The fix-its are applied by @command{bison} itself when given the option
11565 @option{-u}/@option{--update}.  See its documentation above.
11567 @item syntax-only
11568 Do not generate the output files.  The name of this feature is somewhat
11569 misleading as more than just checking the syntax is done: every stage is run
11570 (including checking for conflicts for instance), except the generation of
11571 the output files.
11573 @end table
11574 @end table
11576 @node Diagnostics
11577 @subsection Diagnostics
11579 Options controlling the diagnostics.
11581 @c Please, keep this ordered as in 'bison --help'.
11582 @table @code
11583 @item -W [@var{category}]
11584 @itemx --warnings[=@var{category}]
11585 Output warnings falling in @var{category}.  @var{category} can be one
11587 @table @code
11588 @item @anchor{Wconflicts-sr}conflicts-sr
11589 @itemx @anchor{Wconflicts-rr}conflicts-rr
11590 S/R and R/R conflicts.  These warnings are enabled by default.  However, if
11591 the @code{%expect} or @code{%expect-rr} directive is specified, an
11592 unexpected number of conflicts is an error, and an expected number of
11593 conflicts is not reported, so @option{-W} and @option{--warning} then have
11594 no effect on the conflict report.
11596 @item @anchor{Wcounterexamples}counterexamples
11597 @itemx cex
11598 Provide counterexamples for conflicts.  @xref{Counterexamples}.
11599 Counterexamples take time to compute.  The option @option{-Wcex} should be
11600 used by the developer when working on the grammar; it hardly makes sense to
11601 use it in a CI.
11603 @item @anchor{Wdangling-alias}dangling-alias
11604 Report string literals that are not bound to a token symbol.
11606 String literals, which allow for better error messages, are (too) liberally
11607 accepted by Bison, which might result in silent errors.  For instance
11609 @example
11610 %type <exVal> cond "condition"
11611 @end example
11613 @noindent
11614 does not define ``condition'' as a string alias to @code{cond}---nonterminal
11615 symbols do not have string aliases.  It is rather equivalent to
11617 @example
11618 %nterm <exVal> cond
11619 %token <exVal> "condition"
11620 @end example
11622 @noindent
11623 i.e., it gives the @samp{"condition"} token the type @code{exVal}.
11625 Also, because string aliases do not need to be defined, typos such as
11626 @samp{"baz"} instead of @samp{"bar"} will be not reported.
11628 The option @option{-Wdangling-alias} catches these situations.  On
11630 @example
11631 %token BAR "bar"
11632 %type <ival> foo "foo"
11634 foo: "baz" @{@}
11635 @end example
11637 @noindent
11638 @samp{bison -Wdangling-alias} reports
11640 @example
11641 @dwarning{warning}: string literal not attached to a symbol
11642       | %type <ival> foo @dwarning{"foo"}
11643       |                  @dwarning{^~~~~}
11644 @dwarning{warning}: string literal not attached to a symbol
11645       | foo: @dwarning{"baz"} @{@}
11646       |      @dwarning{^~~~~}
11647 @end example
11649 @item @anchor{Wdeprecated}deprecated
11650 Deprecated constructs whose support will be removed in future versions of
11651 Bison.
11653 @item @anchor{Wempty-rule}empty-rule
11654 Empty rules without @code{%empty}.  @xref{Empty Rules}.  Disabled by
11655 default, but enabled by uses of @code{%empty}, unless
11656 @option{-Wno-empty-rule} was specified.
11658 @item @anchor{Wmidrule-values}midrule-values
11659 Warn about midrule values that are set but not used within any of the actions
11660 of the parent rule.
11661 For example, warn about unused @code{$2} in:
11663 @example
11664 exp: '1' @{ $$ = 1; @} '+' exp @{ $$ = $1 + $4; @};
11665 @end example
11667 Also warn about midrule values that are used but not set.
11668 For example, warn about unset @code{$$} in the midrule action in:
11670 @example
11671 exp: '1' @{ $1 = 1; @} '+' exp @{ $$ = $2 + $4; @};
11672 @end example
11674 These warnings are not enabled by default since they sometimes prove to
11675 be false alarms in existing grammars employing the Yacc constructs
11676 @code{$0} or @code{$-@var{n}} (where @var{n} is some positive integer).
11678 @item @anchor{Wprecedence}precedence
11679 Useless precedence and associativity directives.  Disabled by default.
11681 Consider for instance the following grammar:
11683 @example
11684 @group
11685 %nonassoc "="
11686 %left "+"
11687 %left "*"
11688 %precedence "("
11689 @end group
11691 @group
11692 stmt:
11693   exp
11694 | "var" "=" exp
11696 @end group
11698 @group
11699 exp:
11700   exp "+" exp
11701 | exp "*" "number"
11702 | "(" exp ")"
11703 | "number"
11705 @end group
11706 @end example
11708 Bison reports:
11710 @c cannot leave the location and the [-Wprecedence] for lack of
11711 @c width in PDF.
11712 @example
11713 @group
11714 @dwarning{warning}: useless precedence and associativity for "="
11715       | %nonassoc @dwarning{"="}
11716       |           @dwarning{^~~}
11717 @end group
11718 @group
11719 @dwarning{warning}: useless associativity for "*", use %precedence
11720       | %left @dwarning{"*"}
11721       |       @dwarning{^~~}
11722 @end group
11723 @group
11724 @dwarning{warning}: useless precedence for "("
11725       | %precedence @dwarning{"("}
11726       |             @dwarning{^~~}
11727 @end group
11728 @end example
11730 One would get the exact same parser with the following directives instead:
11732 @example
11733 @group
11734 %left "+"
11735 %precedence "*"
11736 @end group
11737 @end example
11739 @item @anchor{Wyacc}yacc
11740 Incompatibilities with POSIX Yacc.
11742 @item @anchor{Wother}other
11743 All warnings not categorized above.  These warnings are enabled by default.
11745 This category is provided merely for the sake of completeness.  Future
11746 releases of Bison may move warnings from this category to new, more specific
11747 categories.
11749 @item @anchor{Wall}all
11750 All the warnings except @code{counterexamples}, @code{dangling-alias} and
11751 @code{yacc}.
11753 @item @anchor{Wnone}none
11754 Turn off all the warnings.
11756 @item error
11757 See @option{-Werror}, below.
11758 @end table
11760 A category can be turned off by prefixing its name with @samp{no-}.  For
11761 instance, @option{-Wno-yacc} will hide the warnings about
11762 POSIX Yacc incompatibilities.
11764 @item @anchor{Werror}-Werror
11765 Turn enabled warnings for every @var{category} into errors, unless they are
11766 explicitly disabled by @option{-Wno-error=@var{category}}.
11768 @item -Werror=@var{category}
11769 Enable warnings falling in @var{category}, and treat them as errors.
11771 @var{category} is the same as for @option{--warnings}, with the exception that
11772 it may not be prefixed with @samp{no-} (see above).
11774 Note that the precedence of the @samp{=} and @samp{,} operators is such that
11775 the following commands are @emph{not} equivalent, as the first will not treat
11776 S/R conflicts as errors.
11778 @example
11779 $ @kbd{bison -Werror=yacc,conflicts-sr input.y}
11780 $ @kbd{bison -Werror=yacc,error=conflicts-sr input.y}
11781 @end example
11783 @item -Wno-error
11784 Do not turn enabled warnings for every @var{category} into errors, unless
11785 they are explicitly enabled by @option{-Werror=@var{category}}.
11787 @item -Wno-error=@var{category}
11788 Deactivate the error treatment for this @var{category}. However, the warning
11789 itself won't be disabled, or enabled, by this option.
11791 @item --color
11792 Equivalent to @option{--color=always}.
11794 @item --color=@var{when}
11795 Control whether diagnostics are colorized, depending on @var{when}:
11796 @table @code
11797 @item always
11798 @itemx yes
11799 Enable colorized diagnostics.
11801 @item never
11802 @itemx no
11803 Disable colorized diagnostics.
11805 @item auto @r{(default)}
11806 @itemx tty
11807 Diagnostics will be colorized if the output device is a tty, i.e. when the
11808 output goes directly to a text screen or terminal emulator window.
11809 @end table
11811 @item --style=@var{file}
11812 Specifies the CSS style @var{file} to use when colorizing. It has an effect
11813 only when the @option{--color} option is effective.  The
11814 @file{bison-default.css} file provide a good example from which to define
11815 your own style file.  See the documentation of libtextstyle for more
11816 details.
11817 @end table
11819 @node Tuning the Parser
11820 @subsection Tuning the Parser
11822 Options changing the generated parsers.
11824 @c Please, keep this ordered as in 'bison --help'.
11825 @table @option
11826 @item -t
11827 @itemx --debug
11828 In the parser implementation file, define the macro @code{YYDEBUG} to 1 if
11829 it is not already defined, so that the debugging facilities are compiled.
11830 @xref{Tracing}.
11832 @item -D @var{name}[=@var{value}]
11833 @itemx --define=@var{name}[=@var{value}]
11834 @itemx -F @var{name}[=@var{value}]
11835 @itemx --force-define=@var{name}[=@var{value}]
11836 Each of these is equivalent to @samp{%define @var{name} @var{value}}
11837 (@pxref{%define Summary}).  Note that the delimiters are part of
11838 @var{value}: @option{-Dapi.value.type=union},
11839 @option{-Dapi.value.type=@{union@}} and @option{-Dapi.value.type="union"}
11840 correspond to @samp{%define api.value.type union}, @samp{%define
11841 api.value.type @{union@}} and @samp{%define api.value.type "union"}.
11843 Bison processes multiple definitions for the same @var{name} as follows:
11845 @itemize
11846 @item
11847 Bison quietly ignores all command-line definitions for @var{name} except
11848 the last.
11849 @item
11850 If that command-line definition is specified by a @option{-D} or
11851 @option{--define}, Bison reports an error for any @code{%define} definition
11852 for @var{name}.
11853 @item
11854 If that command-line definition is specified by a @option{-F} or
11855 @option{--force-define} instead, Bison quietly ignores all @code{%define}
11856 definitions for @var{name}.
11857 @item
11858 Otherwise, Bison reports an error if there are multiple @code{%define}
11859 definitions for @var{name}.
11860 @end itemize
11862 You should avoid using @option{-F} and @option{--force-define} in your
11863 make files unless you are confident that it is safe to quietly ignore
11864 any conflicting @code{%define} that may be added to the grammar file.
11866 @item -L @var{language}
11867 @itemx --language=@var{language}
11868 Specify the programming language for the generated parser, as if
11869 @code{%language} was specified (@pxref{Decl Summary}).  Currently supported
11870 languages include C, C++, D and Java.  @var{language} is case-insensitive.
11872 @item --locations
11873 Pretend that @code{%locations} was specified.  @xref{Decl Summary}.
11875 @item -p @var{prefix}
11876 @itemx --name-prefix=@var{prefix}
11877 Pretend that @code{%name-prefix "@var{prefix}"} was specified (@pxref{Decl
11878 Summary}).  The option @option{-p} is specified by POSIX.  When POSIX
11879 compatibility is not a requirement, @option{-Dapi.prefix=@var{prefix}} is a
11880 better option (@pxref{Multiple Parsers}).
11882 @item -l
11883 @itemx --no-lines
11884 Don't put any @code{#line} preprocessor commands in the parser
11885 implementation file.  Ordinarily Bison puts them in the parser
11886 implementation file so that the C compiler and debuggers will
11887 associate errors with your source file, the grammar file.  This option
11888 causes them to associate errors with the parser implementation file,
11889 treating it as an independent source file in its own right.
11891 @item -S @var{file}
11892 @itemx --skeleton=@var{file}
11893 Specify the skeleton to use, similar to @code{%skeleton}
11894 (@pxref{Decl Summary}).
11896 @c You probably don't need this option unless you are developing Bison.
11897 @c You should use @option{--language} if you want to specify the skeleton for a
11898 @c different language, because it is clearer and because it will always
11899 @c choose the correct skeleton for non-deterministic or push parsers.
11901 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
11902 file in the Bison installation directory.
11903 If it does, @var{file} is an absolute file name or a file name relative to the
11904 current working directory.
11905 This is similar to how most shells resolve commands.
11907 @item -k
11908 @itemx --token-table
11909 Pretend that @code{%token-table} was specified.  @xref{Decl Summary}.
11911 @item -y
11912 @itemx @anchor{option-yacc} --yacc
11913 Act more like the traditional @command{yacc} command:
11914 @itemize
11915 @item
11916 Generate different diagnostics (it implies @option{-Wyacc}).
11917 @item
11918 Generate @code{#define} statements in addition to an @code{enum} to
11919 associate token codes with token kind names.
11920 @item
11921 If the @code{POSIXLY_CORRECT} environment variable is defined, generate
11922 prototypes for @code{yyerror} and @code{yylex}@footnote{See
11923 @url{https://austingroupbugs.net/view.php?id=1388#c5220}.} (since Bison
11924 3.8):
11925 @example
11926 int yylex (void);
11927 void yyerror (const char *);
11928 @end example
11929 As a Bison extension, additional arguments required by @code{%pure-parser},
11930 @code{%locations}, @code{%lex-param} and @code{%parse-param} are taken into
11931 account.  You may disable @code{yyerror}'s prototype with @samp{#define
11932 yyerror yyerror} (as specified by POSIX), or with @samp{#define
11933 YYERROR_IS_DECLARED} (a Bison extension).  Likewise for @code{yylex}.
11934 @item
11935 Imitate Yacc's output file name conventions, so that the parser
11936 implementation file is called @file{y.tab.c}, and the other outputs are
11937 called @file{y.output} and @file{y.tab.h}.  Do not use @option{--yacc} just
11938 to change the output file names since it also triggers all the
11939 aforementioned behavior changes; rather use @samp{-o y.tab.c}.
11940 @end itemize
11942 The @option{-y}/@option{--yacc} option is intended for use with traditional
11943 Yacc grammars.  This option only makes sense for the default C skeleton,
11944 @file{yacc.c}.  If your grammar uses Bison extensions Bison cannot be
11945 Yacc-compatible, even if this option is specified.
11947 Thus, the following shell script can substitute for Yacc, and the Bison
11948 distribution contains such a @command{yacc} script for compatibility with
11949 POSIX:
11951 @example
11952 #! /bin/sh
11953 bison -y "$@@"
11954 @end example
11955 @end table
11957 @node Output Files
11958 @subsection Output Files
11960 Options controlling the output.
11962 @c Please, keep this ordered as in 'bison --help'.
11963 @table @option
11964 @item -H [@var{file}]
11965 @itemx --header=[@var{file}]
11966 Pretend that @code{%header} was specified, i.e., write an extra output file
11967 containing definitions for the token kind names defined in the grammar, as
11968 well as a few other declarations.  @xref{Decl Summary}.
11970 @item --defines[=@var{file}]
11971 Historical name for option @option{--header} before Bison 3.8.
11973 @item -d
11974 This is the same as @option{--header} except @option{-d} does not accept a
11975 @var{file} argument since POSIX Yacc requires that @option{-d} can be
11976 bundled with other short options.
11978 @item -b @var{file-prefix}
11979 @itemx --file-prefix=@var{prefix}
11980 Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
11981 for all Bison output file names.  @xref{Decl Summary}.
11983 @item -r @var{things}
11984 @itemx --report=@var{things}
11985 Write an extra output file containing verbose description of the comma
11986 separated list of @var{things} among:
11988 @table @code
11989 @item state
11990 Description of the grammar, conflicts (resolved and unresolved), and
11991 parser's automaton.
11993 @item itemset
11994 Implies @code{state} and augments the description of the automaton with
11995 the full set of items for each state, instead of its core only.
11997 @item lookahead
11998 Implies @code{state} and augments the description of the automaton with
11999 each rule's lookahead set.
12001 @item solved
12002 Implies @code{state}.  Explain how conflicts were solved thanks to
12003 precedence and associativity directives.
12005 @item counterexamples
12006 @itemx cex
12007 Look for counterexamples for the conflicts.  @xref{Counterexamples}.
12008 Counterexamples take time to compute.  The option @option{-rcex} should be
12009 used by the developer when working on the grammar; it hardly makes sense to
12010 use it in a CI.
12012 @item all
12013 Enable all the items.
12015 @item none
12016 Do not generate the report.
12017 @end table
12019 @item --report-file=@var{file}
12020 Specify the @var{file} for the verbose description.
12022 @item -v
12023 @itemx --verbose
12024 Pretend that @code{%verbose} was specified, i.e., write an extra output
12025 file containing verbose descriptions of the grammar and
12026 parser.  @xref{Decl Summary}.
12028 @item -o @var{file}
12029 @itemx --output=@var{file}
12030 Specify the @var{file} for the parser implementation file.
12032 The names of the other output files are constructed from @var{file} as
12033 described under the @option{-v} and @option{-d} options.
12035 @item -g [@var{file}]
12036 @itemx --graph[=@var{file}]
12037 Output a graphical representation of the parser's automaton computed by
12038 Bison, in @uref{https://www.graphviz.org/, Graphviz}
12039 @uref{https://www.graphviz.org/doc/info/lang.html, DOT} format.
12040 @code{@var{file}} is optional.  If omitted and the grammar file is
12041 @file{foo.y}, the output file will be @file{foo.gv}.
12043 @item -x [@var{file}]
12044 @itemx --xml[=@var{file}]
12045 Output an XML report of the parser's automaton computed by Bison.
12046 @code{@var{file}} is optional.
12047 If omitted and the grammar file is @file{foo.y}, the output file will be
12048 @file{foo.xml}.
12050 @item -M @var{old}=@var{new}
12051 @itemx --file-prefix-map=@var{old}=@var{new}
12052 Replace prefix @var{old} with @var{new} when writing file paths in output
12053 files.
12054 @end table
12056 @node Option Cross Key
12057 @section Option Cross Key
12059 Here is a list of options, alphabetized by long option, to help you find
12060 the corresponding short option and directive.
12062 @multitable {@option{--force-define=@var{name}[=@var{value}]}} {@option{-F @var{name}[=@var{value}]}} {@code{%nondeterministic-parser}}
12063 @headitem Long Option @tab Short Option @tab Bison Directive
12064 @include cross-options.texi
12065 @end multitable
12067 @node Yacc Library
12068 @section Yacc Library
12070 The Yacc library contains default implementations of the @code{yyerror} and
12071 @code{main} functions.  These default implementations are normally not
12072 useful, but POSIX requires them.  To use the Yacc library, link your program
12073 with the @option{-ly} option.  Note that Bison's implementation of the Yacc
12074 library is distributed under the terms of the GNU General Public License
12075 (@pxref{Copying}).
12077 If you use the Yacc library's @code{yyerror} function, you should declare
12078 @code{yyerror} as follows:
12080 @example
12081 int yyerror (char const *);
12082 @end example
12084 @noindent
12085 The @code{int} value returned by this @code{yyerror} is ignored.
12087 The implementation of Yacc library's @code{main} function is:
12089 @example
12090 int main (void)
12092   setlocale (LC_ALL, "");
12093   return yyparse ();
12095 @end example
12097 @noindent
12098 so if you use it, the internationalization support is enabled (e.g., error
12099 messages are translated), and your @code{yyparse} function should have the
12100 following type signature:
12102 @example
12103 int yyparse (void);
12104 @end example
12106 @c ================================================= C++ Bison
12108 @node Other Languages
12109 @chapter Parsers Written In Other Languages
12111 In addition to C, Bison can generate parsers in C++, D and Java.  This chapter
12112 is devoted to these languages.  The reader is expected to understand how
12113 Bison works; read the introductory chapters first if you don't.
12115 @menu
12116 * C++ Parsers::                 The interface to generate C++ parser classes
12117 * D Parsers::                   The interface to generate D parser classes
12118 * Java Parsers::                The interface to generate Java parser classes
12119 @end menu
12121 @node C++ Parsers
12122 @section C++ Parsers
12124 The Bison parser in C++ is an object, an instance of the class
12125 @code{yy::parser}.
12127 @menu
12128 * A Simple C++ Example::        A short introduction to C++ parsers
12129 * C++ Bison Interface::         Asking for C++ parser generation
12130 * C++ Parser Interface::        Instantiating and running the parser
12131 * C++ Semantic Values::         %union vs. C++
12132 * C++ Location Values::         The position and location classes
12133 * C++ Parser Context::          You can supply a @code{report_syntax_error} function.
12134 * C++ Scanner Interface::       Exchanges between yylex and parse
12135 * A Complete C++ Example::      Demonstrating their use
12136 @end menu
12138 @node A Simple C++ Example
12139 @subsection A Simple C++ Example
12141 This tutorial about C++ parsers is based on a simple, self contained
12142 example.@footnote{The sources of this example are available as
12143 @file{examples/c++/simple.yy}.}  The following sections are the reference
12144 manual for Bison with C++, the last one showing a fully blown example
12145 (@pxref{A Complete C++ Example}).
12147 To look nicer, our example will be in C++14.  It is not required: Bison
12148 supports the original C++98 standard.
12150 A Bison file has three parts.  In the first part, the prologue, we start by
12151 making sure we run a version of Bison which is recent enough, and that we
12152 generate C++.
12154 @ignore
12155 @comment file: c++/simple.yy: 1
12156 @example
12157 /* Simple variant-based parser.   -*- C++ -*-
12159    Copyright (C) 2018-2021 Free Software Foundation, Inc.
12161    This file is part of Bison, the GNU Compiler Compiler.
12163    This program is free software: you can redistribute it and/or modify
12164    it under the terms of the GNU General Public License as published by
12165    the Free Software Foundation, either version 3 of the License, or
12166    (at your option) any later version.
12168    This program is distributed in the hope that it will be useful,
12169    but WITHOUT ANY WARRANTY; without even the implied warranty of
12170    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12171    GNU General Public License for more details.
12173    You should have received a copy of the GNU General Public License
12174    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
12175 @end example
12176 @end ignore
12178 @comment file: c++/simple.yy: 1
12179 @example
12180 %require "3.2"
12181 %language "c++"
12182 @end example
12184 Let's dive directly into the middle part: the grammar.  Our input is a
12185 simple list of strings, that we display once the parsing is done.
12187 @comment file: c++/simple.yy: 2
12188 @example
12190 @group
12191 result:
12192   list  @{ std::cout << $1 << '\n'; @}
12194 @end group
12196 %nterm <std::vector<std::string>> list;
12197 @group
12198 list:
12199   %empty     @{ /* Generates an empty string list */ @}
12200 | list item  @{ $$ = $1; $$.push_back ($2); @}
12202 @end group
12203 @end example
12205 We used a vector of strings as a semantic value!  To use genuine C++ objects
12206 as semantic values---not just PODs---we cannot rely on the union that Bison
12207 uses by default to store them, we need @emph{variants} (@pxref{C++
12208 Variants}):
12210 @comment file: c++/simple.yy: 1
12211 @example
12212 %define api.value.type variant
12213 @end example
12215 Obviously, the rule for @code{result} needs to print a vector of strings.
12216 In the prologue, we add:
12218 @comment file: c++/simple.yy: 1
12219 @example
12220 %code
12222   // Print a list of strings.
12223   auto
12224   operator<< (std::ostream& o, const std::vector<std::string>& ss)
12225     -> std::ostream&
12226   @{
12227     o << '@{';
12228     const char *sep = "";
12229 @group
12230     for (const auto& s: ss)
12231       @{
12232         o << sep << s;
12233         sep = ", ";
12234       @}
12235 @end group
12236     return o << '@}';
12237   @}
12239 @end example
12241 @noindent
12242 You may want to move it into the @code{yy} namespace to avoid leaking it in
12243 your default namespace.  We recommend that you keep the actions simple, and
12244 move details into auxiliary functions, as we did with @code{operator<<}.
12246 Our list of strings will be built from two types of items: numbers and
12247 strings:
12249 @comment file: c++/simple.yy: 2
12250 @example
12251 %nterm <std::string> item;
12252 %token <std::string> TEXT;
12253 %token <int> NUMBER;
12254 @group
12255 item:
12256   TEXT
12257 | NUMBER  @{ $$ = std::to_string ($1); @}
12259 @end group
12260 @end example
12262 In the case of @code{TEXT}, the implicit default action applies: @w{@code{$$
12263 = $1}.}
12265 @sp 1
12267 Our scanner deserves some attention.  The traditional interface of
12268 @code{yylex} is not type safe: since the token kind and the token value are
12269 not correlated, you may return a @code{NUMBER} with a string as semantic
12270 value.  To avoid this, we use @emph{token constructors} (@pxref{Complete
12271 Symbols}).  This directive:
12273 @comment file: c++/simple.yy: 1
12274 @example
12275 %define api.token.constructor
12276 @end example
12278 @noindent
12279 requests that Bison generates the functions @code{make_TEXT} and
12280 @code{make_NUMBER}, but also @code{make_YYEOF}, for the end of input.
12282 Everything is in place for our scanner:
12284 @comment file: c++/simple.yy: 1
12285 @example
12286 %code
12288   namespace yy
12289   @{
12290     // Return the next token.
12291     auto yylex () -> parser::symbol_type
12292     @{
12293       static int count = 0;
12294       switch (int stage = count++)
12295         @{
12296 @group
12297         case 0:
12298           return parser::make_TEXT ("I have three numbers for you.");
12299 @end group
12300 @group
12301         case 1: case 2: case 3:
12302           return parser::make_NUMBER (stage);
12303 @end group
12304 @group
12305         case 4:
12306           return parser::make_TEXT ("And that's all!");
12307 @end group
12308 @group
12309         default:
12310           return parser::make_YYEOF ();
12311 @end group
12312         @}
12313     @}
12314   @}
12316 @end example
12318 In the epilogue, the third part of a Bison grammar file, we leave simple
12319 details: the error reporting function, and the main function.
12321 @comment file: c++/simple.yy: 3
12322 @example
12324 namespace yy
12326   // Report an error to the user.
12327   auto parser::error (const std::string& msg) -> void
12328   @{
12329     std::cerr << msg << '\n';
12330   @}
12333 int main ()
12335   yy::parser parse;
12336   return parse ();
12338 @end example
12340 Compile, and run!
12342 @example
12343 $ @kbd{bison simple.yy -o simple.cc}
12344 $ @kbd{g++ -std=c++14 simple.cc -o simple}
12345 @group
12346 $ @kbd{./simple}
12347 @{I have three numbers for you., 1, 2, 3, And that's all!@}
12348 @end group
12349 @end example
12351 @node C++ Bison Interface
12352 @subsection C++ Bison Interface
12353 @c - %skeleton "lalr1.cc"
12354 @c - Always pure
12355 @c - initial action
12357 The C++ deterministic parser is selected using the skeleton directive,
12358 @samp{%skeleton "lalr1.cc"}.  @xref{Decl Summary}.
12360 When run, @command{bison} will create several entities in the @samp{yy}
12361 namespace.
12362 @findex %define api.namespace
12363 Use the @samp{%define api.namespace} directive to change the namespace name,
12364 see @ref{%define Summary}.  The various classes are generated
12365 in the following files:
12367 @table @file
12368 @item @var{file}.hh
12369 (Assuming the extension of the grammar file was @samp{.yy}.)  The
12370 declaration of the C++ parser class and auxiliary types.  By default, this
12371 file is not generated (@pxref{Decl Summary}).
12373 @item @var{file}.cc
12374 The implementation of the C++ parser class.  The basename and extension of
12375 these two files (@file{@var{file}.hh} and @file{@var{file}.cc}) follow the
12376 same rules as with regular C parsers (@pxref{Invocation}).
12378 @item location.hh
12379 Generated when both @code{%header} and @code{%locations} are enabled, this
12380 file contains the definition of the classes @code{position} and
12381 @code{location}, used for location tracking.  It is not generated if
12382 @samp{%define api.location.file none} is specified, or if user defined
12383 locations are used.  @xref{C++ Location Values}.
12385 @item position.hh
12386 @itemx stack.hh
12387 Useless legacy files.  To get rid of then, use @samp{%require "3.2"} or
12388 newer.
12389 @end table
12391 All these files are documented using Doxygen; run @command{doxygen} for a
12392 complete and accurate documentation.
12394 @node C++ Parser Interface
12395 @subsection C++ Parser Interface
12397 The output files @file{@var{file}.hh} and @file{@var{file}.cc} declare and
12398 define the parser class in the namespace @code{yy}.  The class name defaults
12399 to @code{parser}, but may be changed using @samp{%define api.parser.class
12400 @{@var{name}@}}.  The interface of this class is detailed below.  It can be
12401 extended using the @code{%parse-param} feature: its semantics is slightly
12402 changed since it describes an additional member of the parser class, and an
12403 additional argument for its constructor.
12406 @defcv {Type} {parser} {token}
12407 A structure that contains (only) the @code{token_kind_type} enumeration,
12408 which defines the tokens.  To refer to the token @code{FOO}, use
12409 @code{yy::parser::token::FOO}.  The scanner can use @samp{typedef
12410 yy::parser::token token;} to ``import'' the token enumeration (@pxref{Calc++
12411 Scanner}).
12412 @end defcv
12414 @defcv {Type} {parser} {token_kind_type}
12415 An enumeration of the token kinds.  Its enumerators are forged from the
12416 token names, with a possible token prefix
12417 (@pxref{api-token-prefix,,@code{api.token.prefix}}):
12419 @example
12420 /// Token kinds.
12421 struct token
12423   enum token_kind_type
12424   @{
12425     YYEMPTY = -2,              // No token.
12426     YYEOF = 0,                 // "end of file"
12427     YYerror = 256,             // error
12428     YYUNDEF = 257,             // "invalid token"
12429     PLUS = 258,                // "+"
12430     MINUS = 259,               // "-"
12431     [...]
12432     VAR = 271,                 // "variable"
12433     NEG = 272                  // NEG
12434   @};
12437 /// Token kind, as returned by yylex.
12438 typedef token::token_kind_type token_kind_type;
12439 @end example
12440 @end defcv
12442 @defcv {Type} {parser} {value_type}
12443 The types for semantic values. @xref{C++ Semantic Values}.
12444 @end defcv
12446 @defcv {Type} {parser} {location_type}
12447 The type of locations, if location tracking is enabled.  @xref{C++ Location
12448 Values}.
12449 @end defcv
12451 @defcv {Type} {parser} {syntax_error}
12452 This class derives from @code{std::runtime_error}.  Throw instances of it
12453 from the scanner or from the actions to raise parse errors.  This is
12454 equivalent with first invoking @code{error} to report the location and
12455 message of the syntax error, and then to invoke @code{YYERROR} to enter the
12456 error-recovery mode.  But contrary to @code{YYERROR} which can only be
12457 invoked from user actions (i.e., written in the action itself), the
12458 exception can be thrown from functions invoked from the user action.
12459 @end defcv
12461 @deftypeop {Constructor} {parser} {} parser ()
12462 @deftypeopx {Constructor} {parser} {} parser (@var{type1} @var{arg1}, ...)
12463 Build a new parser object.  There are no arguments, unless
12464 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
12465 @end deftypeop
12467 @deftypeop {Constructor} {syntax_error} {} syntax_error (@code{const location_type&} @var{l}, @code{const std::string&} @var{m})
12468 @deftypeopx {Constructor}  {syntax_error} {} syntax_error (@code{const std::string&} @var{m})
12469 Instantiate a syntax-error exception.
12470 @end deftypeop
12472 @deftypemethod {parser} {int} operator() ()
12473 @deftypemethodx {parser} {int} parse ()
12474 Run the syntactic analysis, and return 0 on success, 1 otherwise.  Both
12475 routines are equivalent, @code{operator()} being more C++ish.
12477 @cindex exceptions
12478 The whole function is wrapped in a @code{try}/@code{catch} block, so that
12479 when an exception is thrown, the @code{%destructor}s are called to release
12480 the lookahead symbol, and the symbols pushed on the stack.
12482 Exception related code in the generated parser is protected by CPP guards
12483 (@code{#if}) and disabled when exceptions are not supported (i.e., passing
12484 @option{-fno-exceptions} to the C++ compiler).
12485 @end deftypemethod
12487 @deftypemethod {parser} {std::ostream&} debug_stream ()
12488 @deftypemethodx {parser} {void} set_debug_stream (@code{std::ostream&} @var{o})
12489 Get or set the stream used for tracing the parsing.  It defaults to
12490 @code{std::cerr}.
12491 @end deftypemethod
12493 @deftypemethod {parser} {debug_level_type} debug_level ()
12494 @deftypemethodx {parser} {void} set_debug_level (debug_level_type @var{l})
12495 Get or set the tracing level (an integral).  Currently its value is either
12496 0, no trace, or nonzero, full tracing.
12497 @end deftypemethod
12499 @deftypemethod {parser} {void} error (@code{const location_type&} @var{l}, @code{const std::string&} @var{m})
12500 @deftypemethodx {parser} {void} error (@code{const std::string&} @var{m})
12501 The definition for this member function must be supplied by the user: the
12502 parser uses it to report a parser error occurring at @var{l}, described by
12503 @var{m}.  If location tracking is not enabled, the second signature is used.
12504 @end deftypemethod
12507 @node C++ Semantic Values
12508 @subsection C++ Semantic Values
12510 Bison supports two different means to handle semantic values in C++.  One is
12511 alike the C interface, and relies on unions.  As C++ practitioners know,
12512 unions are inconvenient in C++, therefore another approach is provided,
12513 based on variants.
12515 @menu
12516 * C++ Unions::             Semantic values cannot be objects
12517 * C++ Variants::           Using objects as semantic values
12518 @end menu
12520 @node C++ Unions
12521 @subsubsection C++ Unions
12523 The @code{%union} directive works as for C, see @ref{Union Decl}.  In
12524 particular it produces a genuine @code{union}, which have a few specific
12525 features in C++.
12526 @itemize @minus
12527 @item
12528 The value type is @code{yy::parser::value_type}, not @code{YYSTYPE}.
12529 @item
12530 Non POD (Plain Old Data) types cannot be used.  C++98 forbids any instance
12531 of classes with constructors in unions: only @emph{pointers} to such objects
12532 are allowed.  C++11 relaxed this constraints, but at the cost of safety.
12533 @end itemize
12535 Because objects have to be stored via pointers, memory is not
12536 reclaimed automatically: using the @code{%destructor} directive is the
12537 only means to avoid leaks.  @xref{Destructor Decl}.
12539 @node C++ Variants
12540 @subsubsection C++ Variants
12542 Bison provides a @emph{variant} based implementation of semantic values for
12543 C++.  This alleviates all the limitations reported in the previous section,
12544 and in particular, object types can be used without pointers.
12546 To enable variant-based semantic values, set the @code{%define} variable
12547 @code{api.value.type} to @code{variant} (@pxref{%define Summary}).  Then
12548 @code{%union} is ignored; instead of using the name of the fields of the
12549 @code{%union} to ``type'' the symbols, use genuine types.
12551 For instance, instead of:
12553 @example
12554 %union
12556   int ival;
12557   std::string* sval;
12559 %token <ival> NUMBER;
12560 %token <sval> STRING;
12561 @end example
12563 @noindent
12564 write:
12566 @example
12567 %token <int> NUMBER;
12568 %token <std::string> STRING;
12569 @end example
12571 @code{STRING} is no longer a pointer, which should fairly simplify the user
12572 actions in the grammar and in the scanner (in particular the memory
12573 management).
12575 Since C++ features destructors, and since it is customary to specialize
12576 @code{operator<<} to support uniform printing of values, variants also
12577 typically simplify Bison printers and destructors.
12579 Variants are stricter than unions.  When based on unions, you may play any
12580 dirty game with @code{yylval}, say storing an @code{int}, reading a
12581 @code{char*}, and then storing a @code{double} in it.  This is no longer
12582 possible with variants: they must be initialized, then assigned to, and
12583 eventually, destroyed.  As a matter of fact, Bison variants forbid the use
12584 of alternative types such as @samp{$<int>2} or @samp{$<std::string>$}, even
12585 in midrule actions.  It is mandatory to use typed midrule actions
12586 (@pxref{Typed Midrule Actions}).
12588 @deftypemethod {value_type} {T&} {emplace<T>} ()
12589 @deftypemethodx {value_type} {T&} {emplace<T>} (@code{const T&} @var{t})
12590 Available in C++98/C++03 only.  Default construct/copy-construct from
12591 @var{t}.  Return a reference to where the actual value may be stored.
12592 Requires that the variant was not initialized yet.
12593 @end deftypemethod
12595 @deftypemethod {value_type} {T&} {emplace<T, U>} (@code{U&&...} @var{u})
12596 Available in C++11 and later only.  Build a variant of type @code{T} from
12597 the variadic forwarding references @var{u...}.
12598 @end deftypemethod
12600 @strong{Warning}: We do not use Boost.Variant, for two reasons.  First, it
12601 appeared unacceptable to require Boost on the user's machine (i.e., the
12602 machine on which the generated parser will be compiled, not the machine on
12603 which @command{bison} was run).  Second, for each possible semantic value,
12604 Boost.Variant not only stores the value, but also a tag specifying its
12605 type.  But the parser already ``knows'' the type of the semantic value, so
12606 that would be duplicating the information.
12608 We do not use C++17's @code{std::variant} either: we want to support all the
12609 C++ standards, and of course @code{std::variant} also stores a tag to record
12610 the current type.
12612 Therefore we developed light-weight variants whose type tag is external (so
12613 they are really like @code{unions} for C++ actually).  There is a number of
12614 limitations in (the current implementation of) variants:
12615 @itemize
12616 @item
12617 Alignment must be enforced: values should be aligned in memory according to
12618 the most demanding type.  Computing the smallest alignment possible requires
12619 meta-programming techniques that are not currently implemented in Bison, and
12620 therefore, since, as far as we know, @code{double} is the most demanding
12621 type on all platforms, alignments are enforced for @code{double} whatever
12622 types are actually used.  This may waste space in some cases.
12624 @item
12625 There might be portability issues we are not aware of.
12626 @end itemize
12628 As far as we know, these limitations @emph{can} be alleviated.  All it takes
12629 is some time and/or some talented C++ hacker willing to contribute to Bison.
12631 @node C++ Location Values
12632 @subsection C++ Location Values
12634 When the directive @code{%locations} is used, the C++ parser supports
12635 location tracking, see @ref{Tracking Locations}.
12637 By default, two auxiliary classes define a @code{position}, a single point
12638 in a file, and a @code{location}, a range composed of a pair of
12639 @code{position}s (possibly spanning several files).  If the @code{%define}
12640 variable @code{api.location.type} is defined, then these classes will not be
12641 generated, and the user defined type will be used.
12643 @menu
12644 * C++ position::         One point in the source file
12645 * C++ location::         Two points in the source file
12646 * Exposing the Location Classes:: Using the Bison location class in your
12647                                   project
12648 * User Defined Location Type::    Required interface for locations
12649 @end menu
12651 @node C++ position
12652 @subsubsection C++ @code{position}
12654 @defcv {Type} {position} {filename_type}
12655 The base type for file names. Defaults to @code{const std::string}.
12656 @xref{api-filename-type,,@code{api.filename.type}}, to change its definition.
12657 @end defcv
12659 @defcv {Type} {position} {counter_type}
12660 The type used to store line and column numbers.  Defined as @code{int}.
12661 @end defcv
12663 @deftypeop {Constructor} {position} {} position (@code{filename_type*} @var{file} = nullptr, @code{counter_type} @var{line} = 1, @code{counter_type} @var{col} = 1)
12664 Create a @code{position} denoting a given point.  Note that @code{file} is
12665 not reclaimed when the @code{position} is destroyed: memory managed must be
12666 handled elsewhere.
12667 @end deftypeop
12669 @deftypemethod {position} {void} initialize (@code{filename_type*} @var{file} = nullptr, @code{counter_type} @var{line} = 1, @code{counter_type} @var{col} = 1)
12670 Reset the position to the given values.
12671 @end deftypemethod
12673 @deftypeivar {position} {filename_type*} file
12674 The name of the file.  It will always be handled as a pointer, the parser
12675 will never duplicate nor deallocate it.
12676 @end deftypeivar
12678 @deftypeivar {position} {counter_type} line
12679 The line, starting at 1.
12680 @end deftypeivar
12682 @deftypemethod {position} {void} lines (@code{counter_type} @var{height} = 1)
12683 If @var{height} is not null, advance by @var{height} lines, resetting the
12684 column number.  The resulting line number cannot be less than 1.
12685 @end deftypemethod
12687 @deftypeivar {position} {counter_type} column
12688 The column, starting at 1.
12689 @end deftypeivar
12691 @deftypemethod {position} {void} columns (@code{counter_type} @var{width} = 1)
12692 Advance by @var{width} columns, without changing the line number. The
12693 resulting column number cannot be less than 1.
12694 @end deftypemethod
12696 @deftypemethod {position} {position&} operator+= (@code{counter_type} @var{width})
12697 @deftypemethodx {position} {position} operator+ (@code{counter_type} @var{width})
12698 @deftypemethodx {position} {position&} operator-= (@code{counter_type} @var{width})
12699 @deftypemethodx {position} {position} operator- (@code{counter_type} @var{width})
12700 Various forms of syntactic sugar for @code{columns}.
12701 @end deftypemethod
12703 @deftypemethod {position} {bool} operator== (@code{const position&} @var{that})
12704 @deftypemethodx {position} {bool} operator!= (@code{const position&} @var{that})
12705 Whether @code{*this} and @code{that} denote equal/different positions.
12706 @end deftypemethod
12708 @deftypefun {std::ostream&} operator<< (@code{std::ostream&} @var{o}, @code{const position&} @var{p})
12709 Report @var{p} on @var{o} like this:
12710 @samp{@var{file}:@var{line}.@var{column}}, or
12711 @samp{@var{line}.@var{column}} if @var{file} is null.
12712 @end deftypefun
12714 @node C++ location
12715 @subsubsection C++ @code{location}
12717 @deftypeop {Constructor} {location} {} location (@code{const position&} @var{begin}, @code{const position&} @var{end})
12718 Create a @code{Location} from the endpoints of the range.
12719 @end deftypeop
12721 @deftypeop {Constructor} {location} {} location (@code{const position&} @var{pos} = position())
12722 @deftypeopx {Constructor} {location} {} location (@code{filename_type*} @var{file}, @code{counter_type} @var{line}, @code{counter_type} @var{col})
12723 Create a @code{Location} denoting an empty range located at a given point.
12724 @end deftypeop
12726 @deftypemethod {location} {void} initialize (@code{filename_type*} @var{file} = nullptr, @code{counter_type} @var{line} = 1, @code{counter_type} @var{col} = 1)
12727 Reset the location to an empty range at the given values.
12728 @end deftypemethod
12730 @deftypeivar {location} {position} begin
12731 @deftypeivarx {location} {position} end
12732 The first, inclusive, position of the range, and the first beyond.
12733 @end deftypeivar
12735 @deftypemethod {location} {void} columns (@code{counter_type} @var{width} = 1)
12736 @deftypemethodx {location} {void} lines (@code{counter_type} @var{height} = 1)
12737 Forwarded to the @code{end} position.
12738 @end deftypemethod
12740 @deftypemethod  {location} {location} operator+  (@code{counter_type} @var{width})
12741 @deftypemethodx {location} {location} operator+= (@code{counter_type} @var{width})
12742 @deftypemethodx {location} {location} operator-  (@code{counter_type} @var{width})
12743 @deftypemethodx {location} {location} operator-= (@code{counter_type} @var{width})
12744 Various forms of syntactic sugar for @code{columns}.
12745 @end deftypemethod
12747 @deftypemethod {location} {location} operator+ (@code{const location&} @var{end})
12748 @deftypemethodx {location} {location} operator+= (@code{const location&} @var{end})
12749 Join two locations: starts at the position of the first one, and ends at the
12750 position of the second.
12751 @end deftypemethod
12753 @deftypemethod {location} {void} step ()
12754 Move @code{begin} onto @code{end}.
12755 @end deftypemethod
12757 @deftypemethod {location} {bool} operator== (@code{const location&} @var{that})
12758 @deftypemethodx {location} {bool} operator!= (@code{const location&} @var{that})
12759 Whether @code{*this} and @code{that} denote equal/different ranges of
12760 positions.
12761 @end deftypemethod
12763 @deftypefun {std::ostream&} operator<< (@code{std::ostream&} @var{o}, @code{const location&} @var{p})
12764 Report @var{p} on @var{o}, taking care of special cases such as: no
12765 @code{filename} defined, or equal filename/line or column.
12766 @end deftypefun
12768 @node Exposing the Location Classes
12769 @subsubsection Exposing the Location Classes
12771 When both @code{%header} and @code{%locations} are enabled, Bison generates
12772 an additional file: @file{location.hh}.  If you don't use locations outside
12773 of the parser, you may avoid its creation with @samp{%define
12774 api.location.file none}.
12776 However this file is useful if, for instance, your parser builds an abstract
12777 syntax tree decorated with locations: you may use Bison's @code{location}
12778 type independently of Bison's parser.  You may name the file differently,
12779 e.g., @samp{%define api.location.file "include/ast/location.hh"}: this name
12780 can have directory components, or even be absolute.  The way the location
12781 file is included is controlled by @code{api.location.include}.
12783 This way it is possible to have several parsers share the same location
12784 file.
12786 For instance, in @file{src/foo/parser.yy}, generate the
12787 @file{include/ast/loc.hh} file:
12789 @example
12790 // src/foo/parser.yy
12791 %locations
12792 %define api.namespace @{foo@}
12793 %define api.location.file "include/ast/loc.hh"
12794 %define api.location.include @{<ast/loc.hh>@}
12795 @end example
12797 @noindent
12798 and use it in @file{src/bar/parser.yy}:
12800 @example
12801 // src/bar/parser.yy
12802 %locations
12803 %define api.namespace @{bar@}
12804 %code requires @{#include <ast/loc.hh>@}
12805 %define api.location.type @{bar::location@}
12806 @end example
12808 Absolute file names are supported; it is safe in your @file{Makefile} to
12809 pass the flag
12810 @option{-Dapi.location.file='"$(top_srcdir)/include/ast/loc.hh"'} to
12811 @command{bison} for @file{src/foo/parser.yy}.  The generated file will not
12812 have references to this absolute path, thanks to @samp{%define
12813 api.location.include @{<ast/loc.hh>@}}.  Adding @samp{-I
12814 $(top_srcdir)/include} to your @code{CPPFLAGS} will suffice for the compiler
12815 to find @file{ast/loc.hh}.
12817 @node User Defined Location Type
12818 @subsubsection User Defined Location Type
12819 @findex %define api.location.type
12821 Instead of using the built-in types you may use the @code{%define} variable
12822 @code{api.location.type} to specify your own type:
12824 @example
12825 %define api.location.type @{@var{LocationType}@}
12826 @end example
12828 The requirements over your @var{LocationType} are:
12829 @itemize
12830 @item
12831 it must be copyable;
12833 @item
12834 in order to compute the (default) value of @code{@@$} in a reduction, the
12835 parser basically runs
12836 @example
12837 @@$.begin = @@1.begin;
12838 @@$.end   = @@@var{N}.end; // The location of last right-hand side symbol.
12839 @end example
12840 @noindent
12841 so there must be copyable @code{begin} and @code{end} members;
12843 @item
12844 alternatively you may redefine the computation of the default location, in
12845 which case these members are not required (@pxref{Location Default Action});
12847 @item
12848 if traces are enabled, then there must exist an @samp{std::ostream&
12849   operator<< (std::ostream& o, const @var{LocationType}& s)} function.
12850 @end itemize
12852 @sp 1
12854 In programs with several C++ parsers, you may also use the @code{%define}
12855 variable @code{api.location.type} to share a common set of built-in
12856 definitions for @code{position} and @code{location}.  For instance, one
12857 parser @file{master/parser.yy} might use:
12859 @example
12860 %header
12861 %locations
12862 %define api.namespace @{master::@}
12863 @end example
12865 @noindent
12866 to generate the @file{master/position.hh} and @file{master/location.hh}
12867 files, reused by other parsers as follows:
12869 @example
12870 %define api.location.type @{master::location@}
12871 %code requires @{ #include <master/location.hh> @}
12872 @end example
12875 @node C++ Parser Context
12876 @subsection C++ Parser Context
12878 When @samp{%define parse.error custom} is used (@pxref{Syntax Error
12879 Reporting Function}), the user must define the following function.
12881 @deftypemethod {parser} {void} report_syntax_error (@code{const context_type&}@var{ctx}) @code{const}
12882 Report a syntax error to the user.  Whether it uses @code{yyerror} is up to
12883 the user.
12884 @end deftypemethod
12886 Use the following types and functions to build the error message.
12888 @defcv {Type} {parser} {context}
12889 A type that captures the circumstances of the syntax error.
12890 @end defcv
12892 @defcv {Type} {parser} {symbol_kind_type}
12893 An enum of all the grammar symbols, tokens and nonterminals.  Its
12894 enumerators are forged from the symbol names:
12896 @example
12897 struct symbol_kind
12899   enum symbol_kind_type
12900   @{
12901     S_YYEMPTY = -2,      // No symbol.
12902     S_YYEOF = 0,         // "end of file"
12903     S_YYERROR = 1,       // error
12904     S_YYUNDEF = 2,       // "invalid token"
12905     S_PLUS = 3,          // "+"
12906     S_MINUS = 4,         // "-"
12907     [...]
12908     S_VAR = 14,          // "variable"
12909     S_NEG = 15,          // NEG
12910     S_YYACCEPT = 16,     // $accept
12911     S_exp = 17,          // exp
12912     S_input = 18         // input
12913   @};
12915 typedef symbol_kind::symbol_kind_t symbol_kind_type;
12916 @end example
12917 @end defcv
12919 @deftypemethod {context} {const symbol_type&} lookahead () @code{const}
12920 The ``unexpected'' token: the lookahead that caused the syntax error.
12921 @end deftypemethod
12923 @deftypemethod {context} {symbol_kind_type} token () @code{const}
12924 The symbol kind of the lookahead token that caused the syntax error.  Returns
12925 @code{symbol_kind::S_YYEMPTY} if there is no lookahead.
12926 @end deftypemethod
12928 @deftypemethod {context} {const location&} location () @code{const}
12929 The location of the syntax error (that of the lookahead).
12930 @end deftypemethod
12932 @deftypemethod {context} int expected_tokens (@code{symbol_kind_type} @var{argv}@code{[]}, @code{int} @var{argc}) @code{const}
12933 Fill @var{argv} with the expected tokens, which never includes
12934 @code{symbol_kind::S_YYEMPTY}, @code{symbol_kind::S_YYERROR}, or
12935 @code{symbol_kind::S_YYUNDEF}.
12937 Never put more than @var{argc} elements into @var{argv}, and on success
12938 return the number of tokens stored in @var{argv}.  If there are more
12939 expected tokens than @var{argc}, fill @var{argv} up to @var{argc} and return
12940 0.  If there are no expected tokens, also return 0, but set @code{argv[0]}
12941 to @code{symbol_kind::S_YYEMPTY}.
12943 If @var{argv} is null, return the size needed to store all the possible
12944 values, which is always less than @code{YYNTOKENS}.
12945 @end deftypemethod
12947 @deftypemethod {parser} {const char *} symbol_name (@code{symbol_kind_t} @var{symbol}) @code{const}
12948 The name of the symbol whose kind is @var{symbol}, possibly translated.
12950 Returns a @code{std::string} when @code{parse.error} is @code{verbose}.
12951 @end deftypemethod
12953 A custom syntax error function looks as follows.  This implementation is
12954 inappropriate for internationalization, see the @file{c/bistromathic}
12955 example for a better alternative.
12957 @example
12958 void
12959 yy::parser::report_syntax_error (const context& ctx)
12961   int res = 0;
12962   std::cerr << ctx.location () << ": syntax error";
12963   // Report the tokens expected at this point.
12964   @{
12965     enum @{ TOKENMAX = 5 @};
12966     symbol_kind_type expected[TOKENMAX];
12967     int n = ctx.expected_tokens (ctx, expected, TOKENMAX);
12968     for (int i = 0; i < n; ++i)
12969       std::cerr << i == 0 ? ": expected " : " or "
12970                 << symbol_name (expected[i]);
12971   @}
12972   // Report the unexpected token.
12973   @{
12974     symbol_kind_type lookahead = ctx.token ();
12975     if (lookahead != symbol_kind::S_YYEMPTY)
12976       std::cerr << " before " << symbol_name (lookahead));
12977   @}
12978   std::cerr << '\n';
12980 @end example
12982 You still must provide a @code{yyerror} function, used for instance to
12983 report memory exhaustion.
12986 @node C++ Scanner Interface
12987 @subsection C++ Scanner Interface
12988 @c - prefix for yylex.
12989 @c - Pure interface to yylex
12990 @c - %lex-param
12992 The parser invokes the scanner by calling @code{yylex}.  Contrary to C
12993 parsers, C++ parsers are always pure: there is no point in using the
12994 @samp{%define api.pure} directive.  The actual interface with @code{yylex}
12995 depends whether you use unions, or variants.
12997 @menu
12998 * Split Symbols::         Passing symbols as two/three components
12999 * Complete Symbols::      Making symbols a whole
13000 @end menu
13002 @node Split Symbols
13003 @subsubsection Split Symbols
13005 The generated parser expects @code{yylex} to have the following prototype.
13007 @deftypefun {int} yylex (@code{value_type*} @var{yylval}, @code{location_type*} @var{yylloc}, @var{type1} @var{arg1}, @dots{})
13008 @deftypefunx {int} yylex (@code{value_type*} @var{yylval}, @var{type1} @var{arg1}, @dots{})
13009 Return the next token.  Its kind is the return value, its semantic value and
13010 location (if enabled) being @var{yylval} and @var{yylloc}.  Invocations of
13011 @samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
13012 @end deftypefun
13014 Note that when using variants, the interface for @code{yylex} is the same,
13015 but @code{yylval} is handled differently.
13017 Regular union-based code in Lex scanner typically looks like:
13019 @example
13020 [0-9]+   @{
13021            yylval->ival = text_to_int (yytext);
13022            return yy::parser::token::INTEGER;
13023          @}
13024 [a-z]+   @{
13025            yylval->sval = new std::string (yytext);
13026            return yy::parser::token::IDENTIFIER;
13027          @}
13028 @end example
13030 Using variants, @code{yylval} is already constructed, but it is not
13031 initialized.  So the code would look like:
13033 @example
13034 [0-9]+   @{
13035            yylval->emplace<int> () = text_to_int (yytext);
13036            return yy::parser::token::INTEGER;
13037          @}
13038 [a-z]+   @{
13039            yylval->emplace<std::string> () = yytext;
13040            return yy::parser::token::IDENTIFIER;
13041          @}
13042 @end example
13044 @noindent
13047 @example
13048 [0-9]+   @{
13049            yylval->emplace (text_to_int (yytext));
13050            return yy::parser::token::INTEGER;
13051          @}
13052 [a-z]+   @{
13053            yylval->emplace (yytext);
13054            return yy::parser::token::IDENTIFIER;
13055          @}
13056 @end example
13059 @node Complete Symbols
13060 @subsubsection Complete Symbols
13062 With both @code{%define api.value.type variant} and @code{%define
13063 api.token.constructor}, the parser defines the type @code{symbol_type}, and
13064 expects @code{yylex} to have the following prototype.
13066 @deftypefun {parser::symbol_type} yylex ()
13067 @deftypefunx {parser::symbol_type} yylex (@var{type1} @var{arg1}, @dots{})
13068 Return a @emph{complete} symbol, aggregating its type (i.e., the traditional
13069 value returned by @code{yylex}), its semantic value, and possibly its
13070 location.  Invocations of @samp{%lex-param @{@var{type1} @var{arg1}@}} yield
13071 additional arguments.
13072 @end deftypefun
13074 @defcv {Type} {parser} {symbol_type}
13075 A ``complete symbol'', that binds together its kind, value and (when
13076 applicable) location.
13077 @end defcv
13079 @deftypemethod {symbol_type} {symbol_kind_type} kind () @code{const}
13080 The kind of this symbol.
13081 @end deftypemethod
13083 @deftypemethod {symbol_type} {const char *} name () @code{const}
13084 The name of the kind of this symbol.
13086 Returns a @code{std::string} when @code{parse.error} is @code{verbose}.
13087 @end deftypemethod
13089 @sp 1
13091 For each token kind, Bison generates named constructors as follows.
13093 @deftypeop  {Constructor} {parser::symbol_type} {} {symbol_type} (@code{int} @var{token}, @code{const @var{value_type}&} @var{value}, @code{const location_type&} @var{location})
13094 @deftypeopx {Constructor} {parser::symbol_type} {} {symbol_type} (@code{int} @var{token}, @code{const location_type&} @var{location})
13095 @deftypeopx {Constructor} {parser::symbol_type} {} {symbol_type} (@code{int} @var{token}, @code{const @var{value_type}&} @var{value})
13096 @deftypeopx {Constructor} {parser::symbol_type} {} {symbol_type} (@code{int} @var{token})
13097 Build a complete terminal symbol for the token kind @var{token} (including
13098 the @code{api.token.prefix}), whose semantic value, if it has one, is
13099 @var{value} of adequate @var{value_type}.  Pass the @var{location} iff
13100 location tracking is enabled.
13102 Consistency between @var{token} and @var{value_type} is checked via an
13103 @code{assert}.
13104 @end deftypeop
13106 For instance, given the following declarations:
13108 @example
13109 %define api.token.prefix @{TOK_@}
13110 %token <std::string> IDENTIFIER;
13111 %token <int> INTEGER;
13112 %token ':';
13113 @end example
13115 @noindent
13116 you may use these constructors:
13118 @example
13119 symbol_type (int token, const std::string&, const location_type&);
13120 symbol_type (int token, const int&, const location_type&);
13121 symbol_type (int token, const location_type&);
13122 @end example
13124 Correct matching between token kinds and value types is checked via
13125 @code{assert}; for instance, @samp{symbol_type (ID, 42)} would abort.  Named
13126 constructors are preferable (see below), as they offer better type safety
13127 (for instance @samp{make_ID (42)} would not even compile), but symbol_type
13128 constructors may help when token kinds are discovered at run-time, e.g.,
13130 @example
13131 @group
13132 [a-z]+   @{
13133            if (auto i = lookup_keyword (yytext))
13134              return yy::parser::symbol_type (i, loc);
13135            else
13136              return yy::parser::make_ID (yytext, loc);
13137          @}
13138 @end group
13139 @end example
13141 @sp 1
13143 Note that it is possible to generate and compile type incorrect code
13144 (e.g. @samp{symbol_type (':', yytext, loc)}).  It will fail at run time,
13145 provided the assertions are enabled (i.e., @option{-DNDEBUG} was not passed
13146 to the compiler).  Bison supports an alternative that guarantees that type
13147 incorrect code will not even compile.  Indeed, it generates @emph{named
13148 constructors} as follows.
13150 @deftypemethod {parser} {symbol_type} {make_@var{token}} (@code{const @var{value_type}&} @var{value}, @code{const location_type&} @var{location})
13151 @deftypemethodx {parser} {symbol_type} {make_@var{token}} (@code{const location_type&} @var{location})
13152 @deftypemethodx {parser} {symbol_type} {make_@var{token}} (@code{const @var{value_type}&} @var{value})
13153 @deftypemethodx {parser} {symbol_type} {make_@var{token}} ()
13154 Build a complete terminal symbol for the token kind @var{token} (not
13155 including the @code{api.token.prefix}), whose semantic value, if it has one,
13156 is @var{value} of adequate @var{value_type}.  Pass the @var{location} iff
13157 location tracking is enabled.
13158 @end deftypemethod
13160 For instance, given the following declarations:
13162 @example
13163 %define api.token.prefix @{TOK_@}
13164 %token <std::string> IDENTIFIER;
13165 %token <int> INTEGER;
13166 %token COLON;
13167 %token EOF 0;
13168 @end example
13170 @noindent
13171 Bison generates:
13173 @example
13174 symbol_type make_IDENTIFIER (const std::string&, const location_type&);
13175 symbol_type make_INTEGER (const int&, const location_type&);
13176 symbol_type make_COLON (const location_type&);
13177 symbol_type make_EOF (const location_type&);
13178 @end example
13180 @noindent
13181 which should be used in a scanner as follows.
13183 @example
13184 [a-z]+   return yy::parser::make_IDENTIFIER (yytext, loc);
13185 [0-9]+   return yy::parser::make_INTEGER (text_to_int (yytext), loc);
13186 ":"      return yy::parser::make_COLON (loc);
13187 <<EOF>>  return yy::parser::make_EOF (loc);
13188 @end example
13190 Tokens that do not have an identifier are not accessible: you cannot simply
13191 use characters such as @code{':'}, they must be declared with @code{%token},
13192 including the end-of-file token.
13195 @node A Complete C++ Example
13196 @subsection A Complete C++ Example
13198 This section demonstrates the use of a C++ parser with a simple but complete
13199 example.  This example should be available on your system, ready to compile,
13200 in the directory @file{examples/c++/calc++}.  It focuses on
13201 the use of Bison, therefore the design of the various C++ classes is very
13202 naive: no accessors, no encapsulation of members etc.  We will use a Lex
13203 scanner, and more precisely, a Flex scanner, to demonstrate the various
13204 interactions.  A hand-written scanner is actually easier to interface with.
13206 @menu
13207 * Calc++ --- C++ Calculator::   The specifications
13208 * Calc++ Parsing Driver::       An active parsing context
13209 * Calc++ Parser::               A parser class
13210 * Calc++ Scanner::              A pure C++ Flex scanner
13211 * Calc++ Top Level::            Conducting the band
13212 @end menu
13214 @node Calc++ --- C++ Calculator
13215 @subsubsection Calc++ --- C++ Calculator
13217 Of course the grammar is dedicated to arithmetic, a single expression,
13218 possibly preceded by variable assignments.  An environment containing
13219 possibly predefined variables such as @code{one} and @code{two}, is
13220 exchanged with the parser.  An example of valid input follows.
13222 @example
13223 three := 3
13224 seven := one + two * three
13225 seven * seven
13226 @end example
13228 @node Calc++ Parsing Driver
13229 @subsubsection Calc++ Parsing Driver
13230 @c - An env
13231 @c - A place to store error messages
13232 @c - A place for the result
13234 To support a pure interface with the parser (and the scanner) the technique
13235 of the ``parsing context'' is convenient: a structure containing all the
13236 data to exchange.  Since, in addition to simply launch the parsing, there
13237 are several auxiliary tasks to execute (open the file for scanning,
13238 instantiate the parser etc.), we recommend transforming the simple parsing
13239 context structure into a fully blown @dfn{parsing driver} class.
13241 The declaration of this driver class, in @file{driver.hh}, is as follows.
13242 The first part includes the CPP guard and imports the required standard
13243 library components, and the declaration of the parser class.
13245 @ignore
13246 @comment file: c++/calc++/driver.hh
13247 @example
13248 /* Driver for calc++.   -*- C++ -*-
13250    Copyright (C) 2005-2015, 2018-2021 Free Software Foundation, Inc.
13252    This file is part of Bison, the GNU Compiler Compiler.
13254    This program is free software: you can redistribute it and/or modify
13255    it under the terms of the GNU General Public License as published by
13256    the Free Software Foundation, either version 3 of the License, or
13257    (at your option) any later version.
13259    This program is distributed in the hope that it will be useful,
13260    but WITHOUT ANY WARRANTY; without even the implied warranty of
13261    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13262    GNU General Public License for more details.
13264    You should have received a copy of the GNU General Public License
13265    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
13266 @end example
13267 @end ignore
13269 @comment file: c++/calc++/driver.hh
13270 @example
13271 #ifndef DRIVER_HH
13272 # define DRIVER_HH
13273 # include <string>
13274 # include <map>
13275 # include "parser.hh"
13276 @end example
13279 @noindent
13280 Then comes the declaration of the scanning function.  Flex expects the
13281 signature of @code{yylex} to be defined in the macro @code{YY_DECL}, and the
13282 C++ parser expects it to be declared.  We can factor both as follows.
13284 @comment file: c++/calc++/driver.hh
13285 @example
13286 // Give Flex the prototype of yylex we want ...
13287 # define YY_DECL \
13288   yy::parser::symbol_type yylex (driver& drv)
13289 // ... and declare it for the parser's sake.
13290 YY_DECL;
13291 @end example
13293 @noindent
13294 The @code{driver} class is then declared with its most obvious members.
13296 @comment file: c++/calc++/driver.hh
13297 @example
13298 // Conducting the whole scanning and parsing of Calc++.
13299 class driver
13301 public:
13302   driver ();
13304   std::map<std::string, int> variables;
13306   int result;
13307 @end example
13309 @noindent
13310 The main routine is of course calling the parser.
13312 @comment file: c++/calc++/driver.hh
13313 @example
13314   // Run the parser on file F.  Return 0 on success.
13315   int parse (const std::string& f);
13316   // The name of the file being parsed.
13317   std::string file;
13318   // Whether to generate parser debug traces.
13319   bool trace_parsing;
13320 @end example
13322 @noindent
13323 To encapsulate the coordination with the Flex scanner, it is useful to have
13324 member functions to open and close the scanning phase.
13326 @comment file: c++/calc++/driver.hh
13327 @example
13328   // Handling the scanner.
13329   void scan_begin ();
13330   void scan_end ();
13331   // Whether to generate scanner debug traces.
13332   bool trace_scanning;
13333   // The token's location used by the scanner.
13334   yy::location location;
13336 #endif // ! DRIVER_HH
13337 @end example
13339 The implementation of the driver (@file{driver.cc}) is straightforward.
13341 @ignore
13342 @comment file: c++/calc++/driver.cc
13343 @example
13344 /* Driver for calc++.   -*- C++ -*-
13346    Copyright (C) 2005-2015, 2018-2021 Free Software Foundation, Inc.
13348    This file is part of Bison, the GNU Compiler Compiler.
13350    This program is free software: you can redistribute it and/or modify
13351    it under the terms of the GNU General Public License as published by
13352    the Free Software Foundation, either version 3 of the License, or
13353    (at your option) any later version.
13355    This program is distributed in the hope that it will be useful,
13356    but WITHOUT ANY WARRANTY; without even the implied warranty of
13357    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13358    GNU General Public License for more details.
13360    You should have received a copy of the GNU General Public License
13361    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
13362 @end example
13363 @end ignore
13365 @comment file: c++/calc++/driver.cc
13366 @example
13367 #include "driver.hh"
13368 #include "parser.hh"
13370 @group
13371 driver::driver ()
13372   : trace_parsing (false), trace_scanning (false)
13374   variables["one"] = 1;
13375   variables["two"] = 2;
13377 @end group
13378 @end example
13380 The @code{parse} member function deserves some attention.
13382 @comment file: c++/calc++/driver.cc
13383 @example
13384 @group
13386 driver::parse (const std::string &f)
13388   file = f;
13389   location.initialize (&file);
13390   scan_begin ();
13391   yy::parser parse (*this);
13392   parse.set_debug_level (trace_parsing);
13393   int res = parse ();
13394   scan_end ();
13395   return res;
13397 @end group
13398 @end example
13400 @node Calc++ Parser
13401 @subsubsection Calc++ Parser
13403 The grammar file @file{parser.yy} starts by asking for the C++ deterministic
13404 parser skeleton, the creation of the parser header file.  Because the C++
13405 skeleton changed several times, it is safer to require the version you
13406 designed the grammar for.
13408 @ignore
13409 @comment file: c++/calc++/parser.yy
13410 @example
13411 /* Parser for calc++.   -*- C++ -*-
13413    Copyright (C) 2005-2015, 2018-2021 Free Software Foundation, Inc.
13415    This file is part of Bison, the GNU Compiler Compiler.
13417    This program is free software: you can redistribute it and/or modify
13418    it under the terms of the GNU General Public License as published by
13419    the Free Software Foundation, either version 3 of the License, or
13420    (at your option) any later version.
13422    This program is distributed in the hope that it will be useful,
13423    but WITHOUT ANY WARRANTY; without even the implied warranty of
13424    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13425    GNU General Public License for more details.
13427    You should have received a copy of the GNU General Public License
13428    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
13429 @end example
13430 @end ignore
13432 @comment file: c++/calc++/parser.yy
13433 @example
13434 %skeleton "lalr1.cc" // -*- C++ -*-
13435 %require "@value{VERSION}"
13436 %header
13437 @end example
13439 @noindent
13440 @findex %define api.token.raw
13441 Because our scanner returns only genuine tokens and never simple characters
13442 (i.e., it returns @samp{PLUS}, not @samp{'+'}), we can avoid conversions.
13444 @comment file: c++/calc++/parser.yy
13445 @example
13446 %define api.token.raw
13447 @end example
13449 @noindent
13450 @findex %define api.token.constructor
13451 @findex %define api.value.type variant
13452 This example uses genuine C++ objects as semantic values, therefore, we
13453 require the variant-based storage of semantic values.  To make sure we
13454 properly use it, we enable assertions.  To fully benefit from type-safety
13455 and more natural definition of ``symbol'', we enable
13456 @code{api.token.constructor}.
13458 @comment file: c++/calc++/parser.yy
13459 @example
13460 %define api.token.constructor
13461 %define api.value.type variant
13462 %define parse.assert
13463 @end example
13465 @noindent
13466 @findex %code requires
13467 Then come the declarations/inclusions needed by the semantic values.
13468 Because the parser uses the parsing driver and reciprocally, both would like
13469 to include the header of the other, which is, of course, insane.  This
13470 mutual dependency will be broken using forward declarations.  Because the
13471 driver's header needs detailed knowledge about the parser class (in
13472 particular its inner types), it is the parser's header which will use a
13473 forward declaration of the driver.  @xref{%code Summary}.
13475 @comment file: c++/calc++/parser.yy
13476 @example
13477 @group
13478 %code requires @{
13479   # include <string>
13480   class driver;
13482 @end group
13483 @end example
13485 @noindent
13486 The driver is passed by reference to the parser and to the scanner.
13487 This provides a simple but effective pure interface, not relying on
13488 global variables.
13490 @comment file: c++/calc++/parser.yy
13491 @example
13492 // The parsing context.
13493 %param @{ driver& drv @}
13494 @end example
13496 @noindent
13497 Then we request location tracking.
13499 @comment file: c++/calc++/parser.yy
13500 @example
13501 %locations
13502 @end example
13504 @noindent
13505 Use the following two directives to enable parser tracing and detailed error
13506 messages.  However, detailed error messages can contain incorrect
13507 information if lookahead correction is not enabled (@pxref{LAC}).
13509 @comment file: c++/calc++/parser.yy
13510 @example
13511 %define parse.trace
13512 %define parse.error detailed
13513 %define parse.lac full
13514 @end example
13516 @noindent
13517 @findex %code
13518 The code between @samp{%code @{} and @samp{@}} is output in the @file{*.cc}
13519 file; it needs detailed knowledge about the driver.
13521 @comment file: c++/calc++/parser.yy
13522 @example
13523 @group
13524 %code @{
13525 # include "driver.hh"
13527 @end group
13528 @end example
13531 @noindent
13532 User friendly names are provided for each symbol.  To avoid name clashes in
13533 the generated files (@pxref{Calc++ Scanner}), prefix tokens with @code{TOK_}
13534 (@pxref{%define Summary}).
13536 @comment file: c++/calc++/parser.yy
13537 @example
13538 %define api.token.prefix @{TOK_@}
13539 %token
13540   ASSIGN  ":="
13541   MINUS   "-"
13542   PLUS    "+"
13543   STAR    "*"
13544   SLASH   "/"
13545   LPAREN  "("
13546   RPAREN  ")"
13548 @end example
13550 @noindent
13551 Since we use variant-based semantic values, @code{%union} is not used, and
13552 @code{%token}, @code{%nterm} and @code{%type} expect genuine types, not type
13553 tags.
13555 @comment file: c++/calc++/parser.yy
13556 @example
13557 %token <std::string> IDENTIFIER "identifier"
13558 %token <int> NUMBER "number"
13559 %nterm <int> exp
13560 @end example
13562 @noindent
13563 No @code{%destructor} is needed to enable memory deallocation during error
13564 recovery; the memory, for strings for instance, will be reclaimed by the
13565 regular destructors.  All the values are printed using their
13566 @code{operator<<} (@pxref{Printer Decl}).
13568 @comment file: c++/calc++/parser.yy
13569 @example
13570 %printer @{ yyo << $$; @} <*>;
13571 @end example
13573 @noindent
13574 The grammar itself is straightforward (@pxref{Location Tracking Calc}).
13576 @comment file: c++/calc++/parser.yy
13577 @example
13579 %start unit;
13580 unit: assignments exp  @{ drv.result = $2; @};
13582 assignments:
13583   %empty                 @{@}
13584 | assignments assignment @{@};
13586 assignment:
13587   "identifier" ":=" exp @{ drv.variables[$1] = $3; @};
13589 %left "+" "-";
13590 %left "*" "/";
13591 exp:
13592   "number"
13593 | "identifier"  @{ $$ = drv.variables[$1]; @}
13594 | exp "+" exp   @{ $$ = $1 + $3; @}
13595 | exp "-" exp   @{ $$ = $1 - $3; @}
13596 | exp "*" exp   @{ $$ = $1 * $3; @}
13597 | exp "/" exp   @{ $$ = $1 / $3; @}
13598 | "(" exp ")"   @{ $$ = $2; @}
13600 @end example
13602 @noindent
13603 Finally the @code{error} member function reports the errors.
13605 @comment file: c++/calc++/parser.yy
13606 @example
13607 void
13608 yy::parser::error (const location_type& l, const std::string& m)
13610   std::cerr << l << ": " << m << '\n';
13612 @end example
13614 @node Calc++ Scanner
13615 @subsubsection Calc++ Scanner
13617 In addition to standard headers, the Flex scanner includes the driver's,
13618 then the parser's to get the set of defined tokens.
13620 @ignore
13621 @comment file: c++/calc++/scanner.ll
13622 @example
13623 /* Scanner for calc++.   -*- C++ -*-
13625    Copyright (C) 2005-2015, 2018-2021 Free Software Foundation, Inc.
13627    This file is part of Bison, the GNU Compiler Compiler.
13629    This program is free software: you can redistribute it and/or modify
13630    it under the terms of the GNU General Public License as published by
13631    the Free Software Foundation, either version 3 of the License, or
13632    (at your option) any later version.
13634    This program is distributed in the hope that it will be useful,
13635    but WITHOUT ANY WARRANTY; without even the implied warranty of
13636    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13637    GNU General Public License for more details.
13639    You should have received a copy of the GNU General Public License
13640    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
13641 @end example
13642 @end ignore
13644 @comment file: c++/calc++/scanner.ll
13645 @example
13646 %@{ /* -*- C++ -*- */
13647 # include <cerrno>
13648 # include <climits>
13649 # include <cstdlib>
13650 # include <cstring> // strerror
13651 # include <string>
13652 # include "driver.hh"
13653 # include "parser.hh"
13655 @end example
13657 @ignore
13658 @comment file: c++/calc++/scanner.ll
13659 @example
13661 #if defined __clang__
13662 # define CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
13663 #endif
13665 // Clang and ICC like to pretend they are GCC.
13666 #if defined __GNUC__ && !defined __clang__ && !defined __ICC
13667 # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
13668 #endif
13670 // Pacify warnings in yy_init_buffer (observed with Flex 2.6.4)
13671 // and GCC 6.4.0, 7.3.0 with -O3.
13672 #if defined GCC_VERSION && 600 <= GCC_VERSION
13673 # pragma GCC diagnostic ignored "-Wnull-dereference"
13674 #endif
13676 // This example uses Flex's C back end, yet compiles it as C++.
13677 // So expect warnings about C style casts and NULL.
13678 #if defined CLANG_VERSION && 500 <= CLANG_VERSION
13679 # pragma clang diagnostic ignored "-Wold-style-cast"
13680 # pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
13681 #elif defined GCC_VERSION && 407 <= GCC_VERSION
13682 # pragma GCC diagnostic ignored "-Wold-style-cast"
13683 # pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
13684 #endif
13686 #define FLEX_VERSION (YY_FLEX_MAJOR_VERSION * 100 + YY_FLEX_MINOR_VERSION)
13688 // Old versions of Flex (2.5.35) generate an incomplete documentation comment.
13690 //  In file included from src/scan-code-c.c:3:
13691 //  src/scan-code.c:2198:21: error: empty paragraph passed to '@param' command
13692 //        [-Werror,-Wdocumentation]
13693 //   * @param line_number
13694 //     ~~~~~~~~~~~~~~~~~^
13695 //  1 error generated.
13696 #if FLEX_VERSION < 206 && defined CLANG_VERSION
13697 # pragma clang diagnostic ignored "-Wdocumentation"
13698 #endif
13700 // Old versions of Flex (2.5.35) use 'register'.  Warnings introduced in
13701 // GCC 7 and Clang 6.
13702 #if FLEX_VERSION < 206
13703 # if defined CLANG_VERSION && 600 <= CLANG_VERSION
13704 #  pragma clang diagnostic ignored "-Wdeprecated-register"
13705 # elif defined GCC_VERSION && 700 <= GCC_VERSION
13706 #  pragma GCC diagnostic ignored "-Wregister"
13707 # endif
13708 #endif
13710 #if FLEX_VERSION < 206
13711 # if defined CLANG_VERSION
13712 #  pragma clang diagnostic ignored "-Wconversion"
13713 #  pragma clang diagnostic ignored "-Wdocumentation"
13714 #  pragma clang diagnostic ignored "-Wshorten-64-to-32"
13715 #  pragma clang diagnostic ignored "-Wsign-conversion"
13716 # elif defined GCC_VERSION
13717 #  pragma GCC diagnostic ignored "-Wconversion"
13718 #  pragma GCC diagnostic ignored "-Wsign-conversion"
13719 # endif
13720 #endif
13722 // Flex 2.6.4, GCC 9
13723 // warning: useless cast to type 'int' [-Wuseless-cast]
13724 // 1361 |   YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
13725 //      |                                                 ^
13726 #if defined GCC_VERSION && 900 <= GCC_VERSION
13727 # pragma GCC diagnostic ignored "-Wuseless-cast"
13728 #endif
13730 @end example
13731 @end ignore
13733 @noindent
13734 Since our calculator has no @code{#include}-like feature, we don't need
13735 @code{yywrap}.  We don't need the @code{unput} and @code{input} functions
13736 either, and we parse an actual file, this is not an interactive session with
13737 the user.  Finally, we enable scanner tracing.
13739 @comment file: c++/calc++/scanner.ll
13740 @example
13741 %option noyywrap nounput noinput batch debug
13742 @end example
13744 @noindent
13745 The following function will be handy to convert a string denoting a number
13746 into a @code{NUMBER} token.
13748 @comment file: c++/calc++/scanner.ll
13749 @example
13751   // A number symbol corresponding to the value in S.
13752   yy::parser::symbol_type
13753   make_NUMBER (const std::string &s, const yy::parser::location_type& loc);
13755 @end example
13757 @noindent
13758 Abbreviations allow for more readable rules.
13760 @comment file: c++/calc++/scanner.ll
13761 @example
13762 id    [a-zA-Z][a-zA-Z_0-9]*
13763 int   [0-9]+
13764 blank [ \t\r]
13765 @end example
13767 @noindent
13768 The following paragraph suffices to track locations accurately.  Each time
13769 @code{yylex} is invoked, the begin position is moved onto the end position.
13770 Then when a pattern is matched, its width is added to the end column.  When
13771 matching ends of lines, the end cursor is adjusted, and each time blanks are
13772 matched, the begin cursor is moved onto the end cursor to effectively ignore
13773 the blanks preceding tokens.  Comments would be treated equally.
13775 @comment file: c++/calc++/scanner.ll
13776 @example
13777 @group
13779   // Code run each time a pattern is matched.
13780   # define YY_USER_ACTION  loc.columns (yyleng);
13782 @end group
13784 @group
13786   // A handy shortcut to the location held by the driver.
13787   yy::location& loc = drv.location;
13788   // Code run each time yylex is called.
13789   loc.step ();
13791 @end group
13792 @{blank@}+   loc.step ();
13793 \n+        loc.lines (yyleng); loc.step ();
13794 @end example
13796 @noindent
13797 The rules are simple.  The driver is used to report errors.
13799 @comment file: c++/calc++/scanner.ll
13800 @example
13801 "-"        return yy::parser::make_MINUS  (loc);
13802 "+"        return yy::parser::make_PLUS   (loc);
13803 "*"        return yy::parser::make_STAR   (loc);
13804 "/"        return yy::parser::make_SLASH  (loc);
13805 "("        return yy::parser::make_LPAREN (loc);
13806 ")"        return yy::parser::make_RPAREN (loc);
13807 ":="       return yy::parser::make_ASSIGN (loc);
13809 @{int@}      return make_NUMBER (yytext, loc);
13810 @{id@}       return yy::parser::make_IDENTIFIER (yytext, loc);
13811 @group
13812 .          @{
13813              throw yy::parser::syntax_error
13814                (loc, "invalid character: " + std::string(yytext));
13816 @end group
13817 <<EOF>>    return yy::parser::make_YYEOF (loc);
13819 @end example
13821 @noindent
13822 You should keep your rules simple, both in the parser and in the scanner.
13823 Throwing from the auxiliary functions is then very handy to report errors.
13825 @comment file: c++/calc++/scanner.ll
13826 @example
13827 @group
13828 yy::parser::symbol_type
13829 make_NUMBER (const std::string &s, const yy::parser::location_type& loc)
13831   errno = 0;
13832   long n = strtol (s.c_str(), NULL, 10);
13833   if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
13834     throw yy::parser::syntax_error (loc, "integer is out of range: " + s);
13835   return yy::parser::make_NUMBER ((int) n, loc);
13837 @end group
13838 @end example
13840 @noindent
13841 Finally, because the scanner-related driver's member-functions depend
13842 on the scanner's data, it is simpler to implement them in this file.
13844 @comment file: c++/calc++/scanner.ll
13845 @example
13846 @group
13847 void
13848 driver::scan_begin ()
13850   yy_flex_debug = trace_scanning;
13851   if (file.empty () || file == "-")
13852     yyin = stdin;
13853   else if (!(yyin = fopen (file.c_str (), "r")))
13854     @{
13855       std::cerr << "cannot open " << file << ": " << strerror (errno) << '\n';
13856       exit (EXIT_FAILURE);
13857     @}
13859 @end group
13861 @group
13862 void
13863 driver::scan_end ()
13865   fclose (yyin);
13867 @end group
13868 @end example
13870 @node Calc++ Top Level
13871 @subsubsection Calc++ Top Level
13873 The top level file, @file{calc++.cc}, poses no problem.
13875 @ignore
13876 @comment file: c++/calc++/calc++.cc
13877 @example
13878 /* Main for calc++.   -*- C++ -*-
13880    Copyright (C) 2005-2015, 2018-2021 Free Software Foundation, Inc.
13882    This file is part of Bison, the GNU Compiler Compiler.
13884    This program is free software: you can redistribute it and/or modify
13885    it under the terms of the GNU General Public License as published by
13886    the Free Software Foundation, either version 3 of the License, or
13887    (at your option) any later version.
13889    This program is distributed in the hope that it will be useful,
13890    but WITHOUT ANY WARRANTY; without even the implied warranty of
13891    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13892    GNU General Public License for more details.
13894    You should have received a copy of the GNU General Public License
13895    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
13896 @end example
13897 @end ignore
13899 @comment file: c++/calc++/calc++.cc
13900 @example
13901 #include <iostream>
13902 #include "driver.hh"
13904 @group
13906 main (int argc, char *argv[])
13908   int res = 0;
13909   driver drv;
13910   for (int i = 1; i < argc; ++i)
13911     if (argv[i] == std::string ("-p"))
13912       drv.trace_parsing = true;
13913     else if (argv[i] == std::string ("-s"))
13914       drv.trace_scanning = true;
13915     else if (!drv.parse (argv[i]))
13916       std::cout << drv.result << '\n';
13917     else
13918       res = 1;
13919   return res;
13921 @end group
13922 @end example
13924 @node D Parsers
13925 @section D Parsers
13927 @menu
13928 * D Bison Interface::        Asking for D parser generation
13929 * D Semantic Values::        %token and %nterm vs. D
13930 * D Location Values::        The position and location classes
13931 * D Parser Interface::       Instantiating and running the parser
13932 * D Parser Context Interface:: Circumstances of a syntax error
13933 * D Scanner Interface::      Specifying the scanner for the parser
13934 * D Action Features::        Special features for use in actions
13935 * D Push Parser Interface::  Instantiating and running the push parser
13936 * D Complete Symbols::       Using token constructors
13937 @end menu
13939 @node D Bison Interface
13940 @subsection D Bison Interface
13941 @c - %language "D"
13943 The D parser skeletons are selected using the @code{%language "D"}
13944 directive or the @option{-L D}/@option{--language=D} option.
13946 @c FIXME: Documented bug.
13947 When generating a D parser, @samp{bison @var{basename}.y} will create a
13948 single D source file named @file{@var{basename}.d} containing the
13949 parser implementation.  Using a grammar file without a @file{.y} suffix is
13950 currently broken.  The basename of the parser implementation file can be
13951 changed by the @code{%file-prefix} directive or the
13952 @option{-b}/@option{--file-prefix} option.  The entire parser implementation
13953 file name can be changed by the @code{%output} directive or the
13954 @option{-o}/@option{--output} option.  The parser implementation file
13955 contains a single class for the parser.
13957 You can create documentation for generated parsers using Ddoc.
13959 GLR parsers are currently unsupported in D.  Do not use the
13960 @code{glr-parser} directive.
13962 No header file can be generated for D parsers.  Do not use the
13963 @code{%header} directive or the @option{-d}/@option{--header} options.
13965 @node D Semantic Values
13966 @subsection D Semantic Values
13968 Semantic types are handled by @code{%union} and @samp{%define api.value.type
13969 union}, similar to C/C++ parsers. In the latter case, the union of the
13970 values is handled by the backend. In D, unions can hold classes, structs,
13971 etc., so this directive is more similar to @samp{%define api.value.type
13972 variant} from C++.
13974 D parsers do not support @code{%destructor}, since the language
13975 adopts garbage collection.  The parser will try to hold references
13976 to semantic values for as little time as needed.
13978 D parsers support @code{%printer}.  An example for the output of type
13979 @code{int}, where @code{yyo} is the parser's debug output:
13981 @example
13982 %printer @{ yyo.write($$); @} <int>
13983 @end example
13986 @node D Location Values
13987 @subsection D Location Values
13988 @c - %locations
13989 @c - class Position
13990 @c - class Location
13992 When the directive @code{%locations} is used, the D parser supports location
13993 tracking, see @ref{Tracking Locations}.  The position and the location
13994 structures are provided.
13996 @deftypeivar {Location} {Position} begin
13997 @deftypeivarx {Location} {Position} end
13998 The first, inclusive, position of the range, and the first beyond.
13999 @end deftypeivar
14001 @deftypeop {Constructor} {Location} {} this(@code{Position} @var{loc})
14002 Create a @code{Location} denoting an empty range located at a given point.
14003 @end deftypeop
14005 @deftypeop {Constructor} {Location} {} this(@code{Position} @var{begin}, @code{Position} @var{end})
14006 Create a @code{Location} from the endpoints of the range.
14007 @end deftypeop
14009 @deftypemethod {Location} {string} toString()
14010 The range represented by the location as a string.
14011 @end deftypemethod
14014 @node D Parser Interface
14015 @subsection D Parser Interface
14017 The name of the generated parser class defaults to @code{YYParser}.  The
14018 @code{YY} prefix may be changed using the @samp{%define api.prefix}.
14019 Alternatively, use @samp{%define api.parser.class @{@var{name}@}} to give a
14020 custom name to the class.  The interface of this class is detailed below.
14022 By default, the parser class has public visibility.  To add modifiers to the
14023 parser class, @code{%define} @code{api.parser.public},
14024 @code{api.parser.abstract} and/or @code{api.parser.final}.
14026 The superclass and the implemented interfaces of the parser class can be
14027 specified with the @samp{%define api.parser.extends} and @samp{%define
14028 api.parser.implements} directives.
14030 The parser class defines an interface, @code{Lexer} (@pxref{D Scanner
14031 Interface}).  Other than this interface and the members described in the
14032 interface below, all the other members and fields are preceded with a
14033 @code{yy} or @code{YY} prefix to avoid clashes with user code.
14035 The parser class can be extended using the @code{%parse-param}
14036 directive. Each occurrence of the directive will add a by default public
14037 field to the parser class, and an argument to its constructor, which
14038 initializes them automatically.
14040 @deftypeop {Constructor} {YYParser} {} this(@var{lex_param}, @dots{}, @var{parse_param}, @dots{})
14041 Build a new parser object with embedded @samp{%code lexer}.  There are no
14042 parameters, unless @code{%param}s and/or @code{%parse-param}s and/or
14043 @code{%lex-param}s are used.
14044 @end deftypeop
14046 @deftypeop {Constructor} {YYParser} {} this(@code{Lexer} @var{lexer}, @var{parse_param}, @dots{})
14047 Build a new parser object using the specified scanner.  There are no
14048 additional parameters unless @code{%param}s and/or @code{%parse-param}s are
14049 used.
14050 @end deftypeop
14052 @deftypemethod {YYParser} {boolean} parse()
14053 Run the syntactic analysis, and return @code{true} on success,
14054 @code{false} otherwise.
14055 @end deftypemethod
14057 @deftypemethod {YYParser} {boolean} getErrorVerbose()
14058 @deftypemethodx {YYParser} {void} setErrorVerbose(boolean @var{verbose})
14059 Get or set the option to produce verbose error messages.  These are only
14060 available with @samp{%define parse.error detailed},
14061 which also turns on verbose error messages.
14062 @end deftypemethod
14064 @deftypemethod {YYParser} {void} yyerror(@code{string} @var{msg})
14065 @deftypemethodx {YYParser} {void} yyerror(@code{Location} @var{loc}, @code{string} @var{msg})
14066 Print an error message using the @code{yyerror} method of the scanner
14067 instance in use. The @code{Location} and @code{Position} parameters are
14068 available only if location tracking is active.
14069 @end deftypemethod
14071 @deftypemethod {YYParser} {boolean} recovering()
14072 During the syntactic analysis, return @code{true} if recovering
14073 from a syntax error.
14074 @xref{Error Recovery}.
14075 @end deftypemethod
14077 @deftypemethod {YYParser} {File} getDebugStream()
14078 @deftypemethodx {YYParser} {void} setDebugStream(@code{File} @var{o})
14079 Get or set the stream used for tracing the parsing.  It defaults to
14080 @code{stderr}.
14081 @end deftypemethod
14083 @deftypemethod {YYParser} {int} getDebugLevel()
14084 @deftypemethodx {YYParser} {void} setDebugLevel(@code{int} @var{l})
14085 Get or set the tracing level.  Currently its value is either 0, no trace,
14086 or nonzero, full tracing.
14087 @end deftypemethod
14089 @deftypecv {Constant} {YYParser} {string} {bisonVersion}
14090 @deftypecvx {Constant} {YYParser} {string} {bisonSkeleton}
14091 Identify the Bison version and skeleton used to generate this parser.
14092 @end deftypecv
14094 The internationalization in D is very similar to the one in C. The D
14095 parser uses @code{dgettext} for translating Bison messages.
14097 To enable internationalization, compile using @samp{-version ENABLE_NLS
14098 -version YYENABLE_NLS} and import @code{bindtextdomain} and
14099 @code{textdomain} from C:
14101 @example
14102 extern(C) char* bindtextdomain(const char* domainname, const char* dirname);
14103 extern(C) char* textdomain(const char* domainname);
14104 @end example
14106 The main function should load the translation catalogs, similarly to the
14107 @file{c/bistromathic} example:
14109 @example
14110 int main()
14112   import core.stdc.locale;
14114   // Set up internationalization.
14115   setlocale(LC_ALL, "");
14116   // Use Bison's standard translation catalog for error messages
14117   // (the generated messages).
14118   bindtextdomain("bison-runtime", BISON_LOCALEDIR);
14119   // For the translation catalog of your own project, use the
14120   // name of your project.
14121   bindtextdomain("bison", LOCALEDIR);
14122   textdomain("bison");
14124   // usual main content
14125   ...
14127 @end example
14129 For user message translations, the user must implement the @samp{string
14130 _(const char* @var{msg})} function.  It is recommended to use
14131 @code{gettext}:
14133 @example
14134 %code imports @{
14135   static if (!is(typeof(_)))
14136   @{
14137     version(ENABLE_NLS)
14138     @{
14139       extern(C) char* gettext(const char*);
14140       string _(const char* s)
14141       @{
14142         return to!string(gettext(s));
14143       @}
14144     @}
14145   @}
14146   static if (!is(typeof(_)))
14147   @{
14148     pragma(inline, true)
14149     string _(string msg) @{ return msg; @}
14150   @}
14152 @end example
14154 @node D Parser Context Interface
14155 @subsection D Parser Context Interface
14156 The parser context provides information to build error reports when you
14157 invoke @samp{%define parse.error custom}.
14159 @defcv {Type} {YYParser} {SymbolKind}
14160 A struct containing an enum of all the grammar symbols, tokens and
14161 nonterminals.  Its enumerators are forged from the symbol names.  Use
14162 @samp{void toString(W)(W sink)} to get the symbol names.
14163 @end defcv
14165 @deftypemethod {YYParser.Context} {YYParser.SymbolKind} getToken()
14166 The kind of the lookahead.  Return @code{null} iff there is no lookahead.
14167 @end deftypemethod
14169 @deftypemethod {YYParser.Context} {YYParser.Location} getLocation()
14170 The location of the lookahead.
14171 @end deftypemethod
14173 @deftypemethod {YYParser.Context} {int} getExpectedTokens(@code{YYParser.SymbolKind[]} @var{argv}, @code{int} @var{argc})
14174 Fill @var{argv} with the expected tokens, which never includes
14175 @code{SymbolKind.YYERROR}, or @code{SymbolKind.YYUNDEF}.
14177 Never put more than @var{argc} elements into @var{argv}, and on success
14178 return the number of tokens stored in @var{argv}.  If there are more
14179 expected tokens than @var{argc}, fill @var{argv} up to @var{argc} and return
14180 0.  If there are no expected tokens, also return 0, but set @code{argv[0]}
14181 to @code{null}.
14183 If @var{argv} is null, return the size needed to store all the possible
14184 values, which is always less than @code{YYNTOKENS}.
14185 @end deftypemethod
14188 @node D Scanner Interface
14189 @subsection D Scanner Interface
14190 @c - %code lexer
14191 @c - %lex-param
14192 @c - Lexer interface
14194 There are two possible ways to interface a Bison-generated D parser
14195 with a scanner: the scanner may be defined by @code{%code lexer}, or
14196 defined elsewhere.  In either case, the scanner has to implement the
14197 @code{Lexer} inner interface of the parser class.  This interface also
14198 contains constants for all user-defined token names and the predefined
14199 @code{YYEOF} token.
14201 In the first case, the body of the scanner class is placed in
14202 @code{%code lexer} blocks.  If you want to pass parameters from the
14203 parser constructor to the scanner constructor, specify them with
14204 @code{%lex-param}; they are passed before @code{%parse-param}s to the
14205 constructor.
14207 In the second case, the scanner has to implement the @code{Lexer} interface,
14208 which is defined within the parser class (e.g., @code{YYParser.Lexer}).
14209 The constructor of the parser object will then accept an object
14210 implementing the interface; @code{%lex-param} is not used in this
14211 case.
14213 In both cases, the scanner has to implement the following methods.
14215 @deftypemethod {Lexer} {void} yyerror(@code{Location} @var{loc}, @code{string} @var{msg})
14216 This method is defined by the user to emit an error message.  The first
14217 parameter is omitted if location tracking is not active.
14218 @end deftypemethod
14220 @deftypemethod {Lexer} {Symbol} yylex()
14221 Return the next token. The return value is of type @code{Symbol}, which
14222 binds together the kind, the semantic value and the location.
14223 @end deftypemethod
14225 @deftypemethod {Lexer} {void} reportSyntaxError(@code{YYParser.Context} @var{ctx})
14226 If you invoke @samp{%define parse.error custom} (@pxref{Bison
14227 Declarations}), then the parser no longer passes syntax error messages to
14228 @code{yyerror}, rather it delegates that task to the user by calling the
14229 @code{reportSyntaxError} function.
14231 Whether it uses @code{yyerror} is up to the user.
14233 Here is an example of a reporting function (@pxref{D Parser Context
14234 Interface}).
14236 @example
14237 public void reportSyntaxError(YYParser.Context ctx)
14239   stderr.write(ctx.getLocation(), ": syntax error");
14240   // Report the expected tokens.
14241   @{
14242     immutable int TOKENMAX = 5;
14243     YYParser.SymbolKind[] arg = new YYParser.SymbolKind[TOKENMAX];
14244     int n = ctx.getExpectedTokens(arg, TOKENMAX);
14245     if (n < TOKENMAX)
14246       for (int i = 0; i < n; ++i)
14247         stderr.write((i == 0 ? ": expected " : " or "), arg[i]);
14248   @}
14249   // Report the unexpected token which triggered the error.
14250   @{
14251     YYParser.SymbolKind lookahead = ctx.getToken();
14252     stderr.writeln(" before ", lookahead);
14253   @}
14255 @end example
14257 @noindent
14258 This implementation is inappropriate for internationalization, see
14259 the @file{c/bistromathic} example for a better alternative.
14260 @end deftypemethod
14262 @node D Action Features
14263 @subsection Special Features for Use in D Actions
14265 Here is a table of Bison constructs, variables and functions that are useful in
14266 actions.
14268 @deffn {Variable} $$
14269 Acts like a variable that contains the semantic value for the
14270 grouping made by the current rule.  @xref{Actions}.
14271 @end deffn
14273 @deffn {Variable} $@var{n}
14274 Acts like a variable that contains the semantic value for the
14275 @var{n}th component of the current rule.  @xref{Actions}.
14276 @end deffn
14278 @deffn {Function} yyerrok
14279 Resume generating error messages immediately for subsequent syntax
14280 errors.  This is useful primarily in error rules.
14281 @xref{Error Recovery}.
14282 @end deffn
14284 @node D Push Parser Interface
14285 @subsection D Push Parser Interface
14286 @c - define push_parse
14287 @findex %define api.push-pull
14289 Normally, Bison generates a pull parser for D.
14290 The following Bison declaration says that you want the parser to be a push
14291 parser (@pxref{%define Summary}):
14293 @example
14294 %define api.push-pull push
14295 @end example
14297 Most of the discussion about the D pull Parser Interface, (@pxref{D
14298 Parser Interface}) applies to the push parser interface as well.
14300 When generating a push parser, the method @code{pushParse} is created with
14301 the following signature:
14303 @deftypemethod {YYParser} {int} pushParse (@code{Symbol} @var{sym})
14304 @end deftypemethod
14306 The primary difference with respect to a pull parser is that the parser
14307 method @code{pushParse} is invoked repeatedly to parse each token.  This
14308 function is available if either the @samp{%define api.push-pull push} or
14309 @samp{%define api.push-pull both} declaration is used (@pxref{%define
14310 Summary}).
14312 The value returned by the @code{pushParse} method is one of the following:
14313 @code{ACCEPT}, @code{ABORT}, or @code{PUSH_MORE}.  This new value,
14314 @code{PUSH_MORE}, may be returned if more input is required to finish
14315 parsing the input.
14317 If @code{api.push-pull} is defined as @code{both}, then the generated parser
14318 class will also implement the @code{parse} method. This method's body is a
14319 loop that repeatedly invokes the scanner and then passes the values obtained
14320 from the scanner to the @code{pushParse} method.
14322 @node D Complete Symbols
14323 @subsection D Complete Symbols
14325 To build return values for @code{yylex}, call the @code{Symbol} method of
14326 the same name as the token kind reported, and adding the parameters for
14327 value and location if necessary.  These methods generate compile-time errors
14328 if the parameters are inconsistent.  Token constructors work with both
14329 @code{%union} and @samp{%define api.value.type union}.
14331 The order of the parameters is the same as for the @code{Symbol}
14332 constructor.  An example for the token kind @code{NUM}, which has value
14333 @code{ival} and with location tracking activated:
14335 @example
14336 Symbol.NUM(ival, location);
14337 @end example
14339 @node Java Parsers
14340 @section Java Parsers
14342 @menu
14343 * Java Bison Interface::        Asking for Java parser generation
14344 * Java Semantic Values::        %token and %nterm vs. Java
14345 * Java Location Values::        The position and location classes
14346 * Java Parser Interface::       Instantiating and running the parser
14347 * Java Parser Context Interface:: Circumstances of a syntax error
14348 * Java Scanner Interface::      Specifying the scanner for the parser
14349 * Java Action Features::        Special features for use in actions
14350 * Java Push Parser Interface::  Instantiating and running the push parser
14351 * Java Differences::            Differences between C/C++ and Java Grammars
14352 * Java Declarations Summary::   List of Bison declarations used with Java
14353 @end menu
14355 @node Java Bison Interface
14356 @subsection Java Bison Interface
14357 @c - %language "Java"
14359 The Java parser skeletons are selected using the @code{%language "Java"}
14360 directive or the @option{-L java}/@option{--language=java} option.
14362 @c FIXME: Documented bug.
14363 When generating a Java parser, @samp{bison @var{basename}.y} will create a
14364 single Java source file named @file{@var{basename}.java} containing the
14365 parser implementation.  Using a grammar file without a @file{.y} suffix is
14366 currently broken.  The basename of the parser implementation file can be
14367 changed by the @code{%file-prefix} directive or the
14368 @option{-b}/@option{--file-prefix} option.  The entire parser implementation
14369 file name can be changed by the @code{%output} directive or the
14370 @option{-o}/@option{--output} option.  The parser implementation file
14371 contains a single class for the parser.
14373 You can create documentation for generated parsers using Javadoc.
14375 Contrary to C parsers, Java parsers do not use global variables; the state
14376 of the parser is always local to an instance of the parser class.
14377 Therefore, all Java parsers are ``pure'', and the @code{%define api.pure}
14378 directive does nothing when used in Java.
14380 GLR parsers are currently unsupported in Java.  Do not use the
14381 @code{glr-parser} directive.
14383 No header file can be generated for Java parsers.  Do not use the
14384 @code{%header} directive or the @option{-d}/@option{-H}/@option{--header}
14385 options.
14387 @c FIXME: Possible code change.
14388 Currently, support for tracing is always compiled in.  Thus the
14389 @samp{%define parse.trace} and @samp{%token-table} directives and the
14390 @option{-t}/@option{--debug} and @option{-k}/@option{--token-table} options
14391 have no effect.  This may change in the future to eliminate unused code in
14392 the generated parser, so use @samp{%define parse.trace} explicitly if
14393 needed.  Also, in the future the @code{%token-table} directive might enable
14394 a public interface to access the token names and codes.
14396 Getting a ``code too large'' error from the Java compiler means the code hit
14397 the 64KB bytecode per method limitation of the Java class file.  Try
14398 reducing the amount of code in actions and static initializers; otherwise,
14399 report a bug so that the parser skeleton will be improved.
14402 @node Java Semantic Values
14403 @subsection Java Semantic Values
14405 There is no @code{%union} directive in Java parsers.  Instead, the semantic
14406 values' types (class names) should be specified in the @code{%nterm} or
14407 @code{%token} directive:
14409 @example
14410 %nterm <Expression> expr assignment_expr term factor
14411 %nterm <Integer> number
14412 @end example
14414 By default, the semantic stack is declared to have @code{Object} members,
14415 which means that the class types you specify can be of any class.
14416 To improve the type safety of the parser, you can declare the common
14417 superclass of all the semantic values using the @samp{%define api.value.type}
14418 directive.  For example, after the following declaration:
14420 @example
14421 %define api.value.type @{ASTNode@}
14422 @end example
14424 @noindent
14425 any @code{%token}, @code{%nterm} or @code{%type} specifying a semantic type
14426 which is not a subclass of @code{ASTNode}, will cause a compile-time error.
14428 @c FIXME: Documented bug.
14429 Types used in the directives may be qualified with a package name.
14430 Primitive data types are accepted for Java version 1.5 or later.  Note
14431 that in this case the autoboxing feature of Java 1.5 will be used.
14432 Generic types may not be used; this is due to a limitation in the
14433 implementation of Bison, and may change in future releases.
14435 Java parsers do not support @code{%destructor}, since the language
14436 adopts garbage collection.  The parser will try to hold references
14437 to semantic values for as little time as needed.
14439 Java parsers do not support @code{%printer}, as @code{toString()}
14440 can be used to print the semantic values.  This however may change
14441 (in a backwards-compatible way) in future versions of Bison.
14444 @node Java Location Values
14445 @subsection Java Location Values
14446 @c - %locations
14447 @c - class Position
14448 @c - class Location
14450 When the directive @code{%locations} is used, the Java parser supports
14451 location tracking, see @ref{Tracking Locations}.  An auxiliary user-defined
14452 class defines a @dfn{position}, a single point in a file; Bison itself
14453 defines a class representing a @dfn{location}, a range composed of a pair of
14454 positions (possibly spanning several files).  The location class is an inner
14455 class of the parser; the name is @code{Location} by default, and may also be
14456 renamed using @code{%define api.location.type @{@var{class-name}@}}.
14458 The location class treats the position as a completely opaque value.
14459 By default, the class name is @code{Position}, but this can be changed
14460 with @code{%define api.position.type @{@var{class-name}@}}.  This class must
14461 be supplied by the user.
14464 @deftypeivar {Location} {Position} begin
14465 @deftypeivarx {Location} {Position} end
14466 The first, inclusive, position of the range, and the first beyond.
14467 @end deftypeivar
14469 @deftypeop {Constructor} {Location} {} Location (@code{Position} @var{loc})
14470 Create a @code{Location} denoting an empty range located at a given point.
14471 @end deftypeop
14473 @deftypeop {Constructor} {Location} {} Location (@code{Position} @var{begin}, @code{Position} @var{end})
14474 Create a @code{Location} from the endpoints of the range.
14475 @end deftypeop
14477 @deftypemethod {Location} {String} toString ()
14478 Prints the range represented by the location.  For this to work
14479 properly, the position class should override the @code{equals} and
14480 @code{toString} methods appropriately.
14481 @end deftypemethod
14484 @node Java Parser Interface
14485 @subsection Java Parser Interface
14487 The name of the generated parser class defaults to @code{YYParser}.  The
14488 @code{YY} prefix may be changed using the @samp{%define api.prefix}.
14489 Alternatively, use @samp{%define api.parser.class @{@var{name}@}} to give a
14490 custom name to the class.  The interface of this class is detailed below.
14492 By default, the parser class has package visibility.  A declaration
14493 @samp{%define api.parser.public} will change to public visibility.  Remember
14494 that, according to the Java language specification, the name of the
14495 @file{.java} file should match the name of the class in this case.
14496 Similarly, you can use @code{api.parser.abstract}, @code{api.parser.final}
14497 and @code{api.parser.strictfp} with the @code{%define} declaration to add
14498 other modifiers to the parser class.  A single @samp{%define
14499 api.parser.annotations @{@var{annotations}@}} directive can be used to add
14500 any number of annotations to the parser class.
14502 The Java package name of the parser class can be specified using the
14503 @samp{%define package} directive.  The superclass and the implemented
14504 interfaces of the parser class can be specified with the @code{%define
14505 api.parser.extends} and @samp{%define api.parser.implements} directives.
14507 The parser class defines an inner class, @code{Location}, that is used
14508 for location tracking (see @ref{Java Location Values}), and a inner
14509 interface, @code{Lexer} (see @ref{Java Scanner Interface}).  Other than
14510 these inner class/interface, and the members described in the interface
14511 below, all the other members and fields are preceded with a @code{yy} or
14512 @code{YY} prefix to avoid clashes with user code.
14514 The parser class can be extended using the @code{%parse-param}
14515 directive. Each occurrence of the directive will add a @code{protected
14516 final} field to the parser class, and an argument to its constructor,
14517 which initializes them automatically.
14519 @deftypeop {Constructor} {YYParser} {} YYParser (@var{lex_param}, @dots{}, @var{parse_param}, @dots{})
14520 Build a new parser object with embedded @code{%code lexer}.  There are
14521 no parameters, unless @code{%param}s and/or @code{%parse-param}s and/or
14522 @code{%lex-param}s are used.
14524 Use @code{%code init} for code added to the start of the constructor
14525 body. This is especially useful to initialize superclasses. Use
14526 @samp{%define init_throws} to specify any uncaught exceptions.
14527 @end deftypeop
14529 @deftypeop {Constructor} {YYParser} {} YYParser (@code{Lexer} @var{lexer}, @var{parse_param}, @dots{})
14530 Build a new parser object using the specified scanner.  There are no
14531 additional parameters unless @code{%param}s and/or @code{%parse-param}s are
14532 used.
14534 If the scanner is defined by @code{%code lexer}, this constructor is
14535 declared @code{protected} and is called automatically with a scanner
14536 created with the correct @code{%param}s and/or @code{%lex-param}s.
14538 Use @code{%code init} for code added to the start of the constructor
14539 body. This is especially useful to initialize superclasses. Use
14540 @samp{%define init_throws} to specify any uncaught exceptions.
14541 @end deftypeop
14543 @deftypemethod {YYParser} {boolean} parse ()
14544 Run the syntactic analysis, and return @code{true} on success,
14545 @code{false} otherwise.
14546 @end deftypemethod
14548 @deftypemethod {YYParser} {boolean} getErrorVerbose ()
14549 @deftypemethodx {YYParser} {void} setErrorVerbose (boolean @var{verbose})
14550 Get or set the option to produce verbose error messages.  These are only
14551 available with @samp{%define parse.error detailed} (or @samp{verbose}),
14552 which also turns on verbose error messages.
14553 @end deftypemethod
14555 @deftypemethod {YYParser} {void} yyerror (@code{String} @var{msg})
14556 @deftypemethodx {YYParser} {void} yyerror (@code{Position} @var{pos}, @code{String} @var{msg})
14557 @deftypemethodx {YYParser} {void} yyerror (@code{Location} @var{loc}, @code{String} @var{msg})
14558 Print an error message using the @code{yyerror} method of the scanner
14559 instance in use. The @code{Location} and @code{Position} parameters are
14560 available only if location tracking is active.
14561 @end deftypemethod
14563 @deftypemethod {YYParser} {boolean} recovering ()
14564 During the syntactic analysis, return @code{true} if recovering
14565 from a syntax error.
14566 @xref{Error Recovery}.
14567 @end deftypemethod
14569 @deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
14570 @deftypemethodx {YYParser} {void} setDebugStream (@code{java.io.PrintStream} @var{o})
14571 Get or set the stream used for tracing the parsing.  It defaults to
14572 @code{System.err}.
14573 @end deftypemethod
14575 @deftypemethod {YYParser} {int} getDebugLevel ()
14576 @deftypemethodx {YYParser} {void} setDebugLevel (@code{int} @var{l})
14577 Get or set the tracing level.  Currently its value is either 0, no trace,
14578 or nonzero, full tracing.
14579 @end deftypemethod
14581 @deftypecv {Constant} {YYParser} {String} {bisonVersion}
14582 @deftypecvx {Constant} {YYParser} {String} {bisonSkeleton}
14583 Identify the Bison version and skeleton used to generate this parser.
14584 @end deftypecv
14586 If you enabled token internationalization (@pxref{Token I18n}), you must
14587 provide the parser with the following function:
14589 @deftypecv {Static Method} {YYParser} {String} {i18n} (@code{string} @var{s})
14590 Return the translation of @var{s} in the user's language.  As an example:
14592 @example
14593 %code @{
14594   static ResourceBundle myResources
14595     = ResourceBundle.getBundle("domain-name");
14596   static final String i18n(String s) @{
14597     return myResources.getString(s);
14598   @}
14600 @end example
14601 @end deftypecv
14603 @node Java Parser Context Interface
14604 @subsection Java Parser Context Interface
14606 The parser context provides information to build error reports when you
14607 invoke @samp{%define parse.error custom}.
14609 @defcv {Type} {YYParser} {SymbolKind}
14610 An enum of all the grammar symbols, tokens and nonterminals.  Its
14611 enumerators are forged from the symbol names:
14613 @example
14614 public enum SymbolKind
14616   S_YYEOF(0),          /* "end of file"  */
14617   S_YYERROR(1),        /* error  */
14618   S_YYUNDEF(2),        /* "invalid token"  */
14619   S_BANG(3),           /* "!"  */
14620   S_PLUS(4),           /* "+"  */
14621   S_MINUS(5),          /* "-"  */
14622   [...]
14623   S_NUM(13),           /* "number"  */
14624   S_NEG(14),           /* NEG  */
14625   S_YYACCEPT(15),      /* $accept  */
14626   S_input(16),         /* input  */
14627   S_line(17);          /* line  */
14629 @end example
14630 @end defcv
14632 @deftypemethod {YYParser.SymbolKind} {String} getName ()
14633 The name of this symbol, possibly translated.
14634 @end deftypemethod
14636 @deftypemethod {YYParser.Context} {YYParser.SymbolKind} getToken ()
14637 The kind of the lookahead.  Return @code{null} iff there is no lookahead.
14638 @end deftypemethod
14640 @deftypemethod {YYParser.Context} {YYParser.Location} getLocation ()
14641 The location of the lookahead.
14642 @end deftypemethod
14644 @deftypemethod {YYParser.Context} {int} getExpectedTokens (@code{YYParser.SymbolKind[]} @var{argv}, @code{int} @var{argc})
14645 Fill @var{argv} with the expected tokens, which never includes
14646 @code{SymbolKind.S_YYERROR}, or @code{SymbolKind.S_YYUNDEF}.
14648 Never put more than @var{argc} elements into @var{argv}, and on success
14649 return the number of tokens stored in @var{argv}.  If there are more
14650 expected tokens than @var{argc}, fill @var{argv} up to @var{argc} and return
14651 0.  If there are no expected tokens, also return 0, but set @code{argv[0]}
14652 to @code{null}.
14654 If @var{argv} is null, return the size needed to store all the possible
14655 values, which is always less than @code{YYNTOKENS}.
14656 @end deftypemethod
14659 @node Java Scanner Interface
14660 @subsection Java Scanner Interface
14661 @c - %code lexer
14662 @c - %lex-param
14663 @c - Lexer interface
14665 There are two possible ways to interface a Bison-generated Java parser
14666 with a scanner: the scanner may be defined by @code{%code lexer}, or
14667 defined elsewhere.  In either case, the scanner has to implement the
14668 @code{Lexer} inner interface of the parser class.  This interface also
14669 contains constants for all user-defined token names and the predefined
14670 @code{YYEOF} token.
14672 In the first case, the body of the scanner class is placed in
14673 @code{%code lexer} blocks.  If you want to pass parameters from the
14674 parser constructor to the scanner constructor, specify them with
14675 @code{%lex-param}; they are passed before @code{%parse-param}s to the
14676 constructor.
14678 In the second case, the scanner has to implement the @code{Lexer} interface,
14679 which is defined within the parser class (e.g., @code{YYParser.Lexer}).
14680 The constructor of the parser object will then accept an object
14681 implementing the interface; @code{%lex-param} is not used in this
14682 case.
14684 In both cases, the scanner has to implement the following methods.
14686 @deftypemethod {Lexer} {void} yyerror (@code{Location} @var{loc}, @code{String} @var{msg})
14687 This method is defined by the user to emit an error message.  The first
14688 parameter is omitted if location tracking is not active.  Its type can be
14689 changed using @code{%define api.location.type @{@var{class-name}@}}.
14690 @end deftypemethod
14692 @deftypemethod {Lexer} {int} yylex ()
14693 Return the next token.  Its type is the return value, its semantic value and
14694 location are saved and returned by the their methods in the interface.  Not
14695 needed for push-only parsers.
14697 Use @samp{%define lex_throws} to specify any uncaught exceptions.
14698 Default is @code{java.io.IOException}.
14699 @end deftypemethod
14701 @deftypemethod {Lexer} {Position} getStartPos ()
14702 @deftypemethodx {Lexer} {Position} getEndPos ()
14703 Return respectively the first position of the last token that @code{yylex}
14704 returned, and the first position beyond it.  These methods are not needed
14705 unless location tracking and pull parsing are active.
14707 They should return new objects for each call, to avoid that all the symbol
14708 share the same Position boundaries.
14710 The return type can be changed using @code{%define api.position.type
14711 @{@var{class-name}@}}.
14712 @end deftypemethod
14714 @deftypemethod {Lexer} {Object} getLVal ()
14715 Return the semantic value of the last token that yylex returned.  Not needed
14716 for push-only parsers.
14718 The return type can be changed using @samp{%define api.value.type
14719 @{@var{class-name}@}}.
14720 @end deftypemethod
14722 @deftypemethod {Lexer} {void} reportSyntaxError (@code{YYParser.Context} @var{ctx})
14723 If you invoke @samp{%define parse.error custom} (@pxref{Bison
14724 Declarations}), then the parser no longer passes syntax error messages to
14725 @code{yyerror}, rather it delegates that task to the user by calling the
14726 @code{reportSyntaxError} function.
14728 Whether it uses @code{yyerror} is up to the user.
14730 Here is an example of a reporting function (@pxref{Java Parser Context
14731 Interface}).
14733 @example
14734 public void reportSyntaxError(YYParser.Context ctx) @{
14735   System.err.print(ctx.getLocation() + ": syntax error");
14736   // Report the expected tokens.
14737   @{
14738     final int TOKENMAX = 5;
14739     YYParser.SymbolKind[] arg = new YYParser.SymbolKind[TOKENMAX];
14740     int n = ctx.getExpectedTokens(arg, TOKENMAX);
14741     for (int i = 0; i < n; ++i)
14742       System.err.print((i == 0 ? ": expected " : " or ")
14743                        + arg[i].getName());
14744   @}
14745   // Report the unexpected token which triggered the error.
14746   @{
14747     YYParser.SymbolKind lookahead = ctx.getToken();
14748     if (lookahead != null)
14749       System.err.print(" before " + lookahead.getName());
14750   @}
14751   System.err.println("");
14753 @end example
14755 @noindent
14756 This implementation is inappropriate for internationalization, see the
14757 @file{c/bistromathic} example for a better alternative.
14758 @end deftypemethod
14760 @node Java Action Features
14761 @subsection Special Features for Use in Java Actions
14763 The following special constructs can be uses in Java actions.
14764 Other analogous C action features are currently unavailable for Java.
14766 Use @samp{%define throws} to specify any uncaught exceptions from parser
14767 actions, and initial actions specified by @code{%initial-action}.
14769 @defvar $@var{n}
14770 The semantic value for the @var{n}th component of the current rule.
14771 This may not be assigned to.
14772 @xref{Java Semantic Values}.
14773 @end defvar
14775 @defvar $<@var{typealt}>@var{n}
14776 Like @code{$@var{n}} but specifies a alternative type @var{typealt}.
14777 @xref{Java Semantic Values}.
14778 @end defvar
14780 @defvar $$
14781 The semantic value for the grouping made by the current rule.  As a
14782 value, this is in the base type (@code{Object} or as specified by
14783 @samp{%define api.value.type}) as in not cast to the declared subtype because
14784 casts are not allowed on the left-hand side of Java assignments.
14785 Use an explicit Java cast if the correct subtype is needed.
14786 @xref{Java Semantic Values}.
14787 @end defvar
14789 @defvar $<@var{typealt}>$
14790 Same as @code{$$} since Java always allow assigning to the base type.
14791 Perhaps we should use this and @code{$<>$} for the value and @code{$$}
14792 for setting the value but there is currently no easy way to distinguish
14793 these constructs.
14794 @xref{Java Semantic Values}.
14795 @end defvar
14797 @defvar @@@var{n}
14798 The location information of the @var{n}th component of the current rule.
14799 This may not be assigned to.
14800 @xref{Java Location Values}.
14801 @end defvar
14803 @defvar @@$
14804 The location information of the grouping made by the current rule.
14805 @xref{Java Location Values}.
14806 @end defvar
14808 @deftypefn {Statement} return YYABORT @code{;}
14809 Return immediately from the parser, indicating failure.
14810 @xref{Java Parser Interface}.
14811 @end deftypefn
14813 @deftypefn {Statement} return YYACCEPT @code{;}
14814 Return immediately from the parser, indicating success.
14815 @xref{Java Parser Interface}.
14816 @end deftypefn
14818 @deftypefn {Statement} {return} YYERROR @code{;}
14819 Start error recovery (without printing an error message).
14820 @xref{Error Recovery}.
14821 @end deftypefn
14823 @deftypefn {Function} {boolean} recovering ()
14824 Return whether error recovery is being done. In this state, the parser
14825 reads token until it reaches a known state, and then restarts normal
14826 operation.
14827 @xref{Error Recovery}.
14828 @end deftypefn
14830 @deftypefn  {Function} {void} yyerror (@code{String} @var{msg})
14831 @deftypefnx {Function} {void} yyerror (@code{Position} @var{loc}, @code{String} @var{msg})
14832 @deftypefnx {Function} {void} yyerror (@code{Location} @var{loc}, @code{String} @var{msg})
14833 Print an error message using the @code{yyerror} method of the scanner
14834 instance in use. The @code{Location} and @code{Position} parameters are
14835 available only if location tracking is active.
14836 @end deftypefn
14838 @node Java Push Parser Interface
14839 @subsection Java Push Parser Interface
14840 @c - define push_parse
14841 @findex %define api.push-pull
14843 Normally, Bison generates a pull parser for Java.
14844 The following Bison declaration says that you want the parser to be a push
14845 parser (@pxref{%define Summary}):
14847 @example
14848 %define api.push-pull push
14849 @end example
14851 Most of the discussion about the Java pull Parser Interface, (@pxref{Java
14852 Parser Interface}) applies to the push parser interface as well.
14854 When generating a push parser, the method @code{push_parse} is created with
14855 the following signature (depending on if locations are enabled).
14857 @deftypemethod {YYParser} {void} push_parse (@code{int} @var{token}, @code{Object} @var{yylval})
14858 @deftypemethodx {YYParser} {void} push_parse (@code{int} @var{token}, @code{Object} @var{yylval}, @code{Location} @var{yyloc})
14859 @deftypemethodx {YYParser} {void} push_parse (@code{int} @var{token}, @code{Object} @var{yylval}, @code{Position} @var{yypos})
14860 @end deftypemethod
14862 The primary difference with respect to a pull parser is that the parser
14863 method @code{push_parse} is invoked repeatedly to parse each token.  This
14864 function is available if either the @samp{%define api.push-pull push} or
14865 @samp{%define api.push-pull both} declaration is used (@pxref{%define
14866 Summary}).  The @code{Location} and @code{Position} parameters are available
14867 only if location tracking is active.
14869 The value returned by the @code{push_parse} method is one of the following:
14870 0 (success), 1 (abort), 2 (memory exhaustion), or @code{YYPUSH_MORE}.  This
14871 new value, @code{YYPUSH_MORE}, may be returned if more input is required to
14872 finish parsing the grammar.
14874 If @code{api.push-pull} is defined as @code{both}, then the generated parser
14875 class will also implement the @code{parse} method. This method's body is a
14876 loop that repeatedly invokes the scanner and then passes the values obtained
14877 from the scanner to the @code{push_parse} method.
14879 There is one additional complication.  Technically, the push parser does not
14880 need to know about the scanner (i.e. an object implementing the
14881 @code{YYParser.Lexer} interface), but it does need access to the
14882 @code{yyerror} method.  Currently, the @code{yyerror} method is defined in
14883 the @code{YYParser.Lexer} interface. Hence, an implementation of that
14884 interface is still required in order to provide an implementation of
14885 @code{yyerror}.  The current approach (and subject to change) is to require
14886 the @code{YYParser} constructor to be given an object implementing the
14887 @code{YYParser.Lexer} interface. This object need only implement the
14888 @code{yyerror} method; the other methods can be stubbed since they will
14889 never be invoked.  The simplest way to do this is to add a trivial scanner
14890 implementation to your grammar file using whatever implementation of
14891 @code{yyerror} is desired. The following code sample shows a simple way to
14892 accomplish this.
14894 @example
14895 %code lexer
14897   public Object getLVal () @{return null;@}
14898   public int yylex () @{return 0;@}
14899   public void yyerror (String s) @{System.err.println(s);@}
14901 @end example
14903 @node Java Differences
14904 @subsection Differences between C/C++ and Java Grammars
14906 The different structure of the Java language forces several differences
14907 between C/C++ grammars, and grammars designed for Java parsers.  This
14908 section summarizes these differences.
14910 @itemize
14911 @item
14912 Java has no a preprocessor, so obviously the @code{YYERROR},
14913 @code{YYACCEPT}, @code{YYABORT} symbols (@pxref{Table of Symbols}) cannot be
14914 macros.  Instead, they should be preceded by @code{return} when they appear
14915 in an action.  The actual definition of these symbols is opaque to the Bison
14916 grammar, and it might change in the future.  The only meaningful operation
14917 that you can do, is to return them.  @xref{Java Action Features}.
14919 Note that of these three symbols, only @code{YYACCEPT} and
14920 @code{YYABORT} will cause a return from the @code{yyparse}
14921 method@footnote{Java parsers include the actions in a separate
14922 method than @code{yyparse} in order to have an intuitive syntax that
14923 corresponds to these C macros.}.
14925 @item
14926 Java lacks unions, so @code{%union} has no effect.  Instead, semantic
14927 values have a common base type: @code{Object} or as specified by
14928 @samp{%define api.value.type}.  Angle brackets on @code{%token}, @code{type},
14929 @code{$@var{n}} and @code{$$} specify subtypes rather than fields of
14930 an union.  The type of @code{$$}, even with angle brackets, is the base
14931 type since Java casts are not allow on the left-hand side of assignments.
14932 Also, @code{$@var{n}} and @code{@@@var{n}} are not allowed on the
14933 left-hand side of assignments. @xref{Java Semantic Values}, and
14934 @ref{Java Action Features}.
14936 @item
14937 The prologue declarations have a different meaning than in C/C++ code.
14938 @table @asis
14939 @item @code{%code imports}
14940 blocks are placed at the beginning of the Java source code.  They may
14941 include copyright notices.  For a @code{package} declarations, use
14942 @samp{%define api.package} instead.
14944 @item unqualified @code{%code}
14945 blocks are placed inside the parser class.
14947 @item @code{%code lexer}
14948 blocks, if specified, should include the implementation of the
14949 scanner.  If there is no such block, the scanner can be any class
14950 that implements the appropriate interface (@pxref{Java Scanner
14951 Interface}).
14952 @end table
14954 Other @code{%code} blocks are not supported in Java parsers.
14955 In particular, @code{%@{ @dots{} %@}} blocks should not be used
14956 and may give an error in future versions of Bison.
14958 The epilogue has the same meaning as in C/C++ code and it can
14959 be used to define other classes used by the parser @emph{outside}
14960 the parser class.
14961 @end itemize
14964 @node Java Declarations Summary
14965 @subsection Java Declarations Summary
14967 This summary only include declarations specific to Java or have special
14968 meaning when used in a Java parser.
14970 @deffn {Directive} {%language "Java"}
14971 Generate a Java class for the parser.
14972 @end deffn
14974 @deffn {Directive} %lex-param @{@var{type} @var{name}@}
14975 A parameter for the lexer class defined by @code{%code lexer}
14976 @emph{only}, added as parameters to the lexer constructor and the parser
14977 constructor that @emph{creates} a lexer.  Default is none.
14978 @xref{Java Scanner Interface}.
14979 @end deffn
14981 @deffn {Directive} %parse-param @{@var{type} @var{name}@}
14982 A parameter for the parser class added as parameters to constructor(s)
14983 and as fields initialized by the constructor(s).  Default is none.
14984 @xref{Java Parser Interface}.
14985 @end deffn
14987 @deffn {Directive} %token <@var{type}> @var{token} @dots{}
14988 Declare tokens.  Note that the angle brackets enclose a Java @emph{type}.
14989 @xref{Java Semantic Values}.
14990 @end deffn
14992 @deffn {Directive} %nterm <@var{type}> @var{nonterminal} @dots{}
14993 Declare the type of nonterminals.  Note that the angle brackets enclose
14994 a Java @emph{type}.
14995 @xref{Java Semantic Values}.
14996 @end deffn
14998 @deffn {Directive} %code @{ @var{code} @dots{} @}
14999 Code appended to the inside of the parser class.
15000 @xref{Java Differences}.
15001 @end deffn
15003 @deffn {Directive} {%code imports} @{ @var{code} @dots{} @}
15004 Code inserted just after the @code{package} declaration.
15005 @xref{Java Differences}.
15006 @end deffn
15008 @deffn {Directive} {%code init} @{ @var{code} @dots{} @}
15009 Code inserted at the beginning of the parser constructor body.
15010 @xref{Java Parser Interface}.
15011 @end deffn
15013 @deffn {Directive} {%code lexer} @{ @var{code} @dots{} @}
15014 Code added to the body of a inner lexer class within the parser class.
15015 @xref{Java Scanner Interface}.
15016 @end deffn
15018 @deffn {Directive} %% @var{code} @dots{}
15019 Code (after the second @code{%%}) appended to the end of the file,
15020 @emph{outside} the parser class.
15021 @xref{Java Differences}.
15022 @end deffn
15024 @deffn {Directive} %@{ @var{code} @dots{} %@}
15025 Not supported.  Use @code{%code imports} instead.
15026 @xref{Java Differences}.
15027 @end deffn
15029 @deffn {Directive} {%define api.prefix} @{@var{prefix}@}
15030 The prefix of the parser class name @code{@var{prefix}Parser} if
15031 @samp{%define api.parser.class} is not used.  Default is @code{YY}.
15032 @xref{Java Bison Interface}.
15033 @end deffn
15035 @deffn {Directive} {%define api.parser.abstract}
15036 Whether the parser class is declared @code{abstract}.  Default is false.
15037 @xref{Java Bison Interface}.
15038 @end deffn
15040 @deffn {Directive} {%define api.parser.annotations} @{@var{annotations}@}
15041 The Java annotations for the parser class.  Default is none.
15042 @xref{Java Bison Interface}.
15043 @end deffn
15045 @deffn {Directive} {%define api.parser.class} @{@var{name}@}
15046 The name of the parser class.  Default is @code{YYParser} or
15047 @code{@var{api.prefix}Parser}.  @xref{Java Bison Interface}.
15048 @end deffn
15050 @deffn {Directive} {%define api.parser.extends} @{@var{superclass}@}
15051 The superclass of the parser class.  Default is none.
15052 @xref{Java Bison Interface}.
15053 @end deffn
15055 @deffn {Directive} {%define api.parser.final}
15056 Whether the parser class is declared @code{final}.  Default is false.
15057 @xref{Java Bison Interface}.
15058 @end deffn
15060 @deffn {Directive} {%define api.parser.implements} @{@var{interfaces}@}
15061 The implemented interfaces of the parser class, a comma-separated list.
15062 Default is none.
15063 @xref{Java Bison Interface}.
15064 @end deffn
15066 @deffn {Directive} {%define api.parser.public}
15067 Whether the parser class is declared @code{public}.  Default is false.
15068 @xref{Java Bison Interface}.
15069 @end deffn
15071 @deffn {Directive} {%define api.parser.strictfp}
15072 Whether the parser class is declared @code{strictfp}.  Default is false.
15073 @xref{Java Bison Interface}.
15074 @end deffn
15076 @deffn {Directive} {%define init_throws} @{@var{exceptions}@}
15077 The exceptions thrown by @code{%code init} from the parser class
15078 constructor.  Default is none.
15079 @xref{Java Parser Interface}.
15080 @end deffn
15082 @deffn {Directive} {%define lex_throws} @{@var{exceptions}@}
15083 The exceptions thrown by the @code{yylex} method of the lexer, a
15084 comma-separated list.  Default is @code{java.io.IOException}.
15085 @xref{Java Scanner Interface}.
15086 @end deffn
15088 @deffn {Directive} {%define api.location.type} @{@var{class}@}
15089 The name of the class used for locations (a range between two
15090 positions).  This class is generated as an inner class of the parser
15091 class by @command{bison}.  Default is @code{Location}.
15092 Formerly named @code{location_type}.
15093 @xref{Java Location Values}.
15094 @end deffn
15096 @deffn {Directive} {%define api.package} @{@var{package}@}
15097 The package to put the parser class in.  Default is none.
15098 @xref{Java Bison Interface}.
15099 Renamed from @code{package} in Bison 3.7.
15100 @end deffn
15102 @deffn {Directive} {%define api.position.type} @{@var{class}@}
15103 The name of the class used for positions. This class must be supplied by
15104 the user.  Default is @code{Position}.
15105 Formerly named @code{position_type}.
15106 @xref{Java Location Values}.
15107 @end deffn
15109 @deffn {Directive} {%define api.value.type} @{@var{class}@}
15110 The base type of semantic values.  Default is @code{Object}.
15111 @xref{Java Semantic Values}.
15112 @end deffn
15114 @deffn {Directive} {%define throws} @{@var{exceptions}@}
15115 The exceptions thrown by user-supplied parser actions and
15116 @code{%initial-action}, a comma-separated list.  Default is none.
15117 @xref{Java Parser Interface}.
15118 @end deffn
15121 @c ================================================= History
15123 @node History
15124 @chapter A Brief History of the Greater Ungulates
15125 @cindex history
15126 @cindex ungulates
15128 @menu
15129 * Yacc::                        The original Yacc
15130 * yacchack::                    An obscure early implementation of reentrancy
15131 * Byacc::                       Berkeley Yacc
15132 * Bison::                       This program
15133 * Other Ungulates::             Similar programs
15134 @end menu
15136 @node Yacc
15137 @section The ancestral Yacc
15139 Bison originated as a workalike of a program called Yacc --- Yet Another
15140 Compiler Compiler.@footnote{Because of the acronym, the name is sometimes
15141 given as ``YACC'', but Johnson used ``Yacc'' in the descriptive paper
15142 included in the
15143 @url{https://s3.amazonaws.com/plan9-bell-labs/7thEdMan/v7vol2b.pdf, Version
15144 7 Unix Manual}.} Yacc was written at Bell Labs as part of the very early
15145 development of Unix; one of its first uses was to develop the original
15146 Portable C Compiler, pcc. The same person, Steven C. Johnson, wrote Yacc and
15147 the original pcc.
15149 According to the author
15150 @footnote{@url{https://lists.gnu.org/r/bison-patches/2019-02/msg00061.html}},
15151 Yacc was first invented in 1971 and reached a form recognizably similar to
15152 the C version in 1973.  Johnson published @cite{A Portable Compiler: Theory
15153 and Practice} @pcite{Johnson 1978}.
15155 Yacc was not itself originally written in C but in its predecessor language,
15156 B.  This goes far to explain its odd interface, which exposes a large number
15157 of global variables rather than bundling them into a C struct.  All other
15158 Yacc-like programs are descended from the C port of Yacc.
15160 Yacc, through both its deployment in pcc and as a standalone tool for
15161 generating other parsers, helped drive the early spread of Unix.  Yacc
15162 itself, however, passed out of use after around 1990 when workalikes
15163 with less restrictive licenses and more features became available.
15165 Original Yacc became generally available when Caldera released the sources
15166 of old versions of Unix up to V7 and 32V in 2002.  By that time it had been
15167 long superseded in practical use by Bison even on Yacc's native Unix
15168 variants.
15170 @node yacchack
15171 @section yacchack
15172 @cindex yacchack
15174 One of the deficiencies of original Yacc was its inability to produce
15175 reentrant parsers.  This was first remedied by a set of drop-in
15176 modifications called ``yacchack'', published by Eric S. Raymond on USENET
15177 around 1983.  This code was quickly forgotten when zoo and Berkeley Yacc
15178 became available a few years later.
15180 @node Byacc
15181 @section Berkeley Yacc
15182 @cindex byacc
15184 Berkeley Yacc was originated in 1985 by Robert Corbett @pcite{Corbett
15185 1984}.  It was originally named ``zoo'', but by October 1989 it became
15186 known as Berkeley Yacc or byacc.
15188 Berkeley Yacc had three advantages over the ancestral Yacc: it generated
15189 faster parsers, it could generate reentrant parsers, and the source code was
15190 released to the public domain rather than being under an AT&T proprietary
15191 license.  The better performance came from implementing techniques from
15192 DeRemer and Penello's seminal paper on LALR parsing @pcite{DeRemer 1982}.
15194 Use of byacc spread rapidly due to its public domain license. However, once
15195 Bison became available, byacc itself passed out of general use.
15197 @node Bison
15198 @section Bison
15199 @cindex zoo
15201 Robert Corbett actually wrote two (closely related) LALR parsers in 1985,
15202 both using the DeRemer/Penello techniques. One was ``zoo'', the other was
15203 ``Byson''. In 1987 Richard Stallman began working on Byson; the name changed
15204 to Bison and the interface became Yacc-compatible.
15206 The main visible difference between Yacc and Byson/Bison at the time of
15207 Byson's first release is that Byson supported the @code{@@@var{n}} construct
15208 (giving access to the starting and ending line number and character number
15209 associated with any of the symbols in the current rule).
15211 There was also the command @samp{%expect @var{n}} which said not to mention the
15212 conflicts if there are @var{n} shift/reduce conflicts and no reduce/reduce
15213 conflicts.  In more recent versions of Bison, @code{%expect} and its
15214 @code{%expect-rr} variant for reduce/reduce conflicts can be applied to
15215 individual rules.
15217 Later versions of Bison added many more new features.
15219 Bison error reporting has been improved in various ways. Notably. ancestral
15220 Yacc and Byson did not have carets in error messages.
15222 Compared to Yacc Bison uses a faster but less space-efficient encoding for
15223 the parse tables @pcite{Corbett 1984}, and more modern techniques for
15224 generating the lookahead sets @pcite{DeRemer 1982}.  This approach is the
15225 standard one since then.
15227 (It has also been plausibly alleged the differences in the algorithms stem
15228 mainly from the horrible kludges that Johnson had to perpetrate to make
15229 the original Yacc fit in a PDP-11.)
15231 Named references, semantic predicates, @code{%locations},
15232 @code{%glr-parser}, @code{%printer}, %destructor, dumps to DOT,
15233 @code{%parse-param}, @code{%lex-param}, and dumps to XSLT, LAC, and IELR(1)
15234 generation are new in Bison.
15236 Bison also has many features to support C++ that were not present in the
15237 ancestral Yacc or Byson.
15239 Bison obsolesced all previous Yacc variants and workalikes generating C by
15240 1995.
15242 @node Other Ungulates
15243 @section Other Ungulates
15245 The Yacc concept has frequently been ported to other languages. Some of the
15246 early ports are extinct along with the languages that hosted them; others
15247 have been superseded by parser skeletons shipped with Bison.
15249 However, independent implementations persist. One of the best-known
15250 still in use is David Beazley's ``PLY'' (Python Lex-Yacc) for
15251 Python. Another is goyacc, supporting the Go language. An ``ocamlyacc''
15252 is shipped as part of the Ocaml compiler suite.
15254 @c ================================================= Version Compatibility
15256 @node Versioning
15257 @chapter Bison Version Compatibility: Best Practices
15258 @cindex version
15259 @cindex compatibility
15261 Bison provides a Yacc compatibility mode in which it strives to conform with
15262 the POSIX standard.  Grammar files which are written to the POSIX standard, and
15263 do not take advantage of any of the special capabilities of Bison, should
15264 work with many versions of Bison without modification.
15266 All other features of Bison are particular to Bison, and are changing.  Bison
15267 is actively maintained and continuously evolving.  It should come as no
15268 surprise that an older version of Bison will not accept Bison source code which
15269 uses newer features that do no not exist at all in the older Bison.
15270 Regrettably, in spite of reasonable effort to maintain compatibility, the
15271 reverse situation may also occur: it may happen that code developed using an
15272 older version of Bison does not build with a newer version of Bison without
15273 modifications.
15275 Because Bison is a code generation tool, it is possible to retain its output
15276 and distribute that to the users of the program.  The users are then not
15277 required to have Bison installed at all, only an implementation of the
15278 programming language, such as C, which is required for processing the generated
15279 output.
15281 It is the output of Bison that is intended to be of the utmost portability.
15282 So, that is to say, whereas the Bison grammar source code may have a dependency
15283 on specific versions of Bison, the generated parser from any version of Bison
15284 should work with with a large number of implementations of C, or whatever
15285 language is applicable.
15287 The recommended best practice for using Bison (in the context of software that
15288 is distributed in source code form) is to ship the generated parser to the
15289 downstream users.  Only those downstream users who engage in active development
15290 of the program who need to make changes to the grammar file need to have Bison
15291 installed at all, and those users can install the specific version of Bison
15292 which is required.
15294 Following this recommended practice also makes it possible to use a more recent
15295 Bison than what is available to users through operating system distributions,
15296 thereby taking advantage of the latest techniques that Bison allows.
15298 Some features of Bison have been, or are being adopted into other Yacc-like
15299 programs.  Therefore it might seem that is a good idea to write grammar code
15300 which targets multiple implementations, similarly to the way C programs are
15301 often written to target multiple compilers and language versions.  Other than
15302 the Yacc subset described by POSIX, the Bison language is not rigorously
15303 standardized.  When a Bison feature is adopted by another parser generator, it
15304 may be initially compatible with that version of Bison on which it was based,
15305 but the compatibility may degrade going forward.  Developers who strive to make
15306 their Bison code simultaneously compatible with other parser generators are
15307 encouraged to nevertheless use specific versions of all generators, and still
15308 follow the recommended practice of shipping generated output.  For example,
15309 a project can internally maintain compatibility with multiple generators,
15310 and choose the output of a particular one to ship to the users.  Or else,
15311 the project could ship all of the outputs, arranging for a way for the user
15312 to specify which one is used to build the program.
15314 @c ================================================= FAQ
15316 @node FAQ
15317 @chapter Frequently Asked Questions
15318 @cindex frequently asked questions
15319 @cindex questions
15321 Several questions about Bison come up occasionally.  Here some of them
15322 are addressed.
15324 @menu
15325 * Memory Exhausted::            Breaking the Stack Limits
15326 * How Can I Reset the Parser::  @code{yyparse} Keeps some State
15327 * Strings are Destroyed::       @code{yylval} Loses Track of Strings
15328 * Implementing Gotos/Loops::    Control Flow in the Calculator
15329 * Multiple start-symbols::      Factoring closely related grammars
15330 * Secure?  Conform?::           Is Bison POSIX safe?
15331 * Enabling Relocatability::     Moving Bison/using it through network shares
15332 * I can't build Bison::         Troubleshooting
15333 * Where can I find help?::      Troubleshouting
15334 * Bug Reports::                 Troublereporting
15335 * More Languages::              Parsers in C++, Java, and so on
15336 * Beta Testing::                Experimenting development versions
15337 * Mailing Lists::               Meeting other Bison users
15338 @end menu
15340 @node Memory Exhausted
15341 @section Memory Exhausted
15343 @quotation
15344 My parser returns with error with a @samp{memory exhausted}
15345 message.  What can I do?
15346 @end quotation
15348 This question is already addressed elsewhere, see @ref{Recursion}.
15350 @node How Can I Reset the Parser
15351 @section How Can I Reset the Parser
15353 The following phenomenon has several symptoms, resulting in the
15354 following typical questions:
15356 @quotation
15357 I invoke @code{yyparse} several times, and on correct input it works
15358 properly; but when a parse error is found, all the other calls fail
15359 too.  How can I reset the error flag of @code{yyparse}?
15360 @end quotation
15362 @noindent
15365 @quotation
15366 My parser includes support for an @samp{#include}-like feature, in which
15367 case I run @code{yyparse} from @code{yyparse}.  This fails although I did
15368 specify @samp{%define api.pure full}.
15369 @end quotation
15371 These problems typically come not from Bison itself, but from
15372 Lex-generated scanners.  Because these scanners use large buffers for
15373 speed, they might not notice a change of input file.  As a
15374 demonstration, consider the following source file,
15375 @file{first-line.l}:
15377 @example
15378 @group
15380 #include <stdio.h>
15381 #include <stdlib.h>
15383 @end group
15385 .*\n    ECHO; return 1;
15387 @group
15389 yyparse (char const *file)
15391   yyin = fopen (file, "r");
15392   if (!yyin)
15393     @{
15394       perror ("fopen");
15395       exit (EXIT_FAILURE);
15396     @}
15397 @end group
15398 @group
15399   /* One token only. */
15400   yylex ();
15401   if (fclose (yyin) != 0)
15402     @{
15403       perror ("fclose");
15404       exit (EXIT_FAILURE);
15405     @}
15406   return 0;
15408 @end group
15410 @group
15412 main (void)
15414   yyparse ("input");
15415   yyparse ("input");
15416   return 0;
15418 @end group
15419 @end example
15421 @noindent
15422 If the file @file{input} contains
15424 @example
15425 input:1: Hello,
15426 input:2: World!
15427 @end example
15429 @noindent
15430 then instead of getting the first line twice, you get:
15432 @example
15433 $ @kbd{flex -ofirst-line.c first-line.l}
15434 $ @kbd{gcc  -ofirst-line   first-line.c -ll}
15435 $ @kbd{./first-line}
15436 input:1: Hello,
15437 input:2: World!
15438 @end example
15440 Therefore, whenever you change @code{yyin}, you must tell the
15441 Lex-generated scanner to discard its current buffer and switch to the
15442 new one.  This depends upon your implementation of Lex; see its
15443 documentation for more.  For Flex, it suffices to call
15444 @samp{YY_FLUSH_BUFFER} after each change to @code{yyin}.  If your
15445 Flex-generated scanner needs to read from several input streams to
15446 handle features like include files, you might consider using Flex
15447 functions like @samp{yy_switch_to_buffer} that manipulate multiple
15448 input buffers.
15450 If your Flex-generated scanner uses start conditions (@pxref{Start
15451 conditions, , Start conditions, flex, The Flex Manual}), you might
15452 also want to reset the scanner's state, i.e., go back to the initial
15453 start condition, through a call to @samp{BEGIN (0)}.
15455 @node Strings are Destroyed
15456 @section Strings are Destroyed
15458 @quotation
15459 My parser seems to destroy old strings, or maybe it loses track of
15460 them.  Instead of reporting @samp{"foo", "bar"}, it reports
15461 @samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
15462 @end quotation
15464 This error is probably the single most frequent ``bug report'' sent to
15465 Bison lists, but is only concerned with a misunderstanding of the role
15466 of the scanner.  Consider the following Lex code:
15468 @example
15469 @group
15471 #include <stdio.h>
15472 char *yylval = NULL;
15474 @end group
15475 @group
15477 .*    yylval = yytext; return 1;
15478 \n    continue;
15480 @end group
15481 @group
15483 main ()
15485   /* Similar to using $1, $2 in a Bison action. */
15486   char *fst = (yylex (), yylval);
15487   char *snd = (yylex (), yylval);
15488   printf ("\"%s\", \"%s\"\n", fst, snd);
15489   return 0;
15491 @end group
15492 @end example
15494 If you compile and run this code, you get:
15496 @example
15497 $ @kbd{flex -osplit-lines.c split-lines.l}
15498 $ @kbd{gcc  -osplit-lines   split-lines.c -ll}
15499 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
15500 "one
15501 two", "two"
15502 @end example
15504 @noindent
15505 this is because @code{yytext} is a buffer provided for @emph{reading}
15506 in the action, but if you want to keep it, you have to duplicate it
15507 (e.g., using @code{strdup}).  Note that the output may depend on how
15508 your implementation of Lex handles @code{yytext}.  For instance, when
15509 given the Lex compatibility option @option{-l} (which triggers the
15510 option @samp{%array}) Flex generates a different behavior:
15512 @example
15513 $ @kbd{flex -l -osplit-lines.c split-lines.l}
15514 $ @kbd{gcc     -osplit-lines   split-lines.c -ll}
15515 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
15516 "two", "two"
15517 @end example
15520 @node Implementing Gotos/Loops
15521 @section Implementing Gotos/Loops
15523 @quotation
15524 My simple calculator supports variables, assignments, and functions,
15525 but how can I implement gotos, or loops?
15526 @end quotation
15528 Although very pedagogical, the examples included in the document blur
15529 the distinction to make between the parser---whose job is to recover
15530 the structure of a text and to transmit it to subsequent modules of
15531 the program---and the processing (such as the execution) of this
15532 structure.  This works well with so called straight line programs,
15533 i.e., precisely those that have a straightforward execution model:
15534 execute simple instructions one after the others.
15536 @cindex abstract syntax tree
15537 @cindex AST
15538 If you want a richer model, you will probably need to use the parser
15539 to construct a tree that does represent the structure it has
15540 recovered; this tree is usually called the @dfn{abstract syntax tree},
15541 or @dfn{AST} for short.  Then, walking through this tree,
15542 traversing it in various ways, will enable treatments such as its
15543 execution or its translation, which will result in an interpreter or a
15544 compiler.
15546 This topic is way beyond the scope of this manual, and the reader is
15547 invited to consult the dedicated literature.
15550 @node Multiple start-symbols
15551 @section Multiple start-symbols
15553 @quotation
15554 I have several closely related grammars, and I would like to share their
15555 implementations.  In fact, I could use a single grammar but with multiple
15556 entry points.
15557 @end quotation
15559 Bison does not support multiple start-symbols, but there is a very simple
15560 means to simulate them.  If @code{foo} and @code{bar} are the two pseudo
15561 start-symbols, then introduce two new tokens, say @code{START_FOO} and
15562 @code{START_BAR}, and use them as switches from the real start-symbol:
15564 @example
15565 %token START_FOO START_BAR;
15566 %start start;
15567 start:
15568   START_FOO foo
15569 | START_BAR bar;
15570 @end example
15572 These tokens prevent the introduction of new conflicts.  As far as the
15573 parser goes, that is all that is needed.
15575 Now the difficult part is ensuring that the scanner will send these tokens
15576 first.  If your scanner is hand-written, that should be straightforward.  If
15577 your scanner is generated by Lex, them there is simple means to do it:
15578 recall that anything between @samp{%@{ ... %@}} after the first @code{%%} is
15579 copied verbatim in the top of the generated @code{yylex} function.  Make
15580 sure a variable @code{start_token} is available in the scanner (e.g., a
15581 global variable or using @code{%lex-param} etc.), and use the following:
15583 @example
15584   /* @r{Prologue.} */
15587   if (start_token)
15588     @{
15589       int t = start_token;
15590       start_token = 0;
15591       return t;
15592     @}
15594   /* @r{The rules.} */
15595 @end example
15598 @node Secure?  Conform?
15599 @section Secure?  Conform?
15601 @quotation
15602 Is Bison secure?  Does it conform to POSIX?
15603 @end quotation
15605 If you're looking for a guarantee or certification, we don't provide it.
15606 However, Bison is intended to be a reliable program that conforms to the
15607 POSIX specification for Yacc.  If you run into problems, please send us a
15608 bug report.
15610 @include relocatable.texi
15612 @node I can't build Bison
15613 @section I can't build Bison
15615 @quotation
15616 I can't build Bison because @command{make} complains that
15617 @code{msgfmt} is not found.
15618 What should I do?
15619 @end quotation
15621 Like most GNU packages with internationalization support, that feature
15622 is turned on by default.  If you have problems building in the @file{po}
15623 subdirectory, it indicates that your system's internationalization
15624 support is lacking.  You can re-configure Bison with
15625 @option{--disable-nls} to turn off this support, or you can install GNU
15626 gettext from @url{https://ftp.gnu.org/gnu/gettext/} and re-configure
15627 Bison.  See the file @file{ABOUT-NLS} for more information.
15629 @quotation
15630 I can't build Bison because my C compiler is too old.
15631 @end quotation
15633 Except for GLR parsers (which require C99), the C code that Bison generates
15634 requires only C89 or later.  However, Bison itself requires common C99
15635 features such as declarations after statements.  Bison's @code{configure}
15636 script attempts to enable C99 (or later) support on compilers that default
15637 to pre-C99.  If your compiler lacks these C99 features entirely, GCC may
15638 well be a better choice; or you can try upgrading to your compiler's latest
15639 version.
15641 @node Where can I find help?
15642 @section Where can I find help?
15644 @quotation
15645 I'm having trouble using Bison.  Where can I find help?
15646 @end quotation
15648 First, read this fine manual.  Beyond that, you can send mail to
15649 @email{help-bison@@gnu.org}.  This mailing list is intended to be
15650 populated with people who are willing to answer questions about using
15651 and installing Bison.  Please keep in mind that (most of) the people on
15652 the list have aspects of their lives which are not related to Bison (!),
15653 so you may not receive an answer to your question right away.  This can
15654 be frustrating, but please try not to honk them off; remember that any
15655 help they provide is purely voluntary and out of the kindness of their
15656 hearts.
15658 @node Bug Reports
15659 @section Bug Reports
15661 @quotation
15662 I found a bug.  What should I include in the bug report?
15663 @end quotation
15665 Before sending a bug report, make sure you are using the latest
15666 version.  Check @url{https://ftp.gnu.org/pub/gnu/bison/} or one of its
15667 mirrors.  Be sure to include the version number in your bug report.  If
15668 the bug is present in the latest version but not in a previous version,
15669 try to determine the most recent version which did not contain the bug.
15671 If the bug is parser-related, you should include the smallest grammar
15672 you can which demonstrates the bug.  The grammar file should also be
15673 complete (i.e., I should be able to run it through Bison without having
15674 to edit or add anything).  The smaller and simpler the grammar, the
15675 easier it will be to fix the bug.
15677 Include information about your compilation environment, including your
15678 operating system's name and version and your compiler's name and
15679 version.  If you have trouble compiling, you should also include a
15680 transcript of the build session, starting with the invocation of
15681 @code{configure}.  Depending on the nature of the bug, you may be asked to
15682 send additional files as well (such as @file{config.h} or @file{config.cache}).
15684 Patches are most welcome, but not required.  That is, do not hesitate to
15685 send a bug report just because you cannot provide a fix.
15687 Send bug reports to @email{bug-bison@@gnu.org}.
15689 @node More Languages
15690 @section More Languages
15692 @quotation
15693 Will Bison ever have C++ and Java support?  How about @var{insert your
15694 favorite language here}?
15695 @end quotation
15697 C++, D and Java are supported.  We'd love to add other languages;
15698 contributions are welcome.
15700 @node Beta Testing
15701 @section Beta Testing
15703 @quotation
15704 What is involved in being a beta tester?
15705 @end quotation
15707 It's not terribly involved.  Basically, you would download a test
15708 release, compile it, and use it to build and run a parser or two.  After
15709 that, you would submit either a bug report or a message saying that
15710 everything is okay.  It is important to report successes as well as
15711 failures because test releases eventually become mainstream releases,
15712 but only if they are adequately tested.  If no one tests, development is
15713 essentially halted.
15715 Beta testers are particularly needed for operating systems to which the
15716 developers do not have easy access.  They currently have easy access to
15717 recent GNU/Linux and Solaris versions.  Reports about other operating
15718 systems are especially welcome.
15720 @node Mailing Lists
15721 @section Mailing Lists
15723 @quotation
15724 How do I join the help-bison and bug-bison mailing lists?
15725 @end quotation
15727 See @url{https://lists.gnu.org/}.
15729 @c ================================================= Table of Symbols
15731 @node Table of Symbols
15732 @appendix Bison Symbols
15733 @cindex Bison symbols, table of
15734 @cindex symbols in Bison, table of
15736 @deffn {Variable} @@$
15737 In an action, the location of the left-hand side of the rule.
15738 @xref{Tracking Locations}.
15739 @end deffn
15741 @deffn {Variable} @@@var{n}
15742 @deffnx {Symbol} @@@var{n}
15743 In an action, the location of the @var{n}-th symbol of the right-hand side
15744 of the rule.  @xref{Tracking Locations}.
15746 In a grammar, the Bison-generated nonterminal symbol for a midrule action
15747 with a semantic value.  @xref{Midrule Action Translation}.
15748 @end deffn
15750 @deffn {Variable} @@@var{name}
15751 @deffnx {Variable} @@[@var{name}]
15752 In an action, the location of a symbol addressed by @var{name}.
15753 @xref{Tracking Locations}.
15754 @end deffn
15756 @deffn {Symbol} $@@@var{n}
15757 In a grammar, the Bison-generated nonterminal symbol for a midrule action
15758 with no semantics value.  @xref{Midrule Action Translation}.
15759 @end deffn
15761 @deffn {Variable} $$
15762 In an action, the semantic value of the left-hand side of the rule.
15763 @xref{Actions}.
15764 @end deffn
15766 @deffn {Variable} $@var{n}
15767 In an action, the semantic value of the @var{n}-th symbol of the
15768 right-hand side of the rule.  @xref{Actions}.
15769 @end deffn
15771 @deffn {Variable} $@var{name}
15772 @deffnx {Variable} $[@var{name}]
15773 In an action, the semantic value of a symbol addressed by @var{name}.
15774 @xref{Actions}.
15775 @end deffn
15777 @deffn {Delimiter} %%
15778 Delimiter used to separate the grammar rule section from the
15779 Bison declarations section or the epilogue.
15780 @xref{Grammar Layout}.
15781 @end deffn
15783 @c Don't insert spaces, or check the DVI output.
15784 @deffn {Delimiter} %@{@var{code}%@}
15785 All code listed between @samp{%@{} and @samp{%@}} is copied verbatim
15786 to the parser implementation file.  Such code forms the prologue of
15787 the grammar file.  @xref{Grammar Outline}.
15788 @end deffn
15790 @deffn {Directive} %?@{@var{expression}@}
15791 Predicate actions.  This is a type of action clause that may appear in
15792 rules. The expression is evaluated, and if false, causes a syntax error.  In
15793 GLR parsers during nondeterministic operation,
15794 this silently causes an alternative parse to die.  During deterministic
15795 operation, it is the same as the effect of YYERROR.
15796 @xref{Semantic Predicates}.
15797 @end deffn
15799 @deffn {Construct} /* @dots{} */
15800 @deffnx {Construct} // @dots{}
15801 Comments, as in C/C++.
15802 @end deffn
15804 @deffn {Delimiter} :
15805 Separates a rule's result from its components.  @xref{Rules}.
15806 @end deffn
15808 @deffn {Delimiter} ;
15809 Terminates a rule.  @xref{Rules}.
15810 @end deffn
15812 @deffn {Delimiter} |
15813 Separates alternate rules for the same result nonterminal.
15814 @xref{Rules}.
15815 @end deffn
15817 @deffn {Directive} <*>
15818 Used to define a default tagged @code{%destructor} or default tagged
15819 @code{%printer}.
15821 @xref{Destructor Decl}.
15822 @end deffn
15824 @deffn {Directive} <>
15825 Used to define a default tagless @code{%destructor} or default tagless
15826 @code{%printer}.
15828 @xref{Destructor Decl}.
15829 @end deffn
15831 @deffn {Symbol} $accept
15832 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
15833 $end}, where @var{start} is the start symbol.  @xref{Start Decl}.  It cannot
15834 be used in the grammar.
15835 @end deffn
15837 @deffn {Directive} %code @{@var{code}@}
15838 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
15839 Insert @var{code} verbatim into the output parser source at the
15840 default location or at the location specified by @var{qualifier}.
15841 @xref{%code Summary}.
15842 @end deffn
15844 @deffn {Directive} %debug
15845 Equip the parser for debugging.  @xref{Decl Summary}.
15846 @end deffn
15848 @ifset defaultprec
15849 @deffn {Directive} %default-prec
15850 Assign a precedence to rules that lack an explicit @samp{%prec}
15851 modifier.  @xref{Contextual Precedence}.
15852 @end deffn
15853 @end ifset
15855 @deffn {Directive} %define @var{variable}
15856 @deffnx {Directive} %define @var{variable} @var{value}
15857 @deffnx {Directive} %define @var{variable} @{@var{value}@}
15858 @deffnx {Directive} %define @var{variable} "@var{value}"
15859 Define a variable to adjust Bison's behavior.  @xref{%define Summary}.
15860 @end deffn
15862 @deffn {Directive} %defines
15863 @deffnx {Directive} %defines @var{defines-file}
15864 Historical name for @code{%header}.
15865 @xref{Decl Summary}.
15866 @end deffn
15868 @deffn {Directive} %destructor
15869 Specify how the parser should reclaim the memory associated to
15870 discarded symbols.  @xref{Destructor Decl}.
15871 @end deffn
15873 @deffn {Directive} %dprec
15874 Bison declaration to assign a precedence to a rule that is used at parse
15875 time to resolve reduce/reduce conflicts.  @xref{GLR Parsers}.
15876 @end deffn
15878 @deffn {Directive} %empty
15879 Bison declaration to declare make explicit that a rule has an empty
15880 right-hand side.  @xref{Empty Rules}.
15881 @end deffn
15883 @deffn {Symbol} $end
15884 The predefined token marking the end of the token stream.  It cannot be
15885 used in the grammar.
15886 @end deffn
15888 @deffn {Symbol} error
15889 A token name reserved for error recovery.  This token may be used in
15890 grammar rules so as to allow the Bison parser to recognize an error in
15891 the grammar without halting the process.  In effect, a sentence
15892 containing an error may be recognized as valid.  On a syntax error, the
15893 token @code{error} becomes the current lookahead token.  Actions
15894 corresponding to @code{error} are then executed, and the lookahead
15895 token is reset to the token that originally caused the violation.
15896 @xref{Error Recovery}.
15897 @end deffn
15899 @deffn {Directive} %error-verbose
15900 An obsolete directive standing for @samp{%define parse.error verbose}.
15901 @end deffn
15903 @deffn {Directive} %file-prefix "@var{prefix}"
15904 Bison declaration to set the prefix of the output files.  @xref{Decl
15905 Summary}.
15906 @end deffn
15908 @deffn {Directive} %glr-parser
15909 Bison declaration to produce a GLR parser.  @xref{GLR
15910 Parsers}.
15911 @end deffn
15913 @deffn {Directive} %header
15914 Bison declaration to create a parser header file, which is usually
15915 meant for the scanner.  @xref{Decl Summary}.
15916 @end deffn
15918 @deffn {Directive} %header @var{header-file}
15919 Same as above, but save in the file @var{header-file}.
15920 @xref{Decl Summary}.
15921 @end deffn
15923 @deffn {Directive} %initial-action
15924 Run user code before parsing.  @xref{Initial Action Decl}.
15925 @end deffn
15927 @deffn {Directive} %language
15928 Specify the programming language for the generated parser.
15929 @xref{Decl Summary}.
15930 @end deffn
15932 @deffn {Directive} %left
15933 Bison declaration to assign precedence and left associativity to token(s).
15934 @xref{Precedence Decl}.
15935 @end deffn
15937 @deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
15938 Bison declaration to specifying additional arguments that
15939 @code{yylex} should accept.  @xref{Pure Calling}.
15940 @end deffn
15942 @deffn {Directive} %merge
15943 Bison declaration to assign a merging function to a rule.  If there is a
15944 reduce/reduce conflict with a rule having the same merging function, the
15945 function is applied to the two semantic values to get a single result.
15946 @xref{GLR Parsers}.
15947 @end deffn
15949 @deffn {Directive} %name-prefix "@var{prefix}"
15950 Obsoleted by the @code{%define} variable @code{api.prefix} (@pxref{Multiple
15951 Parsers}).
15953 Rename the external symbols (variables and functions) used in the parser so
15954 that they start with @var{prefix} instead of @samp{yy}.  Contrary to
15955 @code{api.prefix}, do no rename types and macros.
15957 The precise list of symbols renamed in C parsers is @code{yyparse},
15958 @code{yylex}, @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yychar},
15959 @code{yydebug}, and (if locations are used) @code{yylloc}.  If you use a
15960 push parser, @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
15961 @code{yypstate_new} and @code{yypstate_delete} will also be renamed.  For
15962 example, if you use @samp{%name-prefix "c_"}, the names become
15963 @code{c_parse}, @code{c_lex}, and so on.  For C++ parsers, see the
15964 @code{%define api.namespace} documentation in this section.
15965 @end deffn
15968 @ifset defaultprec
15969 @deffn {Directive} %no-default-prec
15970 Do not assign a precedence to rules that lack an explicit @samp{%prec}
15971 modifier.  @xref{Contextual Precedence}.
15972 @end deffn
15973 @end ifset
15975 @deffn {Directive} %no-lines
15976 Bison declaration to avoid generating @code{#line} directives in the
15977 parser implementation file.  @xref{Decl Summary}.
15978 @end deffn
15980 @deffn {Directive} %nonassoc
15981 Bison declaration to assign precedence and nonassociativity to token(s).
15982 @xref{Precedence Decl}.
15983 @end deffn
15985 @deffn {Directive} %nterm
15986 Bison declaration to declare nonterminals.  @xref{Type Decl}.
15987 @end deffn
15989 @deffn {Directive} %output "@var{file}"
15990 Bison declaration to set the name of the parser implementation file.
15991 @xref{Decl Summary}.
15992 @end deffn
15994 @deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
15995 Bison declaration to specify additional arguments that both
15996 @code{yylex} and @code{yyparse} should accept.  @xref{Parser Function}.
15997 @end deffn
15999 @deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
16000 Bison declaration to specify additional arguments that @code{yyparse}
16001 should accept.  @xref{Parser Function}.
16002 @end deffn
16004 @deffn {Directive} %prec
16005 Bison declaration to assign a precedence to a specific rule.
16006 @xref{Contextual Precedence}.
16007 @end deffn
16009 @deffn {Directive} %precedence
16010 Bison declaration to assign precedence to token(s), but no associativity
16011 @xref{Precedence Decl}.
16012 @end deffn
16014 @deffn {Directive} %pure-parser
16015 Deprecated version of @samp{%define api.pure} (@pxref{%define
16016 Summary}), for which Bison is more careful to warn about
16017 unreasonable usage.
16018 @end deffn
16020 @deffn {Directive} %require "@var{version}"
16021 Require version @var{version} or higher of Bison.  @xref{Require Decl}.
16022 @end deffn
16024 @deffn {Directive} %right
16025 Bison declaration to assign precedence and right associativity to token(s).
16026 @xref{Precedence Decl}.
16027 @end deffn
16029 @deffn {Directive} %skeleton
16030 Specify the skeleton to use; usually for development.
16031 @xref{Decl Summary}.
16032 @end deffn
16034 @deffn {Directive} %start
16035 Bison declaration to specify the start symbol.  @xref{Start Decl}.
16036 @end deffn
16038 @deffn {Directive} %token
16039 Bison declaration to declare token(s) without specifying precedence.
16040 @xref{Token Decl}.
16041 @end deffn
16043 @deffn {Directive} %token-table
16044 Bison declaration to include a token name table in the parser implementation
16045 file.  @xref{Decl Summary}.
16046 @end deffn
16048 @deffn {Directive} %type
16049 Bison declaration to declare symbol value types.  @xref{Type Decl}.
16050 @end deffn
16052 @deffn {Symbol} $undefined
16053 The predefined token onto which all undefined values returned by
16054 @code{yylex} are mapped.  It cannot be used in the grammar, rather, use
16055 @code{error}.
16056 @end deffn
16058 @deffn {Directive} %union
16059 Bison declaration to specify several possible data types for semantic
16060 values.  @xref{Union Decl}.
16061 @end deffn
16063 @deffn {Macro} YYABORT
16064 Macro to pretend that an unrecoverable syntax error has occurred, by making
16065 @code{yyparse} return 1 immediately.  The error reporting function
16066 @code{yyerror} is not called.  @xref{Parser Function}.
16068 For Java parsers, this functionality is invoked using @code{return YYABORT;}
16069 instead.
16070 @end deffn
16072 @deffn {Macro} YYACCEPT
16073 Macro to pretend that a complete utterance of the language has been
16074 read, by making @code{yyparse} return 0 immediately.
16075 @xref{Parser Function}.
16077 For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
16078 instead.
16079 @end deffn
16081 @deffn {Macro} YYBACKUP
16082 Macro to discard a value from the parser stack and fake a lookahead
16083 token.  @xref{Action Features}.
16084 @end deffn
16086 @deffn {Macro} YYBISON
16087 The version of Bison as an integer, for instance 30704 for version 3.7.4.
16088 Defined in @file{yacc.c} only.  Before version 3.7.4, @code{YYBISON} was
16089 defined to 1.
16090 @end deffn
16092 @deffn {Variable} yychar
16093 External integer variable that contains the integer value of the
16094 lookahead token.  (In a pure parser, it is a local variable within
16095 @code{yyparse}.)  Error-recovery rule actions may examine this variable.
16096 @xref{Action Features}.
16097 @end deffn
16099 @deffn {Variable} yyclearin
16100 Macro used in error-recovery rule actions.  It clears the previous
16101 lookahead token.  @xref{Error Recovery}.
16102 @end deffn
16104 @deffn {Macro} YYDEBUG
16105 Macro to define to equip the parser with tracing code.  @xref{Tracing}.
16106 @end deffn
16108 @deffn {Variable} yydebug
16109 External integer variable set to zero by default.  If @code{yydebug}
16110 is given a nonzero value, the parser will output information on input
16111 symbols and parser action.  @xref{Tracing}.
16112 @end deffn
16114 @deffn {Value} YYEMPTY
16115 The pseudo token kind when there is no lookahead token.
16116 @end deffn
16118 @deffn {Value} YYEOF
16119 The token kind denoting is the end of the input stream.
16120 @end deffn
16122 @deffn {Macro} yyerrok
16123 Macro to cause parser to recover immediately to its normal mode
16124 after a syntax error.  @xref{Error Recovery}.
16125 @end deffn
16127 @deffn {Macro} YYERROR
16128 Cause an immediate syntax error.  This statement initiates error
16129 recovery just as if the parser itself had detected an error; however, it
16130 does not call @code{yyerror}, and does not print any message.  If you
16131 want to print an error message, call @code{yyerror} explicitly before
16132 the @samp{YYERROR;} statement.  @xref{Error Recovery}.
16134 For Java parsers, this functionality is invoked using @code{return YYERROR;}
16135 instead.
16136 @end deffn
16138 @deffn {Function} yyerror
16139 User-supplied function to be called by @code{yyparse} on error.
16140 @xref{Error Reporting Function}.
16141 @end deffn
16143 @deffn {Macro} YYFPRINTF
16144 Macro used to output run-time traces in C.
16145 @xref{Enabling Traces}.
16146 @end deffn
16148 @deffn {Macro} YYINITDEPTH
16149 Macro for specifying the initial size of the parser stack.
16150 @xref{Memory Management}.
16151 @end deffn
16153 @deffn {Function} yylex
16154 User-supplied lexical analyzer function, called with no arguments to get
16155 the next token.  @xref{Lexical}.
16156 @end deffn
16158 @deffn {Variable} yylloc
16159 External variable in which @code{yylex} should place the line and column
16160 numbers associated with a token.  (In a pure parser, it is a local
16161 variable within @code{yyparse}, and its address is passed to
16162 @code{yylex}.)
16163 You can ignore this variable if you don't use the @samp{@@} feature in the
16164 grammar actions.
16165 @xref{Token Locations}.
16166 In semantic actions, it stores the location of the lookahead token.
16167 @xref{Actions and Locations}.
16168 @end deffn
16170 @deffn {Type} YYLTYPE
16171 Data type of @code{yylloc}.  By default in C, a structure with four members
16172 (start/end line/column).  @xref{Location Type}.
16173 @end deffn
16175 @deffn {Variable} yylval
16176 External variable in which @code{yylex} should place the semantic
16177 value associated with a token.  (In a pure parser, it is a local
16178 variable within @code{yyparse}, and its address is passed to
16179 @code{yylex}.)
16180 @xref{Token Values}.
16181 In semantic actions, it stores the semantic value of the lookahead token.
16182 @xref{Actions}.
16183 @end deffn
16185 @deffn {Macro} YYMAXDEPTH
16186 Macro for specifying the maximum size of the parser stack.  @xref{Memory
16187 Management}.
16188 @end deffn
16190 @deffn {Variable} yynerrs
16191 Global variable which Bison increments each time it reports a syntax error.
16192 (In a pure parser, it is a local variable within @code{yyparse}. In a
16193 pure push parser, it is a member of @code{yypstate}.)
16194 @xref{Error Reporting Function}.
16195 @end deffn
16197 @deffn {Macro} YYNOMEM
16198 Macro to pretend that memory is exhausted, by making @code{yyparse} return 2
16199 immediately.  The error reporting function @code{yyerror} is called.
16200 @xref{Parser Function}.
16201 @end deffn
16203 @deffn {Function} yyparse
16204 The parser function produced by Bison; call this function to start
16205 parsing.  @xref{Parser Function}.
16206 @end deffn
16208 @deffn {Function} yypstate_delete
16209 The function to delete a parser instance, produced by Bison in push mode;
16210 call this function to delete the memory associated with a parser.
16211 @xref{yypstate_delete,,@code{yypstate_delete}}.  Does nothing when called
16212 with a null pointer.
16213 @end deffn
16215 @deffn {Function} yypstate_new
16216 The function to create a parser instance, produced by Bison in push mode;
16217 call this function to create a new parser.
16218 @xref{yypstate_new,,@code{yypstate_new}}.
16219 @end deffn
16221 @deffn {Function} yypull_parse
16222 The parser function produced by Bison in push mode; call this function to
16223 parse the rest of the input stream.
16224 @xref{yypull_parse,,@code{yypull_parse}}.
16225 @end deffn
16227 @deffn {Function} yypush_parse
16228 The parser function produced by Bison in push mode; call this function to
16229 parse a single token.
16230 @xref{yypush_parse,,@code{yypush_parse}}.
16231 @end deffn
16233 @deffn {Macro} YYRECOVERING
16234 The expression @code{YYRECOVERING ()} yields 1 when the parser
16235 is recovering from a syntax error, and 0 otherwise.
16236 @xref{Action Features}.
16237 @end deffn
16239 @deffn {Macro} YYSTACK_USE_ALLOCA
16240 Macro used to control the use of @code{alloca} when the
16241 deterministic parser in C needs to extend its stacks.  If defined to 0,
16242 the parser will use @code{malloc} to extend its stacks and memory exhaustion
16243 occurs if @code{malloc} fails (@pxref{Memory Management}).  If defined to
16244 1, the parser will use @code{alloca}.  Values other than 0 and 1 are
16245 reserved for future Bison extensions.  If not defined,
16246 @code{YYSTACK_USE_ALLOCA} defaults to 0.
16248 In the all-too-common case where your code may run on a host with a
16249 limited stack and with unreliable stack-overflow checking, you should
16250 set @code{YYMAXDEPTH} to a value that cannot possibly result in
16251 unchecked stack overflow on any of your target hosts when
16252 @code{alloca} is called.  You can inspect the code that Bison
16253 generates in order to determine the proper numeric values.  This will
16254 require some expertise in low-level implementation details.
16255 @end deffn
16257 @deffn {Type} YYSTYPE
16258 In C, data type of semantic values; @code{int} by default.
16259 Deprecated in favor of the @code{%define} variable @code{api.value.type}.
16260 @xref{Value Type}.
16261 @end deffn
16263 @deffn {Type} yysymbol_kind_t
16264 An enum of all the symbols, tokens and nonterminals, of the grammar.
16265 @xref{Syntax Error Reporting Function}.  The symbol kinds are used
16266 internally by the parser, and should not be confused with the token kinds:
16267 the symbol kind of a terminal symbol is not equal to its token kind! (Unless
16268 @samp{%define api.token.raw} was used.)
16269 @end deffn
16271 @deffn {Type} yytoken_kind_t
16272 An enum of all the @dfn{token kinds} declared with @code{%token}
16273 (@pxref{Token Decl}).  These are the return values for @code{yylex}.  They
16274 should not be confused with the @emph{symbol kinds}, used internally by the
16275 parser.
16276 @end deffn
16278 @deffn {Value} YYUNDEF
16279 The token kind denoting an unknown token.
16280 @end deffn
16283 @node Glossary
16284 @appendix Glossary
16285 @cindex glossary
16287 @table @asis
16288 @item Accepting state
16289 A state whose only action is the accept action.
16290 The accepting state is thus a consistent state.
16291 @xref{Understanding}.
16293 @item Backus-Naur Form (BNF; also called ``Backus Normal Form'')
16294 Formal method of specifying context-free grammars originally proposed
16295 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
16296 committee document contributing to what became the Algol 60 report.
16297 @xref{Language and Grammar}.
16299 @item Consistent state
16300 A state containing only one possible action.  @xref{Default Reductions}.
16302 @item Context-free grammars
16303 Grammars specified as rules that can be applied regardless of context.
16304 Thus, if there is a rule which says that an integer can be used as an
16305 expression, integers are allowed @emph{anywhere} an expression is
16306 permitted.  @xref{Language and Grammar}.
16308 @item Counterexample
16309 A sequence of tokens and/or nonterminals, with one dot, that demonstrates a
16310 conflict.  The dot marks the place where the conflict occurs.
16312 @cindex unifying counterexample
16313 @cindex counterexample, unifying
16314 @cindex nonunifying counterexample
16315 @cindex counterexample, nonunifying
16316 A @emph{unifying} counterexample is a single string that has two different
16317 parses; its existence proves that the grammar is ambiguous.  When a unifying
16318 counterexample cannot be found in reasonable time, a @emph{nonunifying}
16319 counterexample is built: @emph{two} different string sharing the prefix up
16320 to the dot.
16322 @xref{Counterexamples}
16324 @item Default reduction
16325 The reduction that a parser should perform if the current parser state
16326 contains no other action for the lookahead token.  In permitted parser
16327 states, Bison declares the reduction with the largest lookahead set to be
16328 the default reduction and removes that lookahead set.  @xref{Default
16329 Reductions}.
16331 @item Defaulted state
16332 A consistent state with a default reduction.  @xref{Default Reductions}.
16334 @item Dynamic allocation
16335 Allocation of memory that occurs during execution, rather than at
16336 compile time or on entry to a function.
16338 @item Empty string
16339 Analogous to the empty set in set theory, the empty string is a
16340 character string of length zero.
16342 @item Finite-state stack machine
16343 A ``machine'' that has discrete states in which it is said to exist at
16344 each instant in time.  As input to the machine is processed, the
16345 machine moves from state to state as specified by the logic of the
16346 machine.  In the case of the parser, the input is the language being
16347 parsed, and the states correspond to various stages in the grammar
16348 rules.  @xref{Algorithm}.
16350 @item Generalized LR (GLR)
16351 A parsing algorithm that can handle all context-free grammars, including those
16352 that are not LR(1).  It resolves situations that Bison's
16353 deterministic parsing
16354 algorithm cannot by effectively splitting off multiple parsers, trying all
16355 possible parsers, and discarding those that fail in the light of additional
16356 right context.  @xref{Generalized LR Parsing}.
16358 @item Grouping
16359 A language construct that is (in general) grammatically divisible;
16360 for example, `expression' or `declaration' in C@.
16361 @xref{Language and Grammar}.
16363 @item IELR(1) (Inadequacy Elimination LR(1))
16364 A minimal LR(1) parser table construction algorithm.  That is, given any
16365 context-free grammar, IELR(1) generates parser tables with the full
16366 language-recognition power of canonical LR(1) but with nearly the same
16367 number of parser states as LALR(1).  This reduction in parser states is
16368 often an order of magnitude.  More importantly, because canonical LR(1)'s
16369 extra parser states may contain duplicate conflicts in the case of non-LR(1)
16370 grammars, the number of conflicts for IELR(1) is often an order of magnitude
16371 less as well.  This can significantly reduce the complexity of developing a
16372 grammar.  @xref{LR Table Construction}.
16374 @item Infix operator
16375 An arithmetic operator that is placed between the operands on which it
16376 performs some operation.
16378 @item Input stream
16379 A continuous flow of data between devices or programs.
16381 @item Kind
16382 ``Token'' and ``symbol'' are each overloaded to mean either a grammar symbol
16383 (kind) or all parse info (kind, value, location) associated with occurrences
16384 of that grammar symbol from the input.  To disambiguate,
16386 @itemize
16387 @item
16388 we use ``token kind'' and ``symbol kind'' to mean both grammar symbols and
16389 the values that represent them in a base programming language (C, C++,
16390 etc.).  The names of the types of these values are typically
16391 @code{token_kind_t}, or @code{token_kind_type}, or @code{TokenKind},
16392 depending on the programming language.
16394 @item
16395 we use ``token'' and ``symbol'' without the word ``kind'' to mean parsed
16396 occurrences, and we append the word ``type'' to refer to the types that
16397 represent them in a base programming language.
16398 @end itemize
16400 In summary: When you see ``kind'', interpret ``symbol'' or ``token'' to mean
16401 a @emph{grammar symbol}.  When you don't see ``kind'' (including when you
16402 see ``type''), interpret ``symbol'' or ``token'' to mean a @emph{parsed
16403 symbol}.
16405 @item LAC (Lookahead Correction)
16406 A parsing mechanism that fixes the problem of delayed syntax error
16407 detection, which is caused by LR state merging, default reductions, and the
16408 use of @code{%nonassoc}.  Delayed syntax error detection results in
16409 unexpected semantic actions, initiation of error recovery in the wrong
16410 syntactic context, and an incorrect list of expected tokens in a verbose
16411 syntax error message.  @xref{LAC}.
16413 @item Language construct
16414 One of the typical usage schemas of the language.  For example, one of
16415 the constructs of the C language is the @code{if} statement.
16416 @xref{Language and Grammar}.
16418 @item Left associativity
16419 Operators having left associativity are analyzed from left to right:
16420 @samp{a+b+c} first computes @samp{a+b} and then combines with
16421 @samp{c}.  @xref{Precedence}.
16423 @item Left recursion
16424 A rule whose result symbol is also its first component symbol; for
16425 example, @samp{expseq1 : expseq1 ',' exp;}.  @xref{Recursion}.
16427 @item Left-to-right parsing
16428 Parsing a sentence of a language by analyzing it token by token from
16429 left to right.  @xref{Algorithm}.
16431 @item Lexical analyzer (scanner)
16432 A function that reads an input stream and returns tokens one by one.
16433 @xref{Lexical}.
16435 @item Lexical tie-in
16436 A flag, set by actions in the grammar rules, which alters the way
16437 tokens are parsed.  @xref{Lexical Tie-ins}.
16439 @item Literal string token
16440 A token which consists of two or more fixed characters.  @xref{Symbols}.
16442 @item Lookahead token
16443 A token already read but not yet shifted.  @xref{Lookahead}.
16445 @item LALR(1)
16446 The class of context-free grammars that Bison (like most other parser
16447 generators) can handle by default; a subset of LR(1).
16448 @xref{Mysterious Conflicts}.
16450 @item LR(1)
16451 The class of context-free grammars in which at most one token of
16452 lookahead is needed to disambiguate the parsing of any piece of input.
16454 @item Nonterminal symbol
16455 A grammar symbol standing for a grammatical construct that can
16456 be expressed through rules in terms of smaller constructs; in other
16457 words, a construct that is not a token.  @xref{Symbols}.
16459 @item Parser
16460 A function that recognizes valid sentences of a language by analyzing
16461 the syntax structure of a set of tokens passed to it from a lexical
16462 analyzer.
16464 @item Postfix operator
16465 An arithmetic operator that is placed after the operands upon which it
16466 performs some operation.
16468 @item Reduction
16469 Replacing a string of nonterminals and/or terminals with a single
16470 nonterminal, according to a grammar rule.  @xref{Algorithm}.
16472 @item Reentrant
16473 A reentrant subprogram is a subprogram which can be in invoked any
16474 number of times in parallel, without interference between the various
16475 invocations.  @xref{Pure Decl}.
16477 @item Reverse Polish Notation
16478 A language in which all operators are postfix operators.
16480 @item Right recursion
16481 A rule whose result symbol is also its last component symbol; for
16482 example, @samp{expseq1: exp ',' expseq1;}.  @xref{Recursion}.
16484 @item Semantics
16485 In computer languages, the semantics are specified by the actions
16486 taken for each instance of the language, i.e., the meaning of
16487 each statement.  @xref{Semantics}.
16489 @item Shift
16490 A parser is said to shift when it makes the choice of analyzing
16491 further input from the stream rather than reducing immediately some
16492 already-recognized rule.  @xref{Algorithm}.
16494 @item Single-character literal
16495 A single character that is recognized and interpreted as is.
16496 @xref{Grammar in Bison}.
16498 @item Start symbol
16499 The nonterminal symbol that stands for a complete valid utterance in
16500 the language being parsed.  The start symbol is usually listed as the
16501 first nonterminal symbol in a language specification.
16502 @xref{Start Decl}.
16504 @item Symbol kind
16505 A (finite) enumeration of the grammar symbols, as processed by the parser.
16506 @xref{Symbols}.
16508 @item Symbol table
16509 A data structure where symbol names and associated data are stored during
16510 parsing to allow for recognition and use of existing information in repeated
16511 uses of a symbol.  @xref{Multi-function Calc}.
16513 @item Syntax error
16514 An error encountered during parsing of an input stream due to invalid
16515 syntax.  @xref{Error Recovery}.
16517 @item Terminal symbol
16518 A grammar symbol that has no rules in the grammar and therefore is
16519 grammatically indivisible.  The piece of text it represents is a token.
16520 @xref{Language and Grammar}.
16522 @item Token
16523 A basic, grammatically indivisible unit of a language.  The symbol that
16524 describes a token in the grammar is a terminal symbol.  The input of the
16525 Bison parser is a stream of tokens which comes from the lexical analyzer.
16526 @xref{Symbols}.
16528 @item Token kind
16529 A (finite) enumeration of the grammar terminals, as discriminated by the
16530 scanner.  @xref{Symbols}.
16532 @item Unreachable state
16533 A parser state to which there does not exist a sequence of transitions from
16534 the parser's start state.  A state can become unreachable during conflict
16535 resolution.  @xref{Unreachable States}.
16536 @end table
16538 @node GNU Free Documentation License
16539 @appendix GNU Free Documentation License
16541 @include fdl.texi
16543 @node Bibliography
16544 @unnumbered Bibliography
16546 @c Please follow the following canvas to add more references.
16547 @c And keep sorted alphabetically.
16549 @table @asis
16550 @anchor{Corbett 1984}
16551 @item [Corbett 1984]
16552 @c author
16553 Robert Paul Corbett,
16554 @c title
16555 Static Semantics in Compiler Error Recovery
16556 @c in
16557 Ph.D. Dissertation, Report No. UCB/CSD 85/251,
16558 @c where
16559 Department of Electrical Engineering and Computer Science, Compute Science
16560 Division, University of California, Berkeley, California
16561 @c when
16562 (June 1985).
16563 @c url
16564 @uref{https://digicoll.lib.berkeley.edu/record/135875}
16566 @anchor{Denny 2008}
16567 @item [Denny 2008]
16568 Joel E. Denny and Brian A. Malloy, IELR(1): Practical LR(1) Parser Tables
16569 for Non-LR(1) Grammars with Conflict Resolution, in @cite{Proceedings of the
16570 2008 ACM Symposium on Applied Computing} (SAC'08), ACM, New York, NY, USA,
16571 pp.@: 240--245.  @uref{https://dx.doi.org/10.1145/1363686.1363747}
16573 @anchor{Denny 2010 May}
16574 @item [Denny 2010 May]
16575 Joel E. Denny, PSLR(1): Pseudo-Scannerless Minimal LR(1) for the
16576 Deterministic Parsing of Composite Languages, Ph.D. Dissertation, Clemson
16577 University, Clemson, SC, USA (May 2010).
16578 @uref{https://tigerprints.clemson.edu/all_dissertations/519/}
16580 @anchor{Denny 2010 November}
16581 @item [Denny 2010 November]
16582 Joel E. Denny and Brian A. Malloy, The IELR(1) Algorithm for Generating
16583 Minimal LR(1) Parser Tables for Non-LR(1) Grammars with Conflict Resolution,
16584 in @cite{Science of Computer Programming}, Vol.@: 75, Issue 11 (November
16585 2010), pp.@: 943--979.  @uref{https://dx.doi.org/10.1016/j.scico.2009.08.001}
16587 @anchor{DeRemer 1982}
16588 @item [DeRemer 1982]
16589 Frank DeRemer and Thomas Pennello, Efficient Computation of LALR(1)
16590 Look-Ahead Sets, in @cite{ACM Transactions on Programming Languages and
16591 Systems}, Vol.@: 4, No.@: 4 (October 1982), pp.@:
16592 615--649. @uref{https://dx.doi.org/10.1145/69622.357187}
16594 @anchor{Isradisaikul 2015}
16595 @item [Isradisaikul 2015]
16596 Chinawat Isradisaikul, Andrew Myers,
16597 Finding Counterexamples from Parsing Conflicts,
16598 in @cite{Proceedings of the 36th ACM SIGPLAN Conference on
16599 Programming Language Design and Implementation} (PLDI '15),
16600 ACM, pp.@: 555--564.
16601 @uref{https://www.cs.cornell.edu/andru/papers/cupex/cupex.pdf}
16603 @anchor{Johnson 1978}
16604 @item [Johnson 1978]
16605 Steven C. Johnson,
16606 A portable compiler: theory and practice,
16607 in @cite{Proceedings of the 5th ACM SIGACT-SIGPLAN symposium on
16608 Principles of programming languages} (POPL '78),
16609 pp.@: 97--104.
16610 @uref{https://dx.doi.org/10.1145/512760.512771}.
16612 @anchor{Knuth 1965}
16613 @item [Knuth 1965]
16614 Donald E. Knuth, On the Translation of Languages from Left to Right, in
16615 @cite{Information and Control}, Vol.@: 8, Issue 6 (December 1965), pp.@:
16616 607--639. @uref{https://dx.doi.org/10.1016/S0019-9958(65)90426-2}
16618 @anchor{Scott 2000}
16619 @item [Scott 2000]
16620 Elizabeth Scott, Adrian Johnstone, and Shamsa Sadaf Hussain,
16621 @cite{Tomita-Style Generalised LR Parsers}, Royal Holloway, University of
16622 London, Department of Computer Science, TR-00-12 (December 2000).
16623 @uref{https://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps}
16624 @end table
16626 @node Index of Terms
16627 @unnumbered Index of Terms
16629 @printindex cp
16631 @bye
16633 @c LocalWords: texinfo setfilename settitle setchapternewpage finalout texi FSF
16634 @c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex FSF's
16635 @c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry Naur
16636 @c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa Multi
16637 @c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc multi
16638 @c LocalWords: rpcalc Lexer Expr ltcalc mfcalc yylex defaultprec Donnelly Gotos
16639 @c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref yypush
16640 @c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex lr
16641 @c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init POSIX ODR
16642 @c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG yypull
16643 @c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit nonfree
16644 @c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok rr
16645 @c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln Stallman Destructor
16646 @c LocalWords: symrec val tptr FUN func struct sym enum IEC syntaxes Byacc
16647 @c LocalWords: fun putsym getsym arith funs atan ptr malloc sizeof Lex pcc
16648 @c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum DOTDOT
16649 @c LocalWords: ptypes itype trigraphs yytname expseq vindex dtype Unary usr
16650 @c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs nonterminal
16651 @c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES reentrant
16652 @c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param yypstate
16653 @c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP subrange
16654 @c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword loc
16655 @c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH inline
16656 @c LocalWords: YYINITDEPTH stmts ref initdcl maybeasm notype Lookahead ctx
16657 @c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args Autoconf
16658 @c LocalWords: ypp yxx itemx tex leaderfill Troubleshouting sqrt Graphviz
16659 @c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll lookahead
16660 @c LocalWords: nbar yytext fst snd osplit ntwo strdup AST Troublereporting th
16661 @c LocalWords: YYSTACK DVI fdl printindex IELR nondeterministic nonterminals ps
16662 @c LocalWords: subexpressions declarator nondeferred config libintl postfix LAC
16663 @c LocalWords: preprocessor nonpositive unary nonnumeric typedef extern rhs sr
16664 @c LocalWords: yytokentype destructor multicharacter nonnull EBCDIC nterm LR's
16665 @c LocalWords: lvalue nonnegative XNUM CHR chr TAGLESS tagless stdout api TOK
16666 @c LocalWords: destructors Reentrancy nonreentrant subgrammar nonassociative Ph
16667 @c LocalWords: deffnx namespace xml goto lalr ielr runtime lex yacc yyps env
16668 @c LocalWords: yystate variadic Unshift NLS gettext po UTF Automake LOCALEDIR
16669 @c LocalWords: YYENABLE bindtextdomain Makefile DEFS CPPFLAGS DBISON DeRemer
16670 @c LocalWords: autoreconf Pennello multisets nondeterminism Generalised baz ACM
16671 @c LocalWords: redeclare automata Dparse localedir datadir XSLT midrule Wno
16672 @c LocalWords: multitable headitem hh basename Doxygen fno filename gdef de
16673 @c LocalWords: doxygen ival sval deftypemethod deallocate pos deftypemethodx
16674 @c LocalWords: Ctor defcv defcvx arg accessors CPP ifndef CALCXX YYerror
16675 @c LocalWords: lexer's calcxx bool LPAREN RPAREN deallocation cerrno climits
16676 @c LocalWords: cstdlib Debian undef yywrap unput noyywrap nounput zA yyleng
16677 @c LocalWords: errno strtol ERANGE str strerror iostream argc argv Javadoc PSLR
16678 @c LocalWords: bytecode initializers superclass stype ASTNode autoboxing nls
16679 @c LocalWords: toString deftypeivar deftypeivarx deftypeop YYParser strictfp
16680 @c LocalWords: superclasses boolean getErrorVerbose setErrorVerbose deftypecv
16681 @c LocalWords: getDebugStream setDebugStream getDebugLevel setDebugLevel url
16682 @c LocalWords: bisonVersion deftypecvx bisonSkeleton getStartPos getEndPos
16683 @c LocalWords: getLVal defvar deftypefn deftypefnx gotos msgfmt Corbett LALR's
16684 @c LocalWords: subdirectory Solaris nonassociativity perror schemas Malloy ints
16685 @c LocalWords: Scannerless ispell american ChangeLog smallexample CSTYPE CLTYPE
16686 @c LocalWords: clval CDEBUG cdebug deftypeopx yyterminate LocationType yyo
16687 @c LocalWords: parsers parser's documentencoding documentlanguage Wempty ss
16688 @c LocalWords: associativity subclasses precedences unresolvable runnable
16689 @c LocalWords: allocators subunit initializations unreferenced untyped dir
16690 @c LocalWords: errorVerbose subtype subtypes Wmidrule midrule's src rvalues
16691 @c LocalWords: automove evolutions Wother Wconflicts PNG lookaheads Acc sep
16692 @c LocalWords: xsltproc XSL xsl xhtml html num Wprecedence Werror fcaret gv
16693 @c LocalWords: fdiagnostics setlocale nullptr ast srcdir iff drv rgbWarning
16694 @c LocalWords: deftypefunx pragma Wnull dereference Wdocumentation elif ish
16695 @c LocalWords: Wdeprecated Wregister noinput yyloc yypos PODs sstream Wsign
16696 @c LocalWords: typename emplace Wconversion Wshorten yacchack reentrancy ou
16697 @c LocalWords: Relocatability exprs fixit Wyacc parseable fixits ffixit svg
16698 @c LocalWords: DNDEBUG cstring Wzero workalike POPL workalikes byacc UCB
16699 @c LocalWords: Penello's Penello Byson Byson's Corbett's CSD TOPLAS PDP cex
16700 @c LocalWords: Beazley's goyacc ocamlyacc SIGACT SIGPLAN colorWarning exVal
16701 @c LocalWords: setcolor rgbError colorError rgbNotice colorNotice derror
16702 @c LocalWords: colorOff maincolor inlineraw darkviolet darkcyan dwarning
16703 @c LocalWords: dnotice copyable stdint ptrdiff bufsize yyreport invariants
16704 @c LocalWords: xrefautomaticsectiontitle yysyntax yysymbol ARGMAX cond RTTI
16705 @c LocalWords: Wdangling yytoken erreur syntaxe inattendu attendait nombre
16706 @c LocalWords: YYUNDEF SymbolKind yypcontext YYENOMEM TOKENMAX getBundle
16707 @c LocalWords: ResourceBundle myResources getString getName getToken ylwrap
16708 @c LocalWords: getLocation getExpectedTokens reportSyntaxError bistromathic
16709 @c LocalWords: TokenKind Automake's rtti Wcounterexamples Chinawat PLDI buf
16710 @c LocalWords: Isradisaikul tcite pcite rgbGreen colorGreen rgbYellow Wcex
16711 @c LocalWords: colorYellow rgbRed colorRed rgbBlue colorBlue rgbPurple Ddoc
16712 @c LocalWords: colorPurple ifhtml ifnothtml situ rcex MERCHANTABILITY Wnone
16713 @c LocalWords: diagError diagNotice diagWarning diagOff danglingElseCex
16714 @c LocalWords: nonunifying YYNOMEM Wuseless dgettext textdomain domainname
16715 @c LocalWords: dirname typeof writeln YYBISON YYLOCATION backend structs
16716 @c LocalWords: pushParse
16718 @c Local Variables:
16719 @c ispell-dictionary: "american"
16720 @c fill-column: 76
16721 @c End: