1\input texinfo @c -*-texinfo-*-
2@comment %**start of header
3@setfilename bison.info
4@include version.texi
5@settitle Bison @value{VERSION}
6@setchapternewpage odd
7
8@finalout
9
10@c SMALL BOOK version
11@c This edition has been formatted so that you can format and print it in
12@c the smallbook format.
13@c @smallbook
14
15@c Set following if you want to document %default-prec and %no-default-prec.
16@c This feature is experimental and may change in future Bison versions.
17@c @set defaultprec
18
19@ifnotinfo
20@syncodeindex fn cp
21@syncodeindex vr cp
22@syncodeindex tp cp
23@end ifnotinfo
24@ifinfo
25@synindex fn cp
26@synindex vr cp
27@synindex tp cp
28@end ifinfo
29@comment %**end of header
30
31@copying
32
33This manual (@value{UPDATED}) is for GNU Bison (version
34@value{VERSION}), the GNU parser generator.
35
36Copyright @copyright{} 1988-1993, 1995, 1998-2012 Free Software
37Foundation, Inc.
38
39@quotation
40Permission is granted to copy, distribute and/or modify this document
41under the terms of the GNU Free Documentation License,
42Version 1.3 or any later version published by the Free Software
43Foundation; with no Invariant Sections, with the Front-Cover texts
44being ``A GNU Manual,'' and with the Back-Cover Texts as in
45(a) below.  A copy of the license is included in the section entitled
46``GNU Free Documentation License.''
47
48(a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
49modify this GNU manual.  Buying copies from the FSF
50supports it in developing GNU and promoting software
51freedom.''
52@end quotation
53@end copying
54
55@dircategory Software development
56@direntry
57* bison: (bison).       GNU parser generator (Yacc replacement).
58@end direntry
59
60@titlepage
61@title Bison
62@subtitle The Yacc-compatible Parser Generator
63@subtitle @value{UPDATED}, Bison Version @value{VERSION}
64
65@author by Charles Donnelly and Richard Stallman
66
67@page
68@vskip 0pt plus 1filll
69@insertcopying
70@sp 2
71Published by the Free Software Foundation @*
7251 Franklin Street, Fifth Floor @*
73Boston, MA  02110-1301  USA @*
74Printed copies are available from the Free Software Foundation.@*
75ISBN 1-882114-44-2
76@sp 2
77Cover art by Etienne Suvasa.
78@end titlepage
79
80@contents
81
82@ifnottex
83@node Top
84@top Bison
85@insertcopying
86@end ifnottex
87
88@menu
89* Introduction::
90* Conditions::
91* Copying::             The GNU General Public License says
92                          how you can copy and share Bison.
93
94Tutorial sections:
95* Concepts::            Basic concepts for understanding Bison.
96* Examples::            Three simple explained examples of using Bison.
97
98Reference sections:
99* Grammar File::        Writing Bison declarations and rules.
100* Interface::           C-language interface to the parser function @code{yyparse}.
101* Algorithm::           How the Bison parser works at run-time.
102* Error Recovery::      Writing rules for error recovery.
103* Context Dependency::  What to do if your language syntax is too
104                          messy for Bison to handle straightforwardly.
105* Debugging::           Understanding or debugging Bison parsers.
106* Invocation::          How to run Bison (to produce the parser implementation).
107* Other Languages::     Creating C++ and Java parsers.
108* FAQ::                 Frequently Asked Questions
109* Table of Symbols::    All the keywords of the Bison language are explained.
110* Glossary::            Basic concepts are explained.
111* Copying This Manual:: License for copying this manual.
112* Bibliography::        Publications cited in this manual.
113* Index of Terms::      Cross-references to the text.
114
115@detailmenu
116 --- The Detailed Node Listing ---
117
118The Concepts of Bison
119
120* Language and Grammar:: Languages and context-free grammars,
121                           as mathematical ideas.
122* Grammar in Bison::     How we represent grammars for Bison's sake.
123* Semantic Values::      Each token or syntactic grouping can have
124                           a semantic value (the value of an integer,
125                           the name of an identifier, etc.).
126* Semantic Actions::     Each rule can have an action containing C code.
127* GLR Parsers::          Writing parsers for general context-free languages.
128* Locations::            Overview of location tracking.
129* Bison Parser::         What are Bison's input and output,
130                           how is the output used?
131* Stages::               Stages in writing and running Bison grammars.
132* Grammar Layout::       Overall structure of a Bison grammar file.
133
134Writing GLR Parsers
135
136* Simple GLR Parsers::     Using GLR parsers on unambiguous grammars.
137* Merging GLR Parses::     Using GLR parsers to resolve ambiguities.
138* GLR Semantic Actions::   Deferred semantic actions have special concerns.
139* Compiler Requirements::  GLR parsers require a modern C compiler.
140
141Examples
142
143* RPN Calc::               Reverse polish notation calculator;
144                             a first example with no operator precedence.
145* Infix Calc::             Infix (algebraic) notation calculator.
146                             Operator precedence is introduced.
147* Simple Error Recovery::  Continuing after syntax errors.
148* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
149* Multi-function Calc::    Calculator with memory and trig functions.
150                             It uses multiple data-types for semantic values.
151* Exercises::              Ideas for improving the multi-function calculator.
152
153Reverse Polish Notation Calculator
154
155* Rpcalc Declarations::    Prologue (declarations) for rpcalc.
156* Rpcalc Rules::           Grammar Rules for rpcalc, with explanation.
157* Rpcalc Lexer::           The lexical analyzer.
158* Rpcalc Main::            The controlling function.
159* Rpcalc Error::           The error reporting function.
160* Rpcalc Generate::        Running Bison on the grammar file.
161* Rpcalc Compile::         Run the C compiler on the output code.
162
163Grammar Rules for @code{rpcalc}
164
165* Rpcalc Input::
166* Rpcalc Line::
167* Rpcalc Expr::
168
169Location Tracking Calculator: @code{ltcalc}
170
171* Ltcalc Declarations::    Bison and C declarations for ltcalc.
172* Ltcalc Rules::           Grammar rules for ltcalc, with explanations.
173* Ltcalc Lexer::           The lexical analyzer.
174
175Multi-Function Calculator: @code{mfcalc}
176
177* Mfcalc Declarations::    Bison declarations for multi-function calculator.
178* Mfcalc Rules::           Grammar rules for the calculator.
179* Mfcalc Symbol Table::    Symbol table management subroutines.
180
181Bison Grammar Files
182
183* Grammar Outline::    Overall layout of the grammar file.
184* Symbols::            Terminal and nonterminal symbols.
185* Rules::              How to write grammar rules.
186* Recursion::          Writing recursive rules.
187* Semantics::          Semantic values and actions.
188* Tracking Locations:: Locations and actions.
189* Named References::   Using named references in actions.
190* Declarations::       All kinds of Bison declarations are described here.
191* Multiple Parsers::   Putting more than one Bison parser in one program.
192
193Outline of a Bison Grammar
194
195* Prologue::              Syntax and usage of the prologue.
196* Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
197* Bison Declarations::    Syntax and usage of the Bison declarations section.
198* Grammar Rules::         Syntax and usage of the grammar rules section.
199* Epilogue::              Syntax and usage of the epilogue.
200
201Defining Language Semantics
202
203* Value Type::        Specifying one data type for all semantic values.
204* Multiple Types::    Specifying several alternative data types.
205* Actions::           An action is the semantic definition of a grammar rule.
206* Action Types::      Specifying data types for actions to operate on.
207* Mid-Rule Actions::  Most actions go at the end of a rule.
208                      This says when, why and how to use the exceptional
209                        action in the middle of a rule.
210
211Actions in Mid-Rule
212
213* Using Mid-Rule Actions::       Putting an action in the middle of a rule.
214* Mid-Rule Action Translation::  How mid-rule actions are actually processed.
215* Mid-Rule Conflicts::           Mid-rule actions can cause conflicts.
216
217Tracking Locations
218
219* Location Type::               Specifying a data type for locations.
220* Actions and Locations::       Using locations in actions.
221* Location Default Action::     Defining a general way to compute locations.
222
223Bison Declarations
224
225* Require Decl::      Requiring a Bison version.
226* Token Decl::        Declaring terminal symbols.
227* Precedence Decl::   Declaring terminals with precedence and associativity.
228* Union Decl::        Declaring the set of all semantic value types.
229* Type Decl::         Declaring the choice of type for a nonterminal symbol.
230* Initial Action Decl::  Code run before parsing starts.
231* Destructor Decl::   Declaring how symbols are freed.
232* Printer Decl::      Declaring how symbol values are displayed.
233* Expect Decl::       Suppressing warnings about parsing conflicts.
234* Start Decl::        Specifying the start symbol.
235* Pure Decl::         Requesting a reentrant parser.
236* Push Decl::         Requesting a push parser.
237* Decl Summary::      Table of all Bison declarations.
238* %define Summary::   Defining variables to adjust Bison's behavior.
239* %code Summary::     Inserting code into the parser source.
240
241Parser C-Language Interface
242
243* Parser Function::         How to call @code{yyparse} and what it returns.
244* Push Parser Function::    How to call @code{yypush_parse} and what it returns.
245* Pull Parser Function::    How to call @code{yypull_parse} and what it returns.
246* Parser Create Function::  How to call @code{yypstate_new} and what it returns.
247* Parser Delete Function::  How to call @code{yypstate_delete} and what it returns.
248* Lexical::                 You must supply a function @code{yylex}
249                              which reads tokens.
250* Error Reporting::         You must supply a function @code{yyerror}.
251* Action Features::         Special features for use in actions.
252* Internationalization::    How to let the parser speak in the user's
253                              native language.
254
255The Lexical Analyzer Function @code{yylex}
256
257* Calling Convention::  How @code{yyparse} calls @code{yylex}.
258* Token Values::        How @code{yylex} must return the semantic value
259                          of the token it has read.
260* Token Locations::     How @code{yylex} must return the text location
261                          (line number, etc.) of the token, if the
262                          actions want that.
263* Pure Calling::        How the calling convention differs in a pure parser
264                          (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
265
266The Bison Parser Algorithm
267
268* Lookahead::         Parser looks one token ahead when deciding what to do.
269* Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
270* Precedence::        Operator precedence works by resolving conflicts.
271* Contextual Precedence::  When an operator's precedence depends on context.
272* Parser States::     The parser is a finite-state-machine with stack.
273* Reduce/Reduce::     When two rules are applicable in the same situation.
274* Mysterious Conflicts:: Conflicts that look unjustified.
275* Tuning LR::         How to tune fundamental aspects of LR-based parsing.
276* Generalized LR Parsing::  Parsing arbitrary context-free grammars.
277* Memory Management:: What happens when memory is exhausted.  How to avoid it.
278
279Operator Precedence
280
281* Why Precedence::    An example showing why precedence is needed.
282* Using Precedence::  How to specify precedence in Bison grammars.
283* Precedence Examples::  How these features are used in the previous example.
284* How Precedence::    How they work.
285* Non Operators::     Using precedence for general conflicts.
286
287Tuning LR
288
289* LR Table Construction:: Choose a different construction algorithm.
290* Default Reductions::    Disable default reductions.
291* LAC::                   Correct lookahead sets in the parser states.
292* Unreachable States::    Keep unreachable parser states for debugging.
293
294Handling Context Dependencies
295
296* Semantic Tokens::   Token parsing can depend on the semantic context.
297* Lexical Tie-ins::   Token parsing can depend on the syntactic context.
298* Tie-in Recovery::   Lexical tie-ins have implications for how
299                        error recovery rules must be written.
300
301Debugging Your Parser
302
303* Understanding::     Understanding the structure of your parser.
304* Graphviz::          Getting a visual representation of the parser.
305* Xml::               Getting a markup representation of the parser.
306* Tracing::           Tracing the execution of your parser.
307
308Tracing Your Parser
309
310* Enabling Traces::             Activating run-time trace support
311* Mfcalc Traces::               Extending @code{mfcalc} to support traces
312* The YYPRINT Macro::           Obsolete interface for semantic value reports
313
314Invoking Bison
315
316* Bison Options::     All the options described in detail,
317                        in alphabetical order by short options.
318* Option Cross Key::  Alphabetical list of long options.
319* Yacc Library::      Yacc-compatible @code{yylex} and @code{main}.
320
321Parsers Written In Other Languages
322
323* C++ Parsers::                 The interface to generate C++ parser classes
324* Java Parsers::                The interface to generate Java parser classes
325
326C++ Parsers
327
328* C++ Bison Interface::         Asking for C++ parser generation
329* C++ Semantic Values::         %union vs. C++
330* C++ Location Values::         The position and location classes
331* C++ Parser Interface::        Instantiating and running the parser
332* C++ Scanner Interface::       Exchanges between yylex and parse
333* A Complete C++ Example::      Demonstrating their use
334
335C++ Location Values
336
337* C++ position::                One point in the source file
338* C++ location::                Two points in the source file
339* User Defined Location Type::  Required interface for locations
340
341A Complete C++ Example
342
343* Calc++ --- C++ Calculator::   The specifications
344* Calc++ Parsing Driver::       An active parsing context
345* Calc++ Parser::               A parser class
346* Calc++ Scanner::              A pure C++ Flex scanner
347* Calc++ Top Level::            Conducting the band
348
349Java Parsers
350
351* Java Bison Interface::        Asking for Java parser generation
352* Java Semantic Values::        %type and %token vs. Java
353* Java Location Values::        The position and location classes
354* Java Parser Interface::       Instantiating and running the parser
355* Java Scanner Interface::      Specifying the scanner for the parser
356* Java Action Features::        Special features for use in actions
357* Java Differences::            Differences between C/C++ and Java Grammars
358* Java Declarations Summary::   List of Bison declarations used with Java
359
360Frequently Asked Questions
361
362* Memory Exhausted::            Breaking the Stack Limits
363* How Can I Reset the Parser::  @code{yyparse} Keeps some State
364* Strings are Destroyed::       @code{yylval} Loses Track of Strings
365* Implementing Gotos/Loops::    Control Flow in the Calculator
366* Multiple start-symbols::      Factoring closely related grammars
367* Secure?  Conform?::           Is Bison POSIX safe?
368* I can't build Bison::         Troubleshooting
369* Where can I find help?::      Troubleshouting
370* Bug Reports::                 Troublereporting
371* More Languages::              Parsers in C++, Java, and so on
372* Beta Testing::                Experimenting development versions
373* Mailing Lists::               Meeting other Bison users
374
375Copying This Manual
376
377* Copying This Manual::         License for copying this manual.
378
379@end detailmenu
380@end menu
381
382@node Introduction
383@unnumbered Introduction
384@cindex introduction
385
386@dfn{Bison} is a general-purpose parser generator that converts an
387annotated context-free grammar into a deterministic LR or generalized
388LR (GLR) parser employing LALR(1) parser tables.  As an experimental
389feature, Bison can also generate IELR(1) or canonical LR(1) parser
390tables.  Once you are proficient with Bison, you can use it to develop
391a wide range of language parsers, from those used in simple desk
392calculators to complex programming languages.
393
394Bison is upward compatible with Yacc: all properly-written Yacc
395grammars ought to work with Bison with no change.  Anyone familiar
396with Yacc should be able to use Bison with little trouble.  You need
397to be fluent in C or C++ programming in order to use Bison or to
398understand this manual.  Java is also supported as an experimental
399feature.
400
401We begin with tutorial chapters that explain the basic concepts of
402using Bison and show three explained examples, each building on the
403last.  If you don't know Bison or Yacc, start by reading these
404chapters.  Reference chapters follow, which describe specific aspects
405of Bison in detail.
406
407Bison was written originally by Robert Corbett.  Richard Stallman made
408it Yacc-compatible.  Wilfred Hansen of Carnegie Mellon University
409added multi-character string literals and other features.  Since then,
410Bison has grown more robust and evolved many other new features thanks
411to the hard work of a long list of volunteers.  For details, see the
412@file{THANKS} and @file{ChangeLog} files included in the Bison
413distribution.
414
415This edition corresponds to version @value{VERSION} of Bison.
416
417@node Conditions
418@unnumbered Conditions for Using Bison
419
420The distribution terms for Bison-generated parsers permit using the
421parsers in nonfree programs.  Before Bison version 2.2, these extra
422permissions applied only when Bison was generating LALR(1)
423parsers in C@.  And before Bison version 1.24, Bison-generated
424parsers could be used only in programs that were free software.
425
426The other GNU programming tools, such as the GNU C
427compiler, have never
428had such a requirement.  They could always be used for nonfree
429software.  The reason Bison was different was not due to a special
430policy decision; it resulted from applying the usual General Public
431License to all of the Bison source code.
432
433The main output of the Bison utility---the Bison parser implementation
434file---contains a verbatim copy of a sizable piece of Bison, which is
435the code for the parser's implementation.  (The actions from your
436grammar are inserted into this implementation at one point, but most
437of the rest of the implementation is not changed.)  When we applied
438the GPL terms to the skeleton code for the parser's implementation,
439the effect was to restrict the use of Bison output to free software.
440
441We didn't change the terms because of sympathy for people who want to
442make software proprietary.  @strong{Software should be free.}  But we
443concluded that limiting Bison's use to free software was doing little to
444encourage people to make other software free.  So we decided to make the
445practical conditions for using Bison match the practical conditions for
446using the other GNU tools.
447
448This exception applies when Bison is generating code for a parser.
449You can tell whether the exception applies to a Bison output file by
450inspecting the file for text beginning with ``As a special
451exception@dots{}''.  The text spells out the exact terms of the
452exception.
453
454@node Copying
455@unnumbered GNU GENERAL PUBLIC LICENSE
456@include gpl-3.0.texi
457
458@node Concepts
459@chapter The Concepts of Bison
460
461This chapter introduces many of the basic concepts without which the
462details of Bison will not make sense.  If you do not already know how to
463use Bison or Yacc, we suggest you start by reading this chapter carefully.
464
465@menu
466* Language and Grammar:: Languages and context-free grammars,
467                           as mathematical ideas.
468* Grammar in Bison::     How we represent grammars for Bison's sake.
469* Semantic Values::      Each token or syntactic grouping can have
470                           a semantic value (the value of an integer,
471                           the name of an identifier, etc.).
472* Semantic Actions::     Each rule can have an action containing C code.
473* GLR Parsers::          Writing parsers for general context-free languages.
474* Locations::            Overview of location tracking.
475* Bison Parser::         What are Bison's input and output,
476                           how is the output used?
477* Stages::               Stages in writing and running Bison grammars.
478* Grammar Layout::       Overall structure of a Bison grammar file.
479@end menu
480
481@node Language and Grammar
482@section Languages and Context-Free Grammars
483
484@cindex context-free grammar
485@cindex grammar, context-free
486In order for Bison to parse a language, it must be described by a
487@dfn{context-free grammar}.  This means that you specify one or more
488@dfn{syntactic groupings} and give rules for constructing them from their
489parts.  For example, in the C language, one kind of grouping is called an
490`expression'.  One rule for making an expression might be, ``An expression
491can be made of a minus sign and another expression''.  Another would be,
492``An expression can be an integer''.  As you can see, rules are often
493recursive, but there must be at least one rule which leads out of the
494recursion.
495
496@cindex BNF
497@cindex Backus-Naur form
498The most common formal system for presenting such rules for humans to read
499is @dfn{Backus-Naur Form} or ``BNF'', which was developed in
500order to specify the language Algol 60.  Any grammar expressed in
501BNF is a context-free grammar.  The input to Bison is
502essentially machine-readable BNF.
503
504@cindex LALR grammars
505@cindex IELR grammars
506@cindex LR grammars
507There are various important subclasses of context-free grammars.  Although
508it can handle almost all context-free grammars, Bison is optimized for what
509are called LR(1) grammars.  In brief, in these grammars, it must be possible
510to tell how to parse any portion of an input string with just a single token
511of lookahead.  For historical reasons, Bison by default is limited by the
512additional restrictions of LALR(1), which is hard to explain simply.
513@xref{Mysterious Conflicts}, for more information on this.  As an
514experimental feature, you can escape these additional restrictions by
515requesting IELR(1) or canonical LR(1) parser tables.  @xref{LR Table
516Construction}, to learn how.
517
518@cindex GLR parsing
519@cindex generalized LR (GLR) parsing
520@cindex ambiguous grammars
521@cindex nondeterministic parsing
522
523Parsers for LR(1) grammars are @dfn{deterministic}, meaning
524roughly that the next grammar rule to apply at any point in the input is
525uniquely determined by the preceding input and a fixed, finite portion
526(called a @dfn{lookahead}) of the remaining input.  A context-free
527grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
528apply the grammar rules to get the same inputs.  Even unambiguous
529grammars can be @dfn{nondeterministic}, meaning that no fixed
530lookahead always suffices to determine the next grammar rule to apply.
531With the proper declarations, Bison is also able to parse these more
532general context-free grammars, using a technique known as GLR
533parsing (for Generalized LR).  Bison's GLR parsers
534are able to handle any context-free grammar for which the number of
535possible parses of any given string is finite.
536
537@cindex symbols (abstract)
538@cindex token
539@cindex syntactic grouping
540@cindex grouping, syntactic
541In the formal grammatical rules for a language, each kind of syntactic
542unit or grouping is named by a @dfn{symbol}.  Those which are built by
543grouping smaller constructs according to grammatical rules are called
544@dfn{nonterminal symbols}; those which can't be subdivided are called
545@dfn{terminal symbols} or @dfn{token types}.  We call a piece of input
546corresponding to a single terminal symbol a @dfn{token}, and a piece
547corresponding to a single nonterminal symbol a @dfn{grouping}.
548
549We can use the C language as an example of what symbols, terminal and
550nonterminal, mean.  The tokens of C are identifiers, constants (numeric
551and string), and the various keywords, arithmetic operators and
552punctuation marks.  So the terminal symbols of a grammar for C include
553`identifier', `number', `string', plus one symbol for each keyword,
554operator or punctuation mark: `if', `return', `const', `static', `int',
555`char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
556(These tokens can be subdivided into characters, but that is a matter of
557lexicography, not grammar.)
558
559Here is a simple C function subdivided into tokens:
560
561@example
562int             /* @r{keyword `int'} */
563square (int x)  /* @r{identifier, open-paren, keyword `int',}
564                   @r{identifier, close-paren} */
565@{               /* @r{open-brace} */
566  return x * x; /* @r{keyword `return', identifier, asterisk,}
567                   @r{identifier, semicolon} */
568@}               /* @r{close-brace} */
569@end example
570
571The syntactic groupings of C include the expression, the statement, the
572declaration, and the function definition.  These are represented in the
573grammar of C by nonterminal symbols `expression', `statement',
574`declaration' and `function definition'.  The full grammar uses dozens of
575additional language constructs, each with its own nonterminal symbol, in
576order to express the meanings of these four.  The example above is a
577function definition; it contains one declaration, and one statement.  In
578the statement, each @samp{x} is an expression and so is @samp{x * x}.
579
580Each nonterminal symbol must have grammatical rules showing how it is made
581out of simpler constructs.  For example, one kind of C statement is the
582@code{return} statement; this would be described with a grammar rule which
583reads informally as follows:
584
585@quotation
586A `statement' can be made of a `return' keyword, an `expression' and a
587`semicolon'.
588@end quotation
589
590@noindent
591There would be many other rules for `statement', one for each kind of
592statement in C.
593
594@cindex start symbol
595One nonterminal symbol must be distinguished as the special one which
596defines a complete utterance in the language.  It is called the @dfn{start
597symbol}.  In a compiler, this means a complete input program.  In the C
598language, the nonterminal symbol `sequence of definitions and declarations'
599plays this role.
600
601For example, @samp{1 + 2} is a valid C expression---a valid part of a C
602program---but it is not valid as an @emph{entire} C program.  In the
603context-free grammar of C, this follows from the fact that `expression' is
604not the start symbol.
605
606The Bison parser reads a sequence of tokens as its input, and groups the
607tokens using the grammar rules.  If the input is valid, the end result is
608that the entire token sequence reduces to a single grouping whose symbol is
609the grammar's start symbol.  If we use a grammar for C, the entire input
610must be a `sequence of definitions and declarations'.  If not, the parser
611reports a syntax error.
612
613@node Grammar in Bison
614@section From Formal Rules to Bison Input
615@cindex Bison grammar
616@cindex grammar, Bison
617@cindex formal grammar
618
619A formal grammar is a mathematical construct.  To define the language
620for Bison, you must write a file expressing the grammar in Bison syntax:
621a @dfn{Bison grammar} file.  @xref{Grammar File, ,Bison Grammar Files}.
622
623A nonterminal symbol in the formal grammar is represented in Bison input
624as an identifier, like an identifier in C@.  By convention, it should be
625in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
626
627The Bison representation for a terminal symbol is also called a @dfn{token
628type}.  Token types as well can be represented as C-like identifiers.  By
629convention, these identifiers should be upper case to distinguish them from
630nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
631@code{RETURN}.  A terminal symbol that stands for a particular keyword in
632the language should be named after that keyword converted to upper case.
633The terminal symbol @code{error} is reserved for error recovery.
634@xref{Symbols}.
635
636A terminal symbol can also be represented as a character literal, just like
637a C character constant.  You should do this whenever a token is just a
638single character (parenthesis, plus-sign, etc.): use that same character in
639a literal as the terminal symbol for that token.
640
641A third way to represent a terminal symbol is with a C string constant
642containing several characters.  @xref{Symbols}, for more information.
643
644The grammar rules also have an expression in Bison syntax.  For example,
645here is the Bison rule for a C @code{return} statement.  The semicolon in
646quotes is a literal character token, representing part of the C syntax for
647the statement; the naked semicolon, and the colon, are Bison punctuation
648used in every rule.
649
650@example
651stmt: RETURN expr ';' ;
652@end example
653
654@noindent
655@xref{Rules, ,Syntax of Grammar Rules}.
656
657@node Semantic Values
658@section Semantic Values
659@cindex semantic value
660@cindex value, semantic
661
662A formal grammar selects tokens only by their classifications: for example,
663if a rule mentions the terminal symbol `integer constant', it means that
664@emph{any} integer constant is grammatically valid in that position.  The
665precise value of the constant is irrelevant to how to parse the input: if
666@samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
667grammatical.
668
669But the precise value is very important for what the input means once it is
670parsed.  A compiler is useless if it fails to distinguish between 4, 1 and
6713989 as constants in the program!  Therefore, each token in a Bison grammar
672has both a token type and a @dfn{semantic value}.  @xref{Semantics,
673,Defining Language Semantics},
674for details.
675
676The token type is a terminal symbol defined in the grammar, such as
677@code{INTEGER}, @code{IDENTIFIER} or @code{','}.  It tells everything
678you need to know to decide where the token may validly appear and how to
679group it with other tokens.  The grammar rules know nothing about tokens
680except their types.
681
682The semantic value has all the rest of the information about the
683meaning of the token, such as the value of an integer, or the name of an
684identifier.  (A token such as @code{','} which is just punctuation doesn't
685need to have any semantic value.)
686
687For example, an input token might be classified as token type
688@code{INTEGER} and have the semantic value 4.  Another input token might
689have the same token type @code{INTEGER} but value 3989.  When a grammar
690rule says that @code{INTEGER} is allowed, either of these tokens is
691acceptable because each is an @code{INTEGER}.  When the parser accepts the
692token, it keeps track of the token's semantic value.
693
694Each grouping can also have a semantic value as well as its nonterminal
695symbol.  For example, in a calculator, an expression typically has a
696semantic value that is a number.  In a compiler for a programming
697language, an expression typically has a semantic value that is a tree
698structure describing the meaning of the expression.
699
700@node Semantic Actions
701@section Semantic Actions
702@cindex semantic actions
703@cindex actions, semantic
704
705In order to be useful, a program must do more than parse input; it must
706also produce some output based on the input.  In a Bison grammar, a grammar
707rule can have an @dfn{action} made up of C statements.  Each time the
708parser recognizes a match for that rule, the action is executed.
709@xref{Actions}.
710
711Most of the time, the purpose of an action is to compute the semantic value
712of the whole construct from the semantic values of its parts.  For example,
713suppose we have a rule which says an expression can be the sum of two
714expressions.  When the parser recognizes such a sum, each of the
715subexpressions has a semantic value which describes how it was built up.
716The action for this rule should create a similar sort of value for the
717newly recognized larger expression.
718
719For example, here is a rule that says an expression can be the sum of
720two subexpressions:
721
722@example
723expr: expr '+' expr   @{ $$ = $1 + $3; @} ;
724@end example
725
726@noindent
727The action says how to produce the semantic value of the sum expression
728from the values of the two subexpressions.
729
730@node GLR Parsers
731@section Writing GLR Parsers
732@cindex GLR parsing
733@cindex generalized LR (GLR) parsing
734@findex %glr-parser
735@cindex conflicts
736@cindex shift/reduce conflicts
737@cindex reduce/reduce conflicts
738
739In some grammars, Bison's deterministic
740LR(1) parsing algorithm cannot decide whether to apply a
741certain grammar rule at a given point.  That is, it may not be able to
742decide (on the basis of the input read so far) which of two possible
743reductions (applications of a grammar rule) applies, or whether to apply
744a reduction or read more of the input and apply a reduction later in the
745input.  These are known respectively as @dfn{reduce/reduce} conflicts
746(@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
747(@pxref{Shift/Reduce}).
748
749To use a grammar that is not easily modified to be LR(1), a
750more general parsing algorithm is sometimes necessary.  If you include
751@code{%glr-parser} among the Bison declarations in your file
752(@pxref{Grammar Outline}), the result is a Generalized LR
753(GLR) parser.  These parsers handle Bison grammars that
754contain no unresolved conflicts (i.e., after applying precedence
755declarations) identically to deterministic parsers.  However, when
756faced with unresolved shift/reduce and reduce/reduce conflicts,
757GLR parsers use the simple expedient of doing both,
758effectively cloning the parser to follow both possibilities.  Each of
759the resulting parsers can again split, so that at any given time, there
760can be any number of possible parses being explored.  The parsers
761proceed in lockstep; that is, all of them consume (shift) a given input
762symbol before any of them proceed to the next.  Each of the cloned
763parsers eventually meets one of two possible fates: either it runs into
764a parsing error, in which case it simply vanishes, or it merges with
765another parser, because the two of them have reduced the input to an
766identical set of symbols.
767
768During the time that there are multiple parsers, semantic actions are
769recorded, but not performed.  When a parser disappears, its recorded
770semantic actions disappear as well, and are never performed.  When a
771reduction makes two parsers identical, causing them to merge, Bison
772records both sets of semantic actions.  Whenever the last two parsers
773merge, reverting to the single-parser case, Bison resolves all the
774outstanding actions either by precedences given to the grammar rules
775involved, or by performing both actions, and then calling a designated
776user-defined function on the resulting values to produce an arbitrary
777merged result.
778
779@menu
780* Simple GLR Parsers::     Using GLR parsers on unambiguous grammars.
781* Merging GLR Parses::     Using GLR parsers to resolve ambiguities.
782* GLR Semantic Actions::   Deferred semantic actions have special concerns.
783* Compiler Requirements::  GLR parsers require a modern C compiler.
784@end menu
785
786@node Simple GLR Parsers
787@subsection Using GLR on Unambiguous Grammars
788@cindex GLR parsing, unambiguous grammars
789@cindex generalized LR (GLR) parsing, unambiguous grammars
790@findex %glr-parser
791@findex %expect-rr
792@cindex conflicts
793@cindex reduce/reduce conflicts
794@cindex shift/reduce conflicts
795
796In the simplest cases, you can use the GLR algorithm
797to parse grammars that are unambiguous but fail to be LR(1).
798Such grammars typically require more than one symbol of lookahead.
799
800Consider a problem that
801arises in the declaration of enumerated and subrange types in the
802programming language Pascal.  Here are some examples:
803
804@example
805type subrange = lo .. hi;
806type enum = (a, b, c);
807@end example
808
809@noindent
810The original language standard allows only numeric
811literals and constant identifiers for the subrange bounds (@samp{lo}
812and @samp{hi}), but Extended Pascal (ISO/IEC
81310206) and many other
814Pascal implementations allow arbitrary expressions there.  This gives
815rise to the following situation, containing a superfluous pair of
816parentheses:
817
818@example
819type subrange = (a) .. b;
820@end example
821
822@noindent
823Compare this to the following declaration of an enumerated
824type with only one value:
825
826@example
827type enum = (a);
828@end example
829
830@noindent
831(These declarations are contrived, but they are syntactically
832valid, and more-complicated cases can come up in practical programs.)
833
834These two declarations look identical until the @samp{..} token.
835With normal LR(1) one-token lookahead it is not
836possible to decide between the two forms when the identifier
837@samp{a} is parsed.  It is, however, desirable
838for a parser to decide this, since in the latter case
839@samp{a} must become a new identifier to represent the enumeration
840value, while in the former case @samp{a} must be evaluated with its
841current meaning, which may be a constant or even a function call.
842
843You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
844to be resolved later, but this typically requires substantial
845contortions in both semantic actions and large parts of the
846grammar, where the parentheses are nested in the recursive rules for
847expressions.
848
849You might think of using the lexer to distinguish between the two
850forms by returning different tokens for currently defined and
851undefined identifiers.  But if these declarations occur in a local
852scope, and @samp{a} is defined in an outer scope, then both forms
853are possible---either locally redefining @samp{a}, or using the
854value of @samp{a} from the outer scope.  So this approach cannot
855work.
856
857A simple solution to this problem is to declare the parser to
858use the GLR algorithm.
859When the GLR parser reaches the critical state, it
860merely splits into two branches and pursues both syntax rules
861simultaneously.  Sooner or later, one of them runs into a parsing
862error.  If there is a @samp{..} token before the next
863@samp{;}, the rule for enumerated types fails since it cannot
864accept @samp{..} anywhere; otherwise, the subrange type rule
865fails since it requires a @samp{..} token.  So one of the branches
866fails silently, and the other one continues normally, performing
867all the intermediate actions that were postponed during the split.
868
869If the input is syntactically incorrect, both branches fail and the parser
870reports a syntax error as usual.
871
872The effect of all this is that the parser seems to ``guess'' the
873correct branch to take, or in other words, it seems to use more
874lookahead than the underlying LR(1) algorithm actually allows
875for.  In this example, LR(2) would suffice, but also some cases
876that are not LR(@math{k}) for any @math{k} can be handled this way.
877
878In general, a GLR parser can take quadratic or cubic worst-case time,
879and the current Bison parser even takes exponential time and space
880for some grammars.  In practice, this rarely happens, and for many
881grammars it is possible to prove that it cannot happen.
882The present example contains only one conflict between two
883rules, and the type-declaration context containing the conflict
884cannot be nested.  So the number of
885branches that can exist at any time is limited by the constant 2,
886and the parsing time is still linear.
887
888Here is a Bison grammar corresponding to the example above.  It
889parses a vastly simplified form of Pascal type declarations.
890
891@example
892%token TYPE DOTDOT ID
893
894@group
895%left '+' '-'
896%left '*' '/'
897@end group
898
899%%
900
901@group
902type_decl: TYPE ID '=' type ';' ;
903@end group
904
905@group
906type:
907  '(' id_list ')'
908| expr DOTDOT expr
909;
910@end group
911
912@group
913id_list:
914  ID
915| id_list ',' ID
916;
917@end group
918
919@group
920expr:
921  '(' expr ')'
922| expr '+' expr
923| expr '-' expr
924| expr '*' expr
925| expr '/' expr
926| ID
927;
928@end group
929@end example
930
931When used as a normal LR(1) grammar, Bison correctly complains
932about one reduce/reduce conflict.  In the conflicting situation the
933parser chooses one of the alternatives, arbitrarily the one
934declared first.  Therefore the following correct input is not
935recognized:
936
937@example
938type t = (a) .. b;
939@end example
940
941The parser can be turned into a GLR parser, while also telling Bison
942to be silent about the one known reduce/reduce conflict, by adding
943these two declarations to the Bison grammar file (before the first
944@samp{%%}):
945
946@example
947%glr-parser
948%expect-rr 1
949@end example
950
951@noindent
952No change in the grammar itself is required.  Now the
953parser recognizes all valid declarations, according to the
954limited syntax above, transparently.  In fact, the user does not even
955notice when the parser splits.
956
957So here we have a case where we can use the benefits of GLR,
958almost without disadvantages.  Even in simple cases like this, however,
959there are at least two potential problems to beware.  First, always
960analyze the conflicts reported by Bison to make sure that GLR
961splitting is only done where it is intended.  A GLR parser
962splitting inadvertently may cause problems less obvious than an
963LR parser statically choosing the wrong alternative in a
964conflict.  Second, consider interactions with the lexer (@pxref{Semantic
965Tokens}) with great care.  Since a split parser consumes tokens without
966performing any actions during the split, the lexer cannot obtain
967information via parser actions.  Some cases of lexer interactions can be
968eliminated by using GLR to shift the complications from the
969lexer to the parser.  You must check the remaining cases for
970correctness.
971
972In our example, it would be safe for the lexer to return tokens based on
973their current meanings in some symbol table, because no new symbols are
974defined in the middle of a type declaration.  Though it is possible for
975a parser to define the enumeration constants as they are parsed, before
976the type declaration is completed, it actually makes no difference since
977they cannot be used within the same enumerated type declaration.
978
979@node Merging GLR Parses
980@subsection Using GLR to Resolve Ambiguities
981@cindex GLR parsing, ambiguous grammars
982@cindex generalized LR (GLR) parsing, ambiguous grammars
983@findex %dprec
984@findex %merge
985@cindex conflicts
986@cindex reduce/reduce conflicts
987
988Let's consider an example, vastly simplified from a C++ grammar.
989
990@example
991%@{
992  #include <stdio.h>
993  #define YYSTYPE char const *
994  int yylex (void);
995  void yyerror (char const *);
996%@}
997
998%token TYPENAME ID
999
1000%right '='
1001%left '+'
1002
1003%glr-parser
1004
1005%%
1006
1007prog:
1008  /* Nothing.  */
1009| prog stmt   @{ printf ("\n"); @}
1010;
1011
1012stmt:
1013  expr ';'  %dprec 1
1014| decl      %dprec 2
1015;
1016
1017expr:
1018  ID               @{ printf ("%s ", $$); @}
1019| TYPENAME '(' expr ')'
1020                   @{ printf ("%s <cast> ", $1); @}
1021| expr '+' expr    @{ printf ("+ "); @}
1022| expr '=' expr    @{ printf ("= "); @}
1023;
1024
1025decl:
1026  TYPENAME declarator ';'
1027                   @{ printf ("%s <declare> ", $1); @}
1028| TYPENAME declarator '=' expr ';'
1029                   @{ printf ("%s <init-declare> ", $1); @}
1030;
1031
1032declarator:
1033  ID               @{ printf ("\"%s\" ", $1); @}
1034| '(' declarator ')'
1035;
1036@end example
1037
1038@noindent
1039This models a problematic part of the C++ grammar---the ambiguity between
1040certain declarations and statements.  For example,
1041
1042@example
1043T (x) = y+z;
1044@end example
1045
1046@noindent
1047parses as either an @code{expr} or a @code{stmt}
1048(assuming that @samp{T} is recognized as a @code{TYPENAME} and
1049@samp{x} as an @code{ID}).
1050Bison detects this as a reduce/reduce conflict between the rules
1051@code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
1052time it encounters @code{x} in the example above.  Since this is a
1053GLR parser, it therefore splits the problem into two parses, one for
1054each choice of resolving the reduce/reduce conflict.
1055Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1056however, neither of these parses ``dies,'' because the grammar as it stands is
1057ambiguous.  One of the parsers eventually reduces @code{stmt : expr ';'} and
1058the other reduces @code{stmt : decl}, after which both parsers are in an
1059identical state: they've seen @samp{prog stmt} and have the same unprocessed
1060input remaining.  We say that these parses have @dfn{merged.}
1061
1062At this point, the GLR parser requires a specification in the
1063grammar of how to choose between the competing parses.
1064In the example above, the two @code{%dprec}
1065declarations specify that Bison is to give precedence
1066to the parse that interprets the example as a
1067@code{decl}, which implies that @code{x} is a declarator.
1068The parser therefore prints
1069
1070@example
1071"x" y z + T <init-declare>
1072@end example
1073
1074The @code{%dprec} declarations only come into play when more than one
1075parse survives.  Consider a different input string for this parser:
1076
1077@example
1078T (x) + y;
1079@end example
1080
1081@noindent
1082This is another example of using GLR to parse an unambiguous
1083construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
1084Here, there is no ambiguity (this cannot be parsed as a declaration).
1085However, at the time the Bison parser encounters @code{x}, it does not
1086have enough information to resolve the reduce/reduce conflict (again,
1087between @code{x} as an @code{expr} or a @code{declarator}).  In this
1088case, no precedence declaration is used.  Again, the parser splits
1089into two, one assuming that @code{x} is an @code{expr}, and the other
1090assuming @code{x} is a @code{declarator}.  The second of these parsers
1091then vanishes when it sees @code{+}, and the parser prints
1092
1093@example
1094x T <cast> y +
1095@end example
1096
1097Suppose that instead of resolving the ambiguity, you wanted to see all
1098the possibilities.  For this purpose, you must merge the semantic
1099actions of the two possible parsers, rather than choosing one over the
1100other.  To do so, you could change the declaration of @code{stmt} as
1101follows:
1102
1103@example
1104stmt:
1105  expr ';'  %merge <stmtMerge>
1106| decl      %merge <stmtMerge>
1107;
1108@end example
1109
1110@noindent
1111and define the @code{stmtMerge} function as:
1112
1113@example
1114static YYSTYPE
1115stmtMerge (YYSTYPE x0, YYSTYPE x1)
1116@{
1117  printf ("<OR> ");
1118  return "";
1119@}
1120@end example
1121
1122@noindent
1123with an accompanying forward declaration
1124in the C declarations at the beginning of the file:
1125
1126@example
1127%@{
1128  #define YYSTYPE char const *
1129  static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
1130%@}
1131@end example
1132
1133@noindent
1134With these declarations, the resulting parser parses the first example
1135as both an @code{expr} and a @code{decl}, and prints
1136
1137@example
1138"x" y z + T <init-declare> x T <cast> y z + = <OR>
1139@end example
1140
1141Bison requires that all of the
1142productions that participate in any particular merge have identical
1143@samp{%merge} clauses.  Otherwise, the ambiguity would be unresolvable,
1144and the parser will report an error during any parse that results in
1145the offending merge.
1146
1147@node GLR Semantic Actions
1148@subsection GLR Semantic Actions
1149
1150@cindex deferred semantic actions
1151By definition, a deferred semantic action is not performed at the same time as
1152the associated reduction.
1153This raises caveats for several Bison features you might use in a semantic
1154action in a GLR parser.
1155
1156@vindex yychar
1157@cindex GLR parsers and @code{yychar}
1158@vindex yylval
1159@cindex GLR parsers and @code{yylval}
1160@vindex yylloc
1161@cindex GLR parsers and @code{yylloc}
1162In any semantic action, you can examine @code{yychar} to determine the type of
1163the lookahead token present at the time of the associated reduction.
1164After checking that @code{yychar} is not set to @code{YYEMPTY} or @code{YYEOF},
1165you can then examine @code{yylval} and @code{yylloc} to determine the
1166lookahead token's semantic value and location, if any.
1167In a nondeferred semantic action, you can also modify any of these variables to
1168influence syntax analysis.
1169@xref{Lookahead, ,Lookahead Tokens}.
1170
1171@findex yyclearin
1172@cindex GLR parsers and @code{yyclearin}
1173In a deferred semantic action, it's too late to influence syntax analysis.
1174In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1175shallow copies of the values they had at the time of the associated reduction.
1176For this reason alone, modifying them is dangerous.
1177Moreover, the result of modifying them is undefined and subject to change with
1178future versions of Bison.
1179For example, if a semantic action might be deferred, you should never write it
1180to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1181memory referenced by @code{yylval}.
1182
1183@findex YYERROR
1184@cindex GLR parsers and @code{YYERROR}
1185Another Bison feature requiring special consideration is @code{YYERROR}
1186(@pxref{Action Features}), which you can invoke in a semantic action to
1187initiate error recovery.
1188During deterministic GLR operation, the effect of @code{YYERROR} is
1189the same as its effect in a deterministic parser.
1190In a deferred semantic action, its effect is undefined.
1191@c The effect is probably a syntax error at the split point.
1192
1193Also, see @ref{Location Default Action, ,Default Action for Locations}, which
1194describes a special usage of @code{YYLLOC_DEFAULT} in GLR parsers.
1195
1196@node Compiler Requirements
1197@subsection Considerations when Compiling GLR Parsers
1198@cindex @code{inline}
1199@cindex GLR parsers and @code{inline}
1200
1201The GLR parsers require a compiler for ISO C89 or
1202later.  In addition, they use the @code{inline} keyword, which is not
1203C89, but is C99 and is a common extension in pre-C99 compilers.  It is
1204up to the user of these parsers to handle
1205portability issues.  For instance, if using Autoconf and the Autoconf
1206macro @code{AC_C_INLINE}, a mere
1207
1208@example
1209%@{
1210  #include <config.h>
1211%@}
1212@end example
1213
1214@noindent
1215will suffice.  Otherwise, we suggest
1216
1217@example
1218%@{
1219  #if (__STDC_VERSION__ < 199901 && ! defined __GNUC__ \
1220       && ! defined inline)
1221  # define inline
1222  #endif
1223%@}
1224@end example
1225
1226@node Locations
1227@section Locations
1228@cindex location
1229@cindex textual location
1230@cindex location, textual
1231
1232Many applications, like interpreters or compilers, have to produce verbose
1233and useful error messages.  To achieve this, one must be able to keep track of
1234the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
1235Bison provides a mechanism for handling these locations.
1236
1237Each token has a semantic value.  In a similar fashion, each token has an
1238associated location, but the type of locations is the same for all tokens
1239and groupings.  Moreover, the output parser is equipped with a default data
1240structure for storing locations (@pxref{Tracking Locations}, for more
1241details).
1242
1243Like semantic values, locations can be reached in actions using a dedicated
1244set of constructs.  In the example above, the location of the whole grouping
1245is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1246@code{@@3}.
1247
1248When a rule is matched, a default action is used to compute the semantic value
1249of its left hand side (@pxref{Actions}).  In the same way, another default
1250action is used for locations.  However, the action for locations is general
1251enough for most cases, meaning there is usually no need to describe for each
1252rule how @code{@@$} should be formed.  When building a new location for a given
1253grouping, the default behavior of the output parser is to take the beginning
1254of the first symbol, and the end of the last symbol.
1255
1256@node Bison Parser
1257@section Bison Output: the Parser Implementation File
1258@cindex Bison parser
1259@cindex Bison utility
1260@cindex lexical analyzer, purpose
1261@cindex parser
1262
1263When you run Bison, you give it a Bison grammar file as input.  The
1264most important output is a C source file that implements a parser for
1265the language described by the grammar.  This parser is called a
1266@dfn{Bison parser}, and this file is called a @dfn{Bison parser
1267implementation file}.  Keep in mind that the Bison utility and the
1268Bison parser are two distinct programs: the Bison utility is a program
1269whose output is the Bison parser implementation file that becomes part
1270of your program.
1271
1272The job of the Bison parser is to group tokens into groupings according to
1273the grammar rules---for example, to build identifiers and operators into
1274expressions.  As it does this, it runs the actions for the grammar rules it
1275uses.
1276
1277The tokens come from a function called the @dfn{lexical analyzer} that
1278you must supply in some fashion (such as by writing it in C).  The Bison
1279parser calls the lexical analyzer each time it wants a new token.  It
1280doesn't know what is ``inside'' the tokens (though their semantic values
1281may reflect this).  Typically the lexical analyzer makes the tokens by
1282parsing characters of text, but Bison does not depend on this.
1283@xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
1284
1285The Bison parser implementation file is C code which defines a
1286function named @code{yyparse} which implements that grammar.  This
1287function does not make a complete C program: you must supply some
1288additional functions.  One is the lexical analyzer.  Another is an
1289error-reporting function which the parser calls to report an error.
1290In addition, a complete C program must start with a function called
1291@code{main}; you have to provide this, and arrange for it to call
1292@code{yyparse} or the parser will never run.  @xref{Interface, ,Parser
1293C-Language Interface}.
1294
1295Aside from the token type names and the symbols in the actions you
1296write, all symbols defined in the Bison parser implementation file
1297itself begin with @samp{yy} or @samp{YY}.  This includes interface
1298functions such as the lexical analyzer function @code{yylex}, the
1299error reporting function @code{yyerror} and the parser function
1300@code{yyparse} itself.  This also includes numerous identifiers used
1301for internal purposes.  Therefore, you should avoid using C
1302identifiers starting with @samp{yy} or @samp{YY} in the Bison grammar
1303file except for the ones defined in this manual.  Also, you should
1304avoid using the C identifiers @samp{malloc} and @samp{free} for
1305anything other than their usual meanings.
1306
1307In some cases the Bison parser implementation file includes system
1308headers, and in those cases your code should respect the identifiers
1309reserved by those headers.  On some non-GNU hosts, @code{<alloca.h>},
1310@code{<malloc.h>}, @code{<stddef.h>}, and @code{<stdlib.h>} are
1311included as needed to declare memory allocators and related types.
1312@code{<libintl.h>} is included if message translation is in use
1313(@pxref{Internationalization}).  Other system headers may be included
1314if you define @code{YYDEBUG} to a nonzero value (@pxref{Tracing,
1315,Tracing Your Parser}).
1316
1317@node Stages
1318@section Stages in Using Bison
1319@cindex stages in using Bison
1320@cindex using Bison
1321
1322The actual language-design process using Bison, from grammar specification
1323to a working compiler or interpreter, has these parts:
1324
1325@enumerate
1326@item
1327Formally specify the grammar in a form recognized by Bison
1328(@pxref{Grammar File, ,Bison Grammar Files}).  For each grammatical rule
1329in the language, describe the action that is to be taken when an
1330instance of that rule is recognized.  The action is described by a
1331sequence of C statements.
1332
1333@item
1334Write a lexical analyzer to process input and pass tokens to the parser.
1335The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
1336Lexical Analyzer Function @code{yylex}}).  It could also be produced
1337using Lex, but the use of Lex is not discussed in this manual.
1338
1339@item
1340Write a controlling function that calls the Bison-produced parser.
1341
1342@item
1343Write error-reporting routines.
1344@end enumerate
1345
1346To turn this source code as written into a runnable program, you
1347must follow these steps:
1348
1349@enumerate
1350@item
1351Run Bison on the grammar to produce the parser.
1352
1353@item
1354Compile the code output by Bison, as well as any other source files.
1355
1356@item
1357Link the object files to produce the finished product.
1358@end enumerate
1359
1360@node Grammar Layout
1361@section The Overall Layout of a Bison Grammar
1362@cindex grammar file
1363@cindex file format
1364@cindex format of grammar file
1365@cindex layout of Bison grammar
1366
1367The input file for the Bison utility is a @dfn{Bison grammar file}.  The
1368general form of a Bison grammar file is as follows:
1369
1370@example
1371%@{
1372@var{Prologue}
1373%@}
1374
1375@var{Bison declarations}
1376
1377%%
1378@var{Grammar rules}
1379%%
1380@var{Epilogue}
1381@end example
1382
1383@noindent
1384The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1385in every Bison grammar file to separate the sections.
1386
1387The prologue may define types and variables used in the actions.  You can
1388also use preprocessor commands to define macros used there, and use
1389@code{#include} to include header files that do any of these things.
1390You need to declare the lexical analyzer @code{yylex} and the error
1391printer @code{yyerror} here, along with any other global identifiers
1392used by the actions in the grammar rules.
1393
1394The Bison declarations declare the names of the terminal and nonterminal
1395symbols, and may also describe operator precedence and the data types of
1396semantic values of various symbols.
1397
1398The grammar rules define how to construct each nonterminal symbol from its
1399parts.
1400
1401The epilogue can contain any code you want to use.  Often the
1402definitions of functions declared in the prologue go here.  In a
1403simple program, all the rest of the program can go here.
1404
1405@node Examples
1406@chapter Examples
1407@cindex simple examples
1408@cindex examples, simple
1409
1410Now we show and explain several sample programs written using Bison: a
1411reverse polish notation calculator, an algebraic (infix) notation
1412calculator --- later extended to track ``locations'' ---
1413and a multi-function calculator.  All
1414produce usable, though limited, interactive desk-top calculators.
1415
1416These examples are simple, but Bison grammars for real programming
1417languages are written the same way.  You can copy these examples into a
1418source file to try them.
1419
1420@menu
1421* RPN Calc::               Reverse polish notation calculator;
1422                             a first example with no operator precedence.
1423* Infix Calc::             Infix (algebraic) notation calculator.
1424                             Operator precedence is introduced.
1425* Simple Error Recovery::  Continuing after syntax errors.
1426* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1427* Multi-function Calc::    Calculator with memory and trig functions.
1428                             It uses multiple data-types for semantic values.
1429* Exercises::              Ideas for improving the multi-function calculator.
1430@end menu
1431
1432@node RPN Calc
1433@section Reverse Polish Notation Calculator
1434@cindex reverse polish notation
1435@cindex polish notation calculator
1436@cindex @code{rpcalc}
1437@cindex calculator, simple
1438
1439The first example is that of a simple double-precision @dfn{reverse polish
1440notation} calculator (a calculator using postfix operators).  This example
1441provides a good starting point, since operator precedence is not an issue.
1442The second example will illustrate how operator precedence is handled.
1443
1444The source code for this calculator is named @file{rpcalc.y}.  The
1445@samp{.y} extension is a convention used for Bison grammar files.
1446
1447@menu
1448* Rpcalc Declarations::    Prologue (declarations) for rpcalc.
1449* Rpcalc Rules::           Grammar Rules for rpcalc, with explanation.
1450* Rpcalc Lexer::           The lexical analyzer.
1451* Rpcalc Main::            The controlling function.
1452* Rpcalc Error::           The error reporting function.
1453* Rpcalc Generate::        Running Bison on the grammar file.
1454* Rpcalc Compile::         Run the C compiler on the output code.
1455@end menu
1456
1457@node Rpcalc Declarations
1458@subsection Declarations for @code{rpcalc}
1459
1460Here are the C and Bison declarations for the reverse polish notation
1461calculator.  As in C, comments are placed between @samp{/*@dots{}*/}.
1462
1463@example
1464/* Reverse polish notation calculator.  */
1465
1466%@{
1467  #define YYSTYPE double
1468  #include <math.h>
1469  int yylex (void);
1470  void yyerror (char const *);
1471%@}
1472
1473%token NUM
1474
1475%% /* Grammar rules and actions follow.  */
1476@end example
1477
1478The declarations section (@pxref{Prologue, , The prologue}) contains two
1479preprocessor directives and two forward declarations.
1480
1481The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1482specifying the C data type for semantic values of both tokens and
1483groupings (@pxref{Value Type, ,Data Types of Semantic Values}).  The
1484Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1485don't define it, @code{int} is the default.  Because we specify
1486@code{double}, each token and each expression has an associated value,
1487which is a floating point number.
1488
1489The @code{#include} directive is used to declare the exponentiation
1490function @code{pow}.
1491
1492The forward declarations for @code{yylex} and @code{yyerror} are
1493needed because the C language requires that functions be declared
1494before they are used.  These functions will be defined in the
1495epilogue, but the parser calls them so they must be declared in the
1496prologue.
1497
1498The second section, Bison declarations, provides information to Bison
1499about the token types (@pxref{Bison Declarations, ,The Bison
1500Declarations Section}).  Each terminal symbol that is not a
1501single-character literal must be declared here.  (Single-character
1502literals normally don't need to be declared.)  In this example, all the
1503arithmetic operators are designated by single-character literals, so the
1504only terminal symbol that needs to be declared is @code{NUM}, the token
1505type for numeric constants.
1506
1507@node Rpcalc Rules
1508@subsection Grammar Rules for @code{rpcalc}
1509
1510Here are the grammar rules for the reverse polish notation calculator.
1511
1512@example
1513@group
1514input:
1515  /* empty */
1516| input line
1517;
1518@end group
1519
1520@group
1521line:
1522  '\n'
1523| exp '\n'      @{ printf ("%.10g\n", $1); @}
1524;
1525@end group
1526
1527@group
1528exp:
1529  NUM           @{ $$ = $1;           @}
1530| exp exp '+'   @{ $$ = $1 + $2;      @}
1531| exp exp '-'   @{ $$ = $1 - $2;      @}
1532| exp exp '*'   @{ $$ = $1 * $2;      @}
1533| exp exp '/'   @{ $$ = $1 / $2;      @}
1534| exp exp '^'   @{ $$ = pow ($1, $2); @}  /* Exponentiation */
1535| exp 'n'       @{ $$ = -$1;          @}  /* Unary minus    */
1536;
1537@end group
1538%%
1539@end example
1540
1541The groupings of the rpcalc ``language'' defined here are the expression
1542(given the name @code{exp}), the line of input (@code{line}), and the
1543complete input transcript (@code{input}).  Each of these nonterminal
1544symbols has several alternate rules, joined by the vertical bar @samp{|}
1545which is read as ``or''.  The following sections explain what these rules
1546mean.
1547
1548The semantics of the language is determined by the actions taken when a
1549grouping is recognized.  The actions are the C code that appears inside
1550braces.  @xref{Actions}.
1551
1552You must specify these actions in C, but Bison provides the means for
1553passing semantic values between the rules.  In each action, the
1554pseudo-variable @code{$$} stands for the semantic value for the grouping
1555that the rule is going to construct.  Assigning a value to @code{$$} is the
1556main job of most actions.  The semantic values of the components of the
1557rule are referred to as @code{$1}, @code{$2}, and so on.
1558
1559@menu
1560* Rpcalc Input::
1561* Rpcalc Line::
1562* Rpcalc Expr::
1563@end menu
1564
1565@node Rpcalc Input
1566@subsubsection Explanation of @code{input}
1567
1568Consider the definition of @code{input}:
1569
1570@example
1571input:
1572  /* empty */
1573| input line
1574;
1575@end example
1576
1577This definition reads as follows: ``A complete input is either an empty
1578string, or a complete input followed by an input line''.  Notice that
1579``complete input'' is defined in terms of itself.  This definition is said
1580to be @dfn{left recursive} since @code{input} appears always as the
1581leftmost symbol in the sequence.  @xref{Recursion, ,Recursive Rules}.
1582
1583The first alternative is empty because there are no symbols between the
1584colon and the first @samp{|}; this means that @code{input} can match an
1585empty string of input (no tokens).  We write the rules this way because it
1586is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1587It's conventional to put an empty alternative first and write the comment
1588@samp{/* empty */} in it.
1589
1590The second alternate rule (@code{input line}) handles all nontrivial input.
1591It means, ``After reading any number of lines, read one more line if
1592possible.''  The left recursion makes this rule into a loop.  Since the
1593first alternative matches empty input, the loop can be executed zero or
1594more times.
1595
1596The parser function @code{yyparse} continues to process input until a
1597grammatical error is seen or the lexical analyzer says there are no more
1598input tokens; we will arrange for the latter to happen at end-of-input.
1599
1600@node Rpcalc Line
1601@subsubsection Explanation of @code{line}
1602
1603Now consider the definition of @code{line}:
1604
1605@example
1606line:
1607  '\n'
1608| exp '\n'  @{ printf ("%.10g\n", $1); @}
1609;
1610@end example
1611
1612The first alternative is a token which is a newline character; this means
1613that rpcalc accepts a blank line (and ignores it, since there is no
1614action).  The second alternative is an expression followed by a newline.
1615This is the alternative that makes rpcalc useful.  The semantic value of
1616the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1617question is the first symbol in the alternative.  The action prints this
1618value, which is the result of the computation the user asked for.
1619
1620This action is unusual because it does not assign a value to @code{$$}.  As
1621a consequence, the semantic value associated with the @code{line} is
1622uninitialized (its value will be unpredictable).  This would be a bug if
1623that value were ever used, but we don't use it: once rpcalc has printed the
1624value of the user's input line, that value is no longer needed.
1625
1626@node Rpcalc Expr
1627@subsubsection Explanation of @code{expr}
1628
1629The @code{exp} grouping has several rules, one for each kind of expression.
1630The first rule handles the simplest expressions: those that are just numbers.
1631The second handles an addition-expression, which looks like two expressions
1632followed by a plus-sign.  The third handles subtraction, and so on.
1633
1634@example
1635exp:
1636  NUM
1637| exp exp '+'     @{ $$ = $1 + $2;    @}
1638| exp exp '-'     @{ $$ = $1 - $2;    @}
1639@dots{}
1640;
1641@end example
1642
1643We have used @samp{|} to join all the rules for @code{exp}, but we could
1644equally well have written them separately:
1645
1646@example
1647exp: NUM ;
1648exp: exp exp '+'     @{ $$ = $1 + $2; @};
1649exp: exp exp '-'     @{ $$ = $1 - $2; @};
1650@dots{}
1651@end example
1652
1653Most of the rules have actions that compute the value of the expression in
1654terms of the value of its parts.  For example, in the rule for addition,
1655@code{$1} refers to the first component @code{exp} and @code{$2} refers to
1656the second one.  The third component, @code{'+'}, has no meaningful
1657associated semantic value, but if it had one you could refer to it as
1658@code{$3}.  When @code{yyparse} recognizes a sum expression using this
1659rule, the sum of the two subexpressions' values is produced as the value of
1660the entire expression.  @xref{Actions}.
1661
1662You don't have to give an action for every rule.  When a rule has no
1663action, Bison by default copies the value of @code{$1} into @code{$$}.
1664This is what happens in the first rule (the one that uses @code{NUM}).
1665
1666The formatting shown here is the recommended convention, but Bison does
1667not require it.  You can add or change white space as much as you wish.
1668For example, this:
1669
1670@example
1671exp: NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
1672@end example
1673
1674@noindent
1675means the same thing as this:
1676
1677@example
1678exp:
1679  NUM
1680| exp exp '+'    @{ $$ = $1 + $2; @}
1681| @dots{}
1682;
1683@end example
1684
1685@noindent
1686The latter, however, is much more readable.
1687
1688@node Rpcalc Lexer
1689@subsection The @code{rpcalc} Lexical Analyzer
1690@cindex writing a lexical analyzer
1691@cindex lexical analyzer, writing
1692
1693The lexical analyzer's job is low-level parsing: converting characters
1694or sequences of characters into tokens.  The Bison parser gets its
1695tokens by calling the lexical analyzer.  @xref{Lexical, ,The Lexical
1696Analyzer Function @code{yylex}}.
1697
1698Only a simple lexical analyzer is needed for the RPN
1699calculator.  This
1700lexical analyzer skips blanks and tabs, then reads in numbers as
1701@code{double} and returns them as @code{NUM} tokens.  Any other character
1702that isn't part of a number is a separate token.  Note that the token-code
1703for such a single-character token is the character itself.
1704
1705The return value of the lexical analyzer function is a numeric code which
1706represents a token type.  The same text used in Bison rules to stand for
1707this token type is also a C expression for the numeric code for the type.
1708This works in two ways.  If the token type is a character literal, then its
1709numeric code is that of the character; you can use the same
1710character literal in the lexical analyzer to express the number.  If the
1711token type is an identifier, that identifier is defined by Bison as a C
1712macro whose definition is the appropriate number.  In this example,
1713therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1714
1715The semantic value of the token (if it has one) is stored into the
1716global variable @code{yylval}, which is where the Bison parser will look
1717for it.  (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1718defined at the beginning of the grammar; @pxref{Rpcalc Declarations,
1719,Declarations for @code{rpcalc}}.)
1720
1721A token type code of zero is returned if the end-of-input is encountered.
1722(Bison recognizes any nonpositive value as indicating end-of-input.)
1723
1724Here is the code for the lexical analyzer:
1725
1726@example
1727@group
1728/* The lexical analyzer returns a double floating point
1729   number on the stack and the token NUM, or the numeric code
1730   of the character read if not a number.  It skips all blanks
1731   and tabs, and returns 0 for end-of-input.  */
1732
1733#include <ctype.h>
1734@end group
1735
1736@group
1737int
1738yylex (void)
1739@{
1740  int c;
1741
1742  /* Skip white space.  */
1743  while ((c = getchar ()) == ' ' || c == '\t')
1744    continue;
1745@end group
1746@group
1747  /* Process numbers.  */
1748  if (c == '.' || isdigit (c))
1749    @{
1750      ungetc (c, stdin);
1751      scanf ("%lf", &yylval);
1752      return NUM;
1753    @}
1754@end group
1755@group
1756  /* Return end-of-input.  */
1757  if (c == EOF)
1758    return 0;
1759  /* Return a single char.  */
1760  return c;
1761@}
1762@end group
1763@end example
1764
1765@node Rpcalc Main
1766@subsection The Controlling Function
1767@cindex controlling function
1768@cindex main function in simple example
1769
1770In keeping with the spirit of this example, the controlling function is
1771kept to the bare minimum.  The only requirement is that it call
1772@code{yyparse} to start the process of parsing.
1773
1774@example
1775@group
1776int
1777main (void)
1778@{
1779  return yyparse ();
1780@}
1781@end group
1782@end example
1783
1784@node Rpcalc Error
1785@subsection The Error Reporting Routine
1786@cindex error reporting routine
1787
1788When @code{yyparse} detects a syntax error, it calls the error reporting
1789function @code{yyerror} to print an error message (usually but not
1790always @code{"syntax error"}).  It is up to the programmer to supply
1791@code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1792here is the definition we will use:
1793
1794@example
1795@group
1796#include <stdio.h>
1797@end group
1798
1799@group
1800/* Called by yyparse on error.  */
1801void
1802yyerror (char const *s)
1803@{
1804  fprintf (stderr, "%s\n", s);
1805@}
1806@end group
1807@end example
1808
1809After @code{yyerror} returns, the Bison parser may recover from the error
1810and continue parsing if the grammar contains a suitable error rule
1811(@pxref{Error Recovery}).  Otherwise, @code{yyparse} returns nonzero.  We
1812have not written any error rules in this example, so any invalid input will
1813cause the calculator program to exit.  This is not clean behavior for a
1814real calculator, but it is adequate for the first example.
1815
1816@node Rpcalc Generate
1817@subsection Running Bison to Make the Parser
1818@cindex running Bison (introduction)
1819
1820Before running Bison to produce a parser, we need to decide how to
1821arrange all the source code in one or more source files.  For such a
1822simple example, the easiest thing is to put everything in one file,
1823the grammar file.  The definitions of @code{yylex}, @code{yyerror} and
1824@code{main} go at the end, in the epilogue of the grammar file
1825(@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1826
1827For a large project, you would probably have several source files, and use
1828@code{make} to arrange to recompile them.
1829
1830With all the source in the grammar file, you use the following command
1831to convert it into a parser implementation file:
1832
1833@example
1834bison @var{file}.y
1835@end example
1836
1837@noindent
1838In this example, the grammar file is called @file{rpcalc.y} (for
1839``Reverse Polish @sc{calc}ulator'').  Bison produces a parser
1840implementation file named @file{@var{file}.tab.c}, removing the
1841@samp{.y} from the grammar file name.  The parser implementation file
1842contains the source code for @code{yyparse}.  The additional functions
1843in the grammar file (@code{yylex}, @code{yyerror} and @code{main}) are
1844copied verbatim to the parser implementation file.
1845
1846@node Rpcalc Compile
1847@subsection Compiling the Parser Implementation File
1848@cindex compiling the parser
1849
1850Here is how to compile and run the parser implementation file:
1851
1852@example
1853@group
1854# @r{List files in current directory.}
1855$ @kbd{ls}
1856rpcalc.tab.c  rpcalc.y
1857@end group
1858
1859@group
1860# @r{Compile the Bison parser.}
1861# @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1862$ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
1863@end group
1864
1865@group
1866# @r{List files again.}
1867$ @kbd{ls}
1868rpcalc  rpcalc.tab.c  rpcalc.y
1869@end group
1870@end example
1871
1872The file @file{rpcalc} now contains the executable code.  Here is an
1873example session using @code{rpcalc}.
1874
1875@example
1876$ @kbd{rpcalc}
1877@kbd{4 9 +}
187813
1879@kbd{3 7 + 3 4 5 *+-}
1880-13
1881@kbd{3 7 + 3 4 5 * + - n}              @r{Note the unary minus, @samp{n}}
188213
1883@kbd{5 6 / 4 n +}
1884-3.166666667
1885@kbd{3 4 ^}                            @r{Exponentiation}
188681
1887@kbd{^D}                               @r{End-of-file indicator}
1888$
1889@end example
1890
1891@node Infix Calc
1892@section Infix Notation Calculator: @code{calc}
1893@cindex infix notation calculator
1894@cindex @code{calc}
1895@cindex calculator, infix notation
1896
1897We now modify rpcalc to handle infix operators instead of postfix.  Infix
1898notation involves the concept of operator precedence and the need for
1899parentheses nested to arbitrary depth.  Here is the Bison code for
1900@file{calc.y}, an infix desk-top calculator.
1901
1902@example
1903/* Infix notation calculator.  */
1904
1905@group
1906%@{
1907  #define YYSTYPE double
1908  #include <math.h>
1909  #include <stdio.h>
1910  int yylex (void);
1911  void yyerror (char const *);
1912%@}
1913@end group
1914
1915@group
1916/* Bison declarations.  */
1917%token NUM
1918%left '-' '+'
1919%left '*' '/'
1920%left NEG     /* negation--unary minus */
1921%right '^'    /* exponentiation */
1922@end group
1923
1924%% /* The grammar follows.  */
1925@group
1926input:
1927  /* empty */
1928| input line
1929;
1930@end group
1931
1932@group
1933line:
1934  '\n'
1935| exp '\n'  @{ printf ("\t%.10g\n", $1); @}
1936;
1937@end group
1938
1939@group
1940exp:
1941  NUM                @{ $$ = $1;           @}
1942| exp '+' exp        @{ $$ = $1 + $3;      @}
1943| exp '-' exp        @{ $$ = $1 - $3;      @}
1944| exp '*' exp        @{ $$ = $1 * $3;      @}
1945| exp '/' exp        @{ $$ = $1 / $3;      @}
1946| '-' exp  %prec NEG @{ $$ = -$2;          @}
1947| exp '^' exp        @{ $$ = pow ($1, $3); @}
1948| '(' exp ')'        @{ $$ = $2;           @}
1949;
1950@end group
1951%%
1952@end example
1953
1954@noindent
1955The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1956same as before.
1957
1958There are two important new features shown in this code.
1959
1960In the second section (Bison declarations), @code{%left} declares token
1961types and says they are left-associative operators.  The declarations
1962@code{%left} and @code{%right} (right associativity) take the place of
1963@code{%token} which is used to declare a token type name without
1964associativity.  (These tokens are single-character literals, which
1965ordinarily don't need to be declared.  We declare them here to specify
1966the associativity.)
1967
1968Operator precedence is determined by the line ordering of the
1969declarations; the higher the line number of the declaration (lower on
1970the page or screen), the higher the precedence.  Hence, exponentiation
1971has the highest precedence, unary minus (@code{NEG}) is next, followed
1972by @samp{*} and @samp{/}, and so on.  @xref{Precedence, ,Operator
1973Precedence}.
1974
1975The other important new feature is the @code{%prec} in the grammar
1976section for the unary minus operator.  The @code{%prec} simply instructs
1977Bison that the rule @samp{| '-' exp} has the same precedence as
1978@code{NEG}---in this case the next-to-highest.  @xref{Contextual
1979Precedence, ,Context-Dependent Precedence}.
1980
1981Here is a sample run of @file{calc.y}:
1982
1983@need 500
1984@example
1985$ @kbd{calc}
1986@kbd{4 + 4.5 - (34/(8*3+-3))}
19876.880952381
1988@kbd{-56 + 2}
1989-54
1990@kbd{3 ^ 2}
19919
1992@end example
1993
1994@node Simple Error Recovery
1995@section Simple Error Recovery
1996@cindex error recovery, simple
1997
1998Up to this point, this manual has not addressed the issue of @dfn{error
1999recovery}---how to continue parsing after the parser detects a syntax
2000error.  All we have handled is error reporting with @code{yyerror}.
2001Recall that by default @code{yyparse} returns after calling
2002@code{yyerror}.  This means that an erroneous input line causes the
2003calculator program to exit.  Now we show how to rectify this deficiency.
2004
2005The Bison language itself includes the reserved word @code{error}, which
2006may be included in the grammar rules.  In the example below it has
2007been added to one of the alternatives for @code{line}:
2008
2009@example
2010@group
2011line:
2012  '\n'
2013| exp '\n'   @{ printf ("\t%.10g\n", $1); @}
2014| error '\n' @{ yyerrok;                  @}
2015;
2016@end group
2017@end example
2018
2019This addition to the grammar allows for simple error recovery in the
2020event of a syntax error.  If an expression that cannot be evaluated is
2021read, the error will be recognized by the third rule for @code{line},
2022and parsing will continue.  (The @code{yyerror} function is still called
2023upon to print its message as well.)  The action executes the statement
2024@code{yyerrok}, a macro defined automatically by Bison; its meaning is
2025that error recovery is complete (@pxref{Error Recovery}).  Note the
2026difference between @code{yyerrok} and @code{yyerror}; neither one is a
2027misprint.
2028
2029This form of error recovery deals with syntax errors.  There are other
2030kinds of errors; for example, division by zero, which raises an exception
2031signal that is normally fatal.  A real calculator program must handle this
2032signal and use @code{longjmp} to return to @code{main} and resume parsing
2033input lines; it would also have to discard the rest of the current line of
2034input.  We won't discuss this issue further because it is not specific to
2035Bison programs.
2036
2037@node Location Tracking Calc
2038@section Location Tracking Calculator: @code{ltcalc}
2039@cindex location tracking calculator
2040@cindex @code{ltcalc}
2041@cindex calculator, location tracking
2042
2043This example extends the infix notation calculator with location
2044tracking.  This feature will be used to improve the error messages.  For
2045the sake of clarity, this example is a simple integer calculator, since
2046most of the work needed to use locations will be done in the lexical
2047analyzer.
2048
2049@menu
2050* Ltcalc Declarations::    Bison and C declarations for ltcalc.
2051* Ltcalc Rules::           Grammar rules for ltcalc, with explanations.
2052* Ltcalc Lexer::           The lexical analyzer.
2053@end menu
2054
2055@node Ltcalc Declarations
2056@subsection Declarations for @code{ltcalc}
2057
2058The C and Bison declarations for the location tracking calculator are
2059the same as the declarations for the infix notation calculator.
2060
2061@example
2062/* Location tracking calculator.  */
2063
2064%@{
2065  #define YYSTYPE int
2066  #include <math.h>
2067  int yylex (void);
2068  void yyerror (char const *);
2069%@}
2070
2071/* Bison declarations.  */
2072%token NUM
2073
2074%left '-' '+'
2075%left '*' '/'
2076%left NEG
2077%right '^'
2078
2079%% /* The grammar follows.  */
2080@end example
2081
2082@noindent
2083Note there are no declarations specific to locations.  Defining a data
2084type for storing locations is not needed: we will use the type provided
2085by default (@pxref{Location Type, ,Data Types of Locations}), which is a
2086four member structure with the following integer fields:
2087@code{first_line}, @code{first_column}, @code{last_line} and
2088@code{last_column}.  By conventions, and in accordance with the GNU
2089Coding Standards and common practice, the line and column count both
2090start at 1.
2091
2092@node Ltcalc Rules
2093@subsection Grammar Rules for @code{ltcalc}
2094
2095Whether handling locations or not has no effect on the syntax of your
2096language.  Therefore, grammar rules for this example will be very close
2097to those of the previous example: we will only modify them to benefit
2098from the new information.
2099
2100Here, we will use locations to report divisions by zero, and locate the
2101wrong expressions or subexpressions.
2102
2103@example
2104@group
2105input:
2106  /* empty */
2107| input line
2108;
2109@end group
2110
2111@group
2112line:
2113  '\n'
2114| exp '\n' @{ printf ("%d\n", $1); @}
2115;
2116@end group
2117
2118@group
2119exp:
2120  NUM           @{ $$ = $1; @}
2121| exp '+' exp   @{ $$ = $1 + $3; @}
2122| exp '-' exp   @{ $$ = $1 - $3; @}
2123| exp '*' exp   @{ $$ = $1 * $3; @}
2124@end group
2125@group
2126| exp '/' exp
2127    @{
2128      if ($3)
2129        $$ = $1 / $3;
2130      else
2131        @{
2132          $$ = 1;
2133          fprintf (stderr, "%d.%d-%d.%d: division by zero",
2134                   @@3.first_line, @@3.first_column,
2135                   @@3.last_line, @@3.last_column);
2136        @}
2137    @}
2138@end group
2139@group
2140| '-' exp %prec NEG     @{ $$ = -$2; @}
2141| exp '^' exp           @{ $$ = pow ($1, $3); @}
2142| '(' exp ')'           @{ $$ = $2; @}
2143@end group
2144@end example
2145
2146This code shows how to reach locations inside of semantic actions, by
2147using the pseudo-variables @code{@@@var{n}} for rule components, and the
2148pseudo-variable @code{@@$} for groupings.
2149
2150We don't need to assign a value to @code{@@$}: the output parser does it
2151automatically.  By default, before executing the C code of each action,
2152@code{@@$} is set to range from the beginning of @code{@@1} to the end
2153of @code{@@@var{n}}, for a rule with @var{n} components.  This behavior
2154can be redefined (@pxref{Location Default Action, , Default Action for
2155Locations}), and for very specific rules, @code{@@$} can be computed by
2156hand.
2157
2158@node Ltcalc Lexer
2159@subsection The @code{ltcalc} Lexical Analyzer.
2160
2161Until now, we relied on Bison's defaults to enable location
2162tracking.  The next step is to rewrite the lexical analyzer, and make it
2163able to feed the parser with the token locations, as it already does for
2164semantic values.
2165
2166To this end, we must take into account every single character of the
2167input text, to avoid the computed locations of being fuzzy or wrong:
2168
2169@example
2170@group
2171int
2172yylex (void)
2173@{
2174  int c;
2175@end group
2176
2177@group
2178  /* Skip white space.  */
2179  while ((c = getchar ()) == ' ' || c == '\t')
2180    ++yylloc.last_column;
2181@end group
2182
2183@group
2184  /* Step.  */
2185  yylloc.first_line = yylloc.last_line;
2186  yylloc.first_column = yylloc.last_column;
2187@end group
2188
2189@group
2190  /* Process numbers.  */
2191  if (isdigit (c))
2192    @{
2193      yylval = c - '0';
2194      ++yylloc.last_column;
2195      while (isdigit (c = getchar ()))
2196        @{
2197          ++yylloc.last_column;
2198          yylval = yylval * 10 + c - '0';
2199        @}
2200      ungetc (c, stdin);
2201      return NUM;
2202    @}
2203@end group
2204
2205  /* Return end-of-input.  */
2206  if (c == EOF)
2207    return 0;
2208
2209@group
2210  /* Return a single char, and update location.  */
2211  if (c == '\n')
2212    @{
2213      ++yylloc.last_line;
2214      yylloc.last_column = 0;
2215    @}
2216  else
2217    ++yylloc.last_column;
2218  return c;
2219@}
2220@end group
2221@end example
2222
2223Basically, the lexical analyzer performs the same processing as before:
2224it skips blanks and tabs, and reads numbers or single-character tokens.
2225In addition, it updates @code{yylloc}, the global variable (of type
2226@code{YYLTYPE}) containing the token's location.
2227
2228Now, each time this function returns a token, the parser has its number
2229as well as its semantic value, and its location in the text.  The last
2230needed change is to initialize @code{yylloc}, for example in the
2231controlling function:
2232
2233@example
2234@group
2235int
2236main (void)
2237@{
2238  yylloc.first_line = yylloc.last_line = 1;
2239  yylloc.first_column = yylloc.last_column = 0;
2240  return yyparse ();
2241@}
2242@end group
2243@end example
2244
2245Remember that computing locations is not a matter of syntax.  Every
2246character must be associated to a location update, whether it is in
2247valid input, in comments, in literal strings, and so on.
2248
2249@node Multi-function Calc
2250@section Multi-Function Calculator: @code{mfcalc}
2251@cindex multi-function calculator
2252@cindex @code{mfcalc}
2253@cindex calculator, multi-function
2254
2255Now that the basics of Bison have been discussed, it is time to move on to
2256a more advanced problem.  The above calculators provided only five
2257functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}.  It would
2258be nice to have a calculator that provides other mathematical functions such
2259as @code{sin}, @code{cos}, etc.
2260
2261It is easy to add new operators to the infix calculator as long as they are
2262only single-character literals.  The lexical analyzer @code{yylex} passes
2263back all nonnumeric characters as tokens, so new grammar rules suffice for
2264adding a new operator.  But we want something more flexible: built-in
2265functions whose syntax has this form:
2266
2267@example
2268@var{function_name} (@var{argument})
2269@end example
2270
2271@noindent
2272At the same time, we will add memory to the calculator, by allowing you
2273to create named variables, store values in them, and use them later.
2274Here is a sample session with the multi-function calculator:
2275
2276@example
2277$ @kbd{mfcalc}
2278@kbd{pi = 3.141592653589}
22793.1415926536
2280@kbd{sin(pi)}
22810.0000000000
2282@kbd{alpha = beta1 = 2.3}
22832.3000000000
2284@kbd{alpha}
22852.3000000000
2286@kbd{ln(alpha)}
22870.8329091229
2288@kbd{exp(ln(beta1))}
22892.3000000000
2290$
2291@end example
2292
2293Note that multiple assignment and nested function calls are permitted.
2294
2295@menu
2296* Mfcalc Declarations::    Bison declarations for multi-function calculator.
2297* Mfcalc Rules::           Grammar rules for the calculator.
2298* Mfcalc Symbol Table::    Symbol table management subroutines.
2299@end menu
2300
2301@node Mfcalc Declarations
2302@subsection Declarations for @code{mfcalc}
2303
2304Here are the C and Bison declarations for the multi-function calculator.
2305
2306@comment file: mfcalc.y: 1
2307@example
2308@group
2309%@{
2310  #include <math.h>  /* For math functions, cos(), sin(), etc.  */
2311  #include "calc.h"  /* Contains definition of `symrec'.  */
2312  int yylex (void);
2313  void yyerror (char const *);
2314%@}
2315@end group
2316
2317@group
2318%union @{
2319  double    val;   /* For returning numbers.  */
2320  symrec  *tptr;   /* For returning symbol-table pointers.  */
2321@}
2322@end group
2323%token <val>  NUM        /* Simple double precision number.  */
2324%token <tptr> VAR FNCT   /* Variable and function.  */
2325%type  <val>  exp
2326
2327@group
2328%right '='
2329%left '-' '+'
2330%left '*' '/'
2331%left NEG     /* negation--unary minus */
2332%right '^'    /* exponentiation */
2333@end group
2334@end example
2335
2336The above grammar introduces only two new features of the Bison language.
2337These features allow semantic values to have various data types
2338(@pxref{Multiple Types, ,More Than One Value Type}).
2339
2340The @code{%union} declaration specifies the entire list of possible types;
2341this is instead of defining @code{YYSTYPE}.  The allowable types are now
2342double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
2343the symbol table.  @xref{Union Decl, ,The Collection of Value Types}.
2344
2345Since values can now have various types, it is necessary to associate a
2346type with each grammar symbol whose semantic value is used.  These symbols
2347are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}.  Their
2348declarations are augmented with information about their data type (placed
2349between angle brackets).
2350
2351The Bison construct @code{%type} is used for declaring nonterminal
2352symbols, just as @code{%token} is used for declaring token types.  We
2353have not used @code{%type} before because nonterminal symbols are
2354normally declared implicitly by the rules that define them.  But
2355@code{exp} must be declared explicitly so we can specify its value type.
2356@xref{Type Decl, ,Nonterminal Symbols}.
2357
2358@node Mfcalc Rules
2359@subsection Grammar Rules for @code{mfcalc}
2360
2361Here are the grammar rules for the multi-function calculator.
2362Most of them are copied directly from @code{calc}; three rules,
2363those which mention @code{VAR} or @code{FNCT}, are new.
2364
2365@comment file: mfcalc.y: 3
2366@example
2367%% /* The grammar follows.  */
2368@group
2369input:
2370  /* empty */
2371| input line
2372;
2373@end group
2374
2375@group
2376line:
2377  '\n'
2378| exp '\n'   @{ printf ("%.10g\n", $1); @}
2379| error '\n' @{ yyerrok;                @}
2380;
2381@end group
2382
2383@group
2384exp:
2385  NUM                @{ $$ = $1;                         @}
2386| VAR                @{ $$ = $1->value.var;              @}
2387| VAR '=' exp        @{ $$ = $3; $1->value.var = $3;     @}
2388| FNCT '(' exp ')'   @{ $$ = (*($1->value.fnctptr))($3); @}
2389| exp '+' exp        @{ $$ = $1 + $3;                    @}
2390| exp '-' exp        @{ $$ = $1 - $3;                    @}
2391| exp '*' exp        @{ $$ = $1 * $3;                    @}
2392| exp '/' exp        @{ $$ = $1 / $3;                    @}
2393| '-' exp  %prec NEG @{ $$ = -$2;                        @}
2394| exp '^' exp        @{ $$ = pow ($1, $3);               @}
2395| '(' exp ')'        @{ $$ = $2;                         @}
2396;
2397@end group
2398/* End of grammar.  */
2399%%
2400@end example
2401
2402@node Mfcalc Symbol Table
2403@subsection The @code{mfcalc} Symbol Table
2404@cindex symbol table example
2405
2406The multi-function calculator requires a symbol table to keep track of the
2407names and meanings of variables and functions.  This doesn't affect the
2408grammar rules (except for the actions) or the Bison declarations, but it
2409requires some additional C functions for support.
2410
2411The symbol table itself consists of a linked list of records.  Its
2412definition, which is kept in the header @file{calc.h}, is as follows.  It
2413provides for either functions or variables to be placed in the table.
2414
2415@comment file: calc.h
2416@example
2417@group
2418/* Function type.  */
2419typedef double (*func_t) (double);
2420@end group
2421
2422@group
2423/* Data type for links in the chain of symbols.  */
2424struct symrec
2425@{
2426  char *name;  /* name of symbol */
2427  int type;    /* type of symbol: either VAR or FNCT */
2428  union
2429  @{
2430    double var;      /* value of a VAR */
2431    func_t fnctptr;  /* value of a FNCT */
2432  @} value;
2433  struct symrec *next;  /* link field */
2434@};
2435@end group
2436
2437@group
2438typedef struct symrec symrec;
2439
2440/* The symbol table: a chain of `struct symrec'.  */
2441extern symrec *sym_table;
2442
2443symrec *putsym (char const *, int);
2444symrec *getsym (char const *);
2445@end group
2446@end example
2447
2448The new version of @code{main} includes a call to @code{init_table}, a
2449function that initializes the symbol table.  Here it is, and
2450@code{init_table} as well:
2451
2452@comment file: mfcalc.y: 3
2453@example
2454#include <stdio.h>
2455
2456@group
2457/* Called by yyparse on error.  */
2458void
2459yyerror (char const *s)
2460@{
2461  fprintf (stderr, "%s\n", s);
2462@}
2463@end group
2464
2465@group
2466struct init
2467@{
2468  char const *fname;
2469  double (*fnct) (double);
2470@};
2471@end group
2472
2473@group
2474struct init const arith_fncts[] =
2475@{
2476  "sin",  sin,
2477  "cos",  cos,
2478  "atan", atan,
2479  "ln",   log,
2480  "exp",  exp,
2481  "sqrt", sqrt,
2482  0, 0
2483@};
2484@end group
2485
2486@group
2487/* The symbol table: a chain of `struct symrec'.  */
2488symrec *sym_table;
2489@end group
2490
2491@group
2492/* Put arithmetic functions in table.  */
2493void
2494init_table (void)
2495@{
2496  int i;
2497  for (i = 0; arith_fncts[i].fname != 0; i++)
2498    @{
2499      symrec *ptr = putsym (arith_fncts[i].fname, FNCT);
2500      ptr->value.fnctptr = arith_fncts[i].fnct;
2501    @}
2502@}
2503@end group
2504
2505@group
2506int
2507main (void)
2508@{
2509  init_table ();
2510  return yyparse ();
2511@}
2512@end group
2513@end example
2514
2515By simply editing the initialization list and adding the necessary include
2516files, you can add additional functions to the calculator.
2517
2518Two important functions allow look-up and installation of symbols in the
2519symbol table.  The function @code{putsym} is passed a name and the type
2520(@code{VAR} or @code{FNCT}) of the object to be installed.  The object is
2521linked to the front of the list, and a pointer to the object is returned.
2522The function @code{getsym} is passed the name of the symbol to look up.  If
2523found, a pointer to that symbol is returned; otherwise zero is returned.
2524
2525@comment file: mfcalc.y: 3
2526@example
2527#include <stdlib.h> /* malloc. */
2528#include <string.h> /* strlen. */
2529
2530@group
2531symrec *
2532putsym (char const *sym_name, int sym_type)
2533@{
2534  symrec *ptr = (symrec *) malloc (sizeof (symrec));
2535  ptr->name = (char *) malloc (strlen (sym_name) + 1);
2536  strcpy (ptr->name,sym_name);
2537  ptr->type = sym_type;
2538  ptr->value.var = 0; /* Set value to 0 even if fctn.  */
2539  ptr->next = (struct symrec *)sym_table;
2540  sym_table = ptr;
2541  return ptr;
2542@}
2543@end group
2544
2545@group
2546symrec *
2547getsym (char const *sym_name)
2548@{
2549  symrec *ptr;
2550  for (ptr = sym_table; ptr != (symrec *) 0;
2551       ptr = (symrec *)ptr->next)
2552    if (strcmp (ptr->name,sym_name) == 0)
2553      return ptr;
2554  return 0;
2555@}
2556@end group
2557@end example
2558
2559The function @code{yylex} must now recognize variables, numeric values, and
2560the single-character arithmetic operators.  Strings of alphanumeric
2561characters with a leading letter are recognized as either variables or
2562functions depending on what the symbol table says about them.
2563
2564The string is passed to @code{getsym} for look up in the symbol table.  If
2565the name appears in the table, a pointer to its location and its type
2566(@code{VAR} or @code{FNCT}) is returned to @code{yyparse}.  If it is not
2567already in the table, then it is installed as a @code{VAR} using
2568@code{putsym}.  Again, a pointer and its type (which must be @code{VAR}) is
2569returned to @code{yyparse}.
2570
2571No change is needed in the handling of numeric values and arithmetic
2572operators in @code{yylex}.
2573
2574@comment file: mfcalc.y: 3
2575@example
2576@group
2577#include <ctype.h>
2578@end group
2579
2580@group
2581int
2582yylex (void)
2583@{
2584  int c;
2585
2586  /* Ignore white space, get first nonwhite character.  */
2587  while ((c = getchar ()) == ' ' || c == '\t')
2588    continue;
2589
2590  if (c == EOF)
2591    return 0;
2592@end group
2593
2594@group
2595  /* Char starts a number => parse the number.         */
2596  if (c == '.' || isdigit (c))
2597    @{
2598      ungetc (c, stdin);
2599      scanf ("%lf", &yylval.val);
2600      return NUM;
2601    @}
2602@end group
2603
2604@group
2605  /* Char starts an identifier => read the name.       */
2606  if (isalpha (c))
2607    @{
2608      /* Initially make the buffer long enough
2609         for a 40-character symbol name.  */
2610      static size_t length = 40;
2611      static char *symbuf = 0;
2612      symrec *s;
2613      int i;
2614@end group
2615
2616      if (!symbuf)
2617        symbuf = (char *) malloc (length + 1);
2618
2619      i = 0;
2620      do
2621@group
2622        @{
2623          /* If buffer is full, make it bigger.        */
2624          if (i == length)
2625            @{
2626              length *= 2;
2627              symbuf = (char *) realloc (symbuf, length + 1);
2628            @}
2629          /* Add this character to the buffer.         */
2630          symbuf[i++] = c;
2631          /* Get another character.                    */
2632          c = getchar ();
2633        @}
2634@end group
2635@group
2636      while (isalnum (c));
2637
2638      ungetc (c, stdin);
2639      symbuf[i] = '\0';
2640@end group
2641
2642@group
2643      s = getsym (symbuf);
2644      if (s == 0)
2645        s = putsym (symbuf, VAR);
2646      yylval.tptr = s;
2647      return s->type;
2648    @}
2649
2650  /* Any other character is a token by itself.        */
2651  return c;
2652@}
2653@end group
2654@end example
2655
2656The error reporting function is unchanged, and the new version of
2657@code{main} includes a call to @code{init_table} and sets the @code{yydebug}
2658on user demand (@xref{Tracing, , Tracing Your Parser}, for details):
2659
2660@comment file: mfcalc.y: 3
2661@example
2662@group
2663/* Called by yyparse on error.  */
2664void
2665yyerror (char const *s)
2666@{
2667  fprintf (stderr, "%s\n", s);
2668@}
2669@end group
2670
2671@group
2672int
2673main (int argc, char const* argv[])
2674@{
2675  int i;
2676  /* Enable parse traces on option -p.  */
2677  for (i = 1; i < argc; ++i)
2678    if (!strcmp(argv[i], "-p"))
2679      yydebug = 1;
2680  init_table ();
2681  return yyparse ();
2682@}
2683@end group
2684@end example
2685
2686This program is both powerful and flexible.  You may easily add new
2687functions, and it is a simple job to modify this code to install
2688predefined variables such as @code{pi} or @code{e} as well.
2689
2690@node Exercises
2691@section Exercises
2692@cindex exercises
2693
2694@enumerate
2695@item
2696Add some new functions from @file{math.h} to the initialization list.
2697
2698@item
2699Add another array that contains constants and their values.  Then
2700modify @code{init_table} to add these constants to the symbol table.
2701It will be easiest to give the constants type @code{VAR}.
2702
2703@item
2704Make the program report an error if the user refers to an
2705uninitialized variable in any way except to store a value in it.
2706@end enumerate
2707
2708@node Grammar File
2709@chapter Bison Grammar Files
2710
2711Bison takes as input a context-free grammar specification and produces a
2712C-language function that recognizes correct instances of the grammar.
2713
2714The Bison grammar file conventionally has a name ending in @samp{.y}.
2715@xref{Invocation, ,Invoking Bison}.
2716
2717@menu
2718* Grammar Outline::    Overall layout of the grammar file.
2719* Symbols::            Terminal and nonterminal symbols.
2720* Rules::              How to write grammar rules.
2721* Recursion::          Writing recursive rules.
2722* Semantics::          Semantic values and actions.
2723* Tracking Locations:: Locations and actions.
2724* Named References::   Using named references in actions.
2725* Declarations::       All kinds of Bison declarations are described here.
2726* Multiple Parsers::   Putting more than one Bison parser in one program.
2727@end menu
2728
2729@node Grammar Outline
2730@section Outline of a Bison Grammar
2731@cindex comment
2732@findex // @dots{}
2733@findex /* @dots{} */
2734
2735A Bison grammar file has four main sections, shown here with the
2736appropriate delimiters:
2737
2738@example
2739%@{
2740  @var{Prologue}
2741%@}
2742
2743@var{Bison declarations}
2744
2745%%
2746@var{Grammar rules}
2747%%
2748
2749@var{Epilogue}
2750@end example
2751
2752Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2753As a GNU extension, @samp{//} introduces a comment that continues until end
2754of line.
2755
2756@menu
2757* Prologue::              Syntax and usage of the prologue.
2758* Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
2759* Bison Declarations::    Syntax and usage of the Bison declarations section.
2760* Grammar Rules::         Syntax and usage of the grammar rules section.
2761* Epilogue::              Syntax and usage of the epilogue.
2762@end menu
2763
2764@node Prologue
2765@subsection The prologue
2766@cindex declarations section
2767@cindex Prologue
2768@cindex declarations
2769
2770The @var{Prologue} section contains macro definitions and declarations
2771of functions and variables that are used in the actions in the grammar
2772rules.  These are copied to the beginning of the parser implementation
2773file so that they precede the definition of @code{yyparse}.  You can
2774use @samp{#include} to get the declarations from a header file.  If
2775you don't need any C declarations, you may omit the @samp{%@{} and
2776@samp{%@}} delimiters that bracket this section.
2777
2778The @var{Prologue} section is terminated by the first occurrence
2779of @samp{%@}} that is outside a comment, a string literal, or a
2780character constant.
2781
2782You may have more than one @var{Prologue} section, intermixed with the
2783@var{Bison declarations}.  This allows you to have C and Bison
2784declarations that refer to each other.  For example, the @code{%union}
2785declaration may use types defined in a header file, and you may wish to
2786prototype functions that take arguments of type @code{YYSTYPE}.  This
2787can be done with two @var{Prologue} blocks, one before and one after the
2788@code{%union} declaration.
2789
2790@example
2791%@{
2792  #define _GNU_SOURCE
2793  #include <stdio.h>
2794  #include "ptypes.h"
2795%@}
2796
2797%union @{
2798  long int n;
2799  tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2800@}
2801
2802%@{
2803  static void print_token_value (FILE *, int, YYSTYPE);
2804  #define YYPRINT(F, N, L) print_token_value (F, N, L)
2805%@}
2806
2807@dots{}
2808@end example
2809
2810When in doubt, it is usually safer to put prologue code before all
2811Bison declarations, rather than after.  For example, any definitions
2812of feature test macros like @code{_GNU_SOURCE} or
2813@code{_POSIX_C_SOURCE} should appear before all Bison declarations, as
2814feature test macros can affect the behavior of Bison-generated
2815@code{#include} directives.
2816
2817@node Prologue Alternatives
2818@subsection Prologue Alternatives
2819@cindex Prologue Alternatives
2820
2821@findex %code
2822@findex %code requires
2823@findex %code provides
2824@findex %code top
2825
2826The functionality of @var{Prologue} sections can often be subtle and
2827inflexible.  As an alternative, Bison provides a @code{%code}
2828directive with an explicit qualifier field, which identifies the
2829purpose of the code and thus the location(s) where Bison should
2830generate it.  For C/C++, the qualifier can be omitted for the default
2831location, or it can be one of @code{requires}, @code{provides},
2832@code{top}.  @xref{%code Summary}.
2833
2834Look again at the example of the previous section:
2835
2836@example
2837%@{
2838  #define _GNU_SOURCE
2839  #include <stdio.h>
2840  #include "ptypes.h"
2841%@}
2842
2843%union @{
2844  long int n;
2845  tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2846@}
2847
2848%@{
2849  static void print_token_value (FILE *, int, YYSTYPE);
2850  #define YYPRINT(F, N, L) print_token_value (F, N, L)
2851%@}
2852
2853@dots{}
2854@end example
2855
2856@noindent
2857Notice that there are two @var{Prologue} sections here, but there's a
2858subtle distinction between their functionality.  For example, if you
2859decide to override Bison's default definition for @code{YYLTYPE}, in
2860which @var{Prologue} section should you write your new definition?
2861You should write it in the first since Bison will insert that code
2862into the parser implementation file @emph{before} the default
2863@code{YYLTYPE} definition.  In which @var{Prologue} section should you
2864prototype an internal function, @code{trace_token}, that accepts
2865@code{YYLTYPE} and @code{yytokentype} as arguments?  You should
2866prototype it in the second since Bison will insert that code
2867@emph{after} the @code{YYLTYPE} and @code{yytokentype} definitions.
2868
2869This distinction in functionality between the two @var{Prologue} sections is
2870established by the appearance of the @code{%union} between them.
2871This behavior raises a few questions.
2872First, why should the position of a @code{%union} affect definitions related to
2873@code{YYLTYPE} and @code{yytokentype}?
2874Second, what if there is no @code{%union}?
2875In that case, the second kind of @var{Prologue} section is not available.
2876This behavior is not intuitive.
2877
2878To avoid this subtle @code{%union} dependency, rewrite the example using a
2879@code{%code top} and an unqualified @code{%code}.
2880Let's go ahead and add the new @code{YYLTYPE} definition and the
2881@code{trace_token} prototype at the same time:
2882
2883@example
2884%code top @{
2885  #define _GNU_SOURCE
2886  #include <stdio.h>
2887
2888  /* WARNING: The following code really belongs
2889   * in a `%code requires'; see below.  */
2890
2891  #include "ptypes.h"
2892  #define YYLTYPE YYLTYPE
2893  typedef struct YYLTYPE
2894  @{
2895    int first_line;
2896    int first_column;
2897    int last_line;
2898    int last_column;
2899    char *filename;
2900  @} YYLTYPE;
2901@}
2902
2903%union @{
2904  long int n;
2905  tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2906@}
2907
2908%code @{
2909  static void print_token_value (FILE *, int, YYSTYPE);
2910  #define YYPRINT(F, N, L) print_token_value (F, N, L)
2911  static void trace_token (enum yytokentype token, YYLTYPE loc);
2912@}
2913
2914@dots{}
2915@end example
2916
2917@noindent
2918In this way, @code{%code top} and the unqualified @code{%code} achieve the same
2919functionality as the two kinds of @var{Prologue} sections, but it's always
2920explicit which kind you intend.
2921Moreover, both kinds are always available even in the absence of @code{%union}.
2922
2923The @code{%code top} block above logically contains two parts.  The
2924first two lines before the warning need to appear near the top of the
2925parser implementation file.  The first line after the warning is
2926required by @code{YYSTYPE} and thus also needs to appear in the parser
2927implementation file.  However, if you've instructed Bison to generate
2928a parser header file (@pxref{Decl Summary, ,%defines}), you probably
2929want that line to appear before the @code{YYSTYPE} definition in that
2930header file as well.  The @code{YYLTYPE} definition should also appear
2931in the parser header file to override the default @code{YYLTYPE}
2932definition there.
2933
2934In other words, in the @code{%code top} block above, all but the first two
2935lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
2936definitions.
2937Thus, they belong in one or more @code{%code requires}:
2938
2939@example
2940@group
2941%code top @{
2942  #define _GNU_SOURCE
2943  #include <stdio.h>
2944@}
2945@end group
2946
2947@group
2948%code requires @{
2949  #include "ptypes.h"
2950@}
2951@end group
2952@group
2953%union @{
2954  long int n;
2955  tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2956@}
2957@end group
2958
2959@group
2960%code requires @{
2961  #define YYLTYPE YYLTYPE
2962  typedef struct YYLTYPE
2963  @{
2964    int first_line;
2965    int first_column;
2966    int last_line;
2967    int last_column;
2968    char *filename;
2969  @} YYLTYPE;
2970@}
2971@end group
2972
2973@group
2974%code @{
2975  static void print_token_value (FILE *, int, YYSTYPE);
2976  #define YYPRINT(F, N, L) print_token_value (F, N, L)
2977  static void trace_token (enum yytokentype token, YYLTYPE loc);
2978@}
2979@end group
2980
2981@dots{}
2982@end example
2983
2984@noindent
2985Now Bison will insert @code{#include "ptypes.h"} and the new
2986@code{YYLTYPE} definition before the Bison-generated @code{YYSTYPE}
2987and @code{YYLTYPE} definitions in both the parser implementation file
2988and the parser header file.  (By the same reasoning, @code{%code
2989requires} would also be the appropriate place to write your own
2990definition for @code{YYSTYPE}.)
2991
2992When you are writing dependency code for @code{YYSTYPE} and
2993@code{YYLTYPE}, you should prefer @code{%code requires} over
2994@code{%code top} regardless of whether you instruct Bison to generate
2995a parser header file.  When you are writing code that you need Bison
2996to insert only into the parser implementation file and that has no
2997special need to appear at the top of that file, you should prefer the
2998unqualified @code{%code} over @code{%code top}.  These practices will
2999make the purpose of each block of your code explicit to Bison and to
3000other developers reading your grammar file.  Following these
3001practices, we expect the unqualified @code{%code} and @code{%code
3002requires} to be the most important of the four @var{Prologue}
3003alternatives.
3004
3005At some point while developing your parser, you might decide to
3006provide @code{trace_token} to modules that are external to your
3007parser.  Thus, you might wish for Bison to insert the prototype into
3008both the parser header file and the parser implementation file.  Since
3009this function is not a dependency required by @code{YYSTYPE} or
3010@code{YYLTYPE}, it doesn't make sense to move its prototype to a
3011@code{%code requires}.  More importantly, since it depends upon
3012@code{YYLTYPE} and @code{yytokentype}, @code{%code requires} is not
3013sufficient.  Instead, move its prototype from the unqualified
3014@code{%code} to a @code{%code provides}:
3015
3016@example
3017@group
3018%code top @{
3019  #define _GNU_SOURCE
3020  #include <stdio.h>
3021@}
3022@end group
3023
3024@group
3025%code requires @{
3026  #include "ptypes.h"
3027@}
3028@end group
3029@group
3030%union @{
3031  long int n;
3032  tree t;  /* @r{@code{tree} is defined in @file{ptypes.h}.} */
3033@}
3034@end group
3035
3036@group
3037%code requires @{
3038  #define YYLTYPE YYLTYPE
3039  typedef struct YYLTYPE
3040  @{
3041    int first_line;
3042    int first_column;
3043    int last_line;
3044    int last_column;
3045    char *filename;
3046  @} YYLTYPE;
3047@}
3048@end group
3049
3050@group
3051%code provides @{
3052  void trace_token (enum yytokentype token, YYLTYPE loc);
3053@}
3054@end group
3055
3056@group
3057%code @{
3058  static void print_token_value (FILE *, int, YYSTYPE);
3059  #define YYPRINT(F, N, L) print_token_value (F, N, L)
3060@}
3061@end group
3062
3063@dots{}
3064@end example
3065
3066@noindent
3067Bison will insert the @code{trace_token} prototype into both the
3068parser header file and the parser implementation file after the
3069definitions for @code{yytokentype}, @code{YYLTYPE}, and
3070@code{YYSTYPE}.
3071
3072The above examples are careful to write directives in an order that
3073reflects the layout of the generated parser implementation and header
3074files: @code{%code top}, @code{%code requires}, @code{%code provides},
3075and then @code{%code}.  While your grammar files may generally be
3076easier to read if you also follow this order, Bison does not require
3077it.  Instead, Bison lets you choose an organization that makes sense
3078to you.
3079
3080You may declare any of these directives multiple times in the grammar file.
3081In that case, Bison concatenates the contained code in declaration order.
3082This is the only way in which the position of one of these directives within
3083the grammar file affects its functionality.
3084
3085The result of the previous two properties is greater flexibility in how you may
3086organize your grammar file.
3087For example, you may organize semantic-type-related directives by semantic
3088type:
3089
3090@example
3091@group
3092%code requires @{ #include "type1.h" @}
3093%union @{ type1 field1; @}
3094%destructor @{ type1_free ($$); @} <field1>
3095%printer @{ type1_print (yyoutput, $$); @} <field1>
3096@end group
3097
3098@group
3099%code requires @{ #include "type2.h" @}
3100%union @{ type2 field2; @}
3101%destructor @{ type2_free ($$); @} <field2>
3102%printer @{ type2_print (yyoutput, $$); @} <field2>
3103@end group
3104@end example
3105
3106@noindent
3107You could even place each of the above directive groups in the rules section of
3108the grammar file next to the set of rules that uses the associated semantic
3109type.
3110(In the rules section, you must terminate each of those directives with a
3111semicolon.)
3112And you don't have to worry that some directive (like a @code{%union}) in the
3113definitions section is going to adversely affect their functionality in some
3114counter-intuitive manner just because it comes first.
3115Such an organization is not possible using @var{Prologue} sections.
3116
3117This section has been concerned with explaining the advantages of the four
3118@var{Prologue} alternatives over the original Yacc @var{Prologue}.
3119However, in most cases when using these directives, you shouldn't need to
3120think about all the low-level ordering issues discussed here.
3121Instead, you should simply use these directives to label each block of your
3122code according to its purpose and let Bison handle the ordering.
3123@code{%code} is the most generic label.
3124Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
3125as needed.
3126
3127@node Bison Declarations
3128@subsection The Bison Declarations Section
3129@cindex Bison declarations (introduction)
3130@cindex declarations, Bison (introduction)
3131
3132The @var{Bison declarations} section contains declarations that define
3133terminal and nonterminal symbols, specify precedence, and so on.
3134In some simple grammars you may not need any declarations.
3135@xref{Declarations, ,Bison Declarations}.
3136
3137@node Grammar Rules
3138@subsection The Grammar Rules Section
3139@cindex grammar rules section
3140@cindex rules section for grammar
3141
3142The @dfn{grammar rules} section contains one or more Bison grammar
3143rules, and nothing else.  @xref{Rules, ,Syntax of Grammar Rules}.
3144
3145There must always be at least one grammar rule, and the first
3146@samp{%%} (which precedes the grammar rules) may never be omitted even
3147if it is the first thing in the file.
3148
3149@node Epilogue
3150@subsection The epilogue
3151@cindex additional C code section
3152@cindex epilogue
3153@cindex C code, section for additional
3154
3155The @var{Epilogue} is copied verbatim to the end of the parser
3156implementation file, just as the @var{Prologue} is copied to the
3157beginning.  This is the most convenient place to put anything that you
3158want to have in the parser implementation file but which need not come
3159before the definition of @code{yyparse}.  For example, the definitions
3160of @code{yylex} and @code{yyerror} often go here.  Because C requires
3161functions to be declared before being used, you often need to declare
3162functions like @code{yylex} and @code{yyerror} in the Prologue, even
3163if you define them in the Epilogue.  @xref{Interface, ,Parser
3164C-Language Interface}.
3165
3166If the last section is empty, you may omit the @samp{%%} that separates it
3167from the grammar rules.
3168
3169The Bison parser itself contains many macros and identifiers whose names
3170start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3171any such names (except those documented in this manual) in the epilogue
3172of the grammar file.
3173
3174@node Symbols
3175@section Symbols, Terminal and Nonterminal
3176@cindex nonterminal symbol
3177@cindex terminal symbol
3178@cindex token type
3179@cindex symbol
3180
3181@dfn{Symbols} in Bison grammars represent the grammatical classifications
3182of the language.
3183
3184A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
3185class of syntactically equivalent tokens.  You use the symbol in grammar
3186rules to mean that a token in that class is allowed.  The symbol is
3187represented in the Bison parser by a numeric code, and the @code{yylex}
3188function returns a token type code to indicate what kind of token has
3189been read.  You don't need to know what the code value is; you can use
3190the symbol to stand for it.
3191
3192A @dfn{nonterminal symbol} stands for a class of syntactically
3193equivalent groupings.  The symbol name is used in writing grammar rules.
3194By convention, it should be all lower case.
3195
3196Symbol names can contain letters, underscores, periods, and non-initial
3197digits and dashes.  Dashes in symbol names are a GNU extension, incompatible
3198with POSIX Yacc.  Periods and dashes make symbol names less convenient to
3199use with named references, which require brackets around such names
3200(@pxref{Named References}).  Terminal symbols that contain periods or dashes
3201make little sense: since they are not valid symbols (in most programming
3202languages) they are not exported as token names.
3203
3204There are three ways of writing terminal symbols in the grammar:
3205
3206@itemize @bullet
3207@item
3208A @dfn{named token type} is written with an identifier, like an
3209identifier in C@.  By convention, it should be all upper case.  Each
3210such name must be defined with a Bison declaration such as
3211@code{%token}.  @xref{Token Decl, ,Token Type Names}.
3212
3213@item
3214@cindex character token
3215@cindex literal token
3216@cindex single-character literal
3217A @dfn{character token type} (or @dfn{literal character token}) is
3218written in the grammar using the same syntax used in C for character
3219constants; for example, @code{'+'} is a character token type.  A
3220character token type doesn't need to be declared unless you need to
3221specify its semantic value data type (@pxref{Value Type, ,Data Types of
3222Semantic Values}), associativity, or precedence (@pxref{Precedence,
3223,Operator Precedence}).
3224
3225By convention, a character token type is used only to represent a
3226token that consists of that particular character.  Thus, the token
3227type @code{'+'} is used to represent the character @samp{+} as a
3228token.  Nothing enforces this convention, but if you depart from it,
3229your program will confuse other readers.
3230
3231All the usual escape sequences used in character literals in C can be
3232used in Bison as well, but you must not use the null character as a
3233character literal because its numeric code, zero, signifies
3234end-of-input (@pxref{Calling Convention, ,Calling Convention
3235for @code{yylex}}).  Also, unlike standard C, trigraphs have no
3236special meaning in Bison character literals, nor is backslash-newline
3237allowed.
3238
3239@item
3240@cindex string token
3241@cindex literal string token
3242@cindex multicharacter literal
3243A @dfn{literal string token} is written like a C string constant; for
3244example, @code{"<="} is a literal string token.  A literal string token
3245doesn't need to be declared unless you need to specify its semantic
3246value data type (@pxref{Value Type}), associativity, or precedence
3247(@pxref{Precedence}).
3248
3249You can associate the literal string token with a symbolic name as an
3250alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
3251Declarations}).  If you don't do that, the lexical analyzer has to
3252retrieve the token number for the literal string token from the
3253@code{yytname} table (@pxref{Calling Convention}).
3254
3255@strong{Warning}: literal string tokens do not work in Yacc.
3256
3257By convention, a literal string token is used only to represent a token
3258that consists of that particular string.  Thus, you should use the token
3259type @code{"<="} to represent the string @samp{<=} as a token.  Bison
3260does not enforce this convention, but if you depart from it, people who
3261read your program will be confused.
3262
3263All the escape sequences used in string literals in C can be used in
3264Bison as well, except that you must not use a null character within a
3265string literal.  Also, unlike Standard C, trigraphs have no special
3266meaning in Bison string literals, nor is backslash-newline allowed.  A
3267literal string token must contain two or more characters; for a token
3268containing just one character, use a character token (see above).
3269@end itemize
3270
3271How you choose to write a terminal symbol has no effect on its
3272grammatical meaning.  That depends only on where it appears in rules and
3273on when the parser function returns that symbol.
3274
3275The value returned by @code{yylex} is always one of the terminal
3276symbols, except that a zero or negative value signifies end-of-input.
3277Whichever way you write the token type in the grammar rules, you write
3278it the same way in the definition of @code{yylex}.  The numeric code
3279for a character token type is simply the positive numeric code of the
3280character, so @code{yylex} can use the identical value to generate the
3281requisite code, though you may need to convert it to @code{unsigned
3282char} to avoid sign-extension on hosts where @code{char} is signed.
3283Each named token type becomes a C macro in the parser implementation
3284file, so @code{yylex} can use the name to stand for the code.  (This
3285is why periods don't make sense in terminal symbols.)  @xref{Calling
3286Convention, ,Calling Convention for @code{yylex}}.
3287
3288If @code{yylex} is defined in a separate file, you need to arrange for the
3289token-type macro definitions to be available there.  Use the @samp{-d}
3290option when you run Bison, so that it will write these macro definitions
3291into a separate header file @file{@var{name}.tab.h} which you can include
3292in the other source files that need it.  @xref{Invocation, ,Invoking Bison}.
3293
3294If you want to write a grammar that is portable to any Standard C
3295host, you must use only nonnull character tokens taken from the basic
3296execution character set of Standard C@.  This set consists of the ten
3297digits, the 52 lower- and upper-case English letters, and the
3298characters in the following C-language string:
3299
3300@example
3301"\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3302@end example
3303
3304The @code{yylex} function and Bison must use a consistent character set
3305and encoding for character tokens.  For example, if you run Bison in an
3306ASCII environment, but then compile and run the resulting
3307program in an environment that uses an incompatible character set like
3308EBCDIC, the resulting program may not work because the tables
3309generated by Bison will assume ASCII numeric values for
3310character tokens.  It is standard practice for software distributions to
3311contain C source files that were generated by Bison in an
3312ASCII environment, so installers on platforms that are
3313incompatible with ASCII must rebuild those files before
3314compiling them.
3315
3316The symbol @code{error} is a terminal symbol reserved for error recovery
3317(@pxref{Error Recovery}); you shouldn't use it for any other purpose.
3318In particular, @code{yylex} should never return this value.  The default
3319value of the error token is 256, unless you explicitly assigned 256 to
3320one of your tokens with a @code{%token} declaration.
3321
3322@node Rules
3323@section Syntax of Grammar Rules
3324@cindex rule syntax
3325@cindex grammar rule syntax
3326@cindex syntax of grammar rules
3327
3328A Bison grammar rule has the following general form:
3329
3330@example
3331@group
3332@var{result}: @var{components}@dots{};
3333@end group
3334@end example
3335
3336@noindent
3337where @var{result} is the nonterminal symbol that this rule describes,
3338and @var{components} are various terminal and nonterminal symbols that
3339are put together by this rule (@pxref{Symbols}).
3340
3341For example,
3342
3343@example
3344@group
3345exp: exp '+' exp;
3346@end group
3347@end example
3348
3349@noindent
3350says that two groupings of type @code{exp}, with a @samp{+} token in between,
3351can be combined into a larger grouping of type @code{exp}.
3352
3353White space in rules is significant only to separate symbols.  You can add
3354extra white space as you wish.
3355
3356Scattered among the components can be @var{actions} that determine
3357the semantics of the rule.  An action looks like this:
3358
3359@example
3360@{@var{C statements}@}
3361@end example
3362
3363@noindent
3364@cindex braced code
3365This is an example of @dfn{braced code}, that is, C code surrounded by
3366braces, much like a compound statement in C@.  Braced code can contain
3367any sequence of C tokens, so long as its braces are balanced.  Bison
3368does not check the braced code for correctness directly; it merely
3369copies the code to the parser implementation file, where the C
3370compiler can check it.
3371
3372Within braced code, the balanced-brace count is not affected by braces
3373within comments, string literals, or character constants, but it is
3374affected by the C digraphs @samp{<%} and @samp{%>} that represent
3375braces.  At the top level braced code must be terminated by @samp{@}}
3376and not by a digraph.  Bison does not look for trigraphs, so if braced
3377code uses trigraphs you should ensure that they do not affect the
3378nesting of braces or the boundaries of comments, string literals, or
3379character constants.
3380
3381Usually there is only one action and it follows the components.
3382@xref{Actions}.
3383
3384@findex |
3385Multiple rules for the same @var{result} can be written separately or can
3386be joined with the vertical-bar character @samp{|} as follows:
3387
3388@example
3389@group
3390@var{result}:
3391  @var{rule1-components}@dots{}
3392| @var{rule2-components}@dots{}
3393@dots{}
3394;
3395@end group
3396@end example
3397
3398@noindent
3399They are still considered distinct rules even when joined in this way.
3400
3401If @var{components} in a rule is empty, it means that @var{result} can
3402match the empty string.  For example, here is how to define a
3403comma-separated sequence of zero or more @code{exp} groupings:
3404
3405@example
3406@group
3407expseq:
3408  /* empty */
3409| expseq1
3410;
3411@end group
3412
3413@group
3414expseq1:
3415  exp
3416| expseq1 ',' exp
3417;
3418@end group
3419@end example
3420
3421@noindent
3422It is customary to write a comment @samp{/* empty */} in each rule
3423with no components.
3424
3425@node Recursion
3426@section Recursive Rules
3427@cindex recursive rule
3428
3429A rule is called @dfn{recursive} when its @var{result} nonterminal
3430appears also on its right hand side.  Nearly all Bison grammars need to
3431use recursion, because that is the only way to define a sequence of any
3432number of a particular thing.  Consider this recursive definition of a
3433comma-separated sequence of one or more expressions:
3434
3435@example
3436@group
3437expseq1:
3438  exp
3439| expseq1 ',' exp
3440;
3441@end group
3442@end example
3443
3444@cindex left recursion
3445@cindex right recursion
3446@noindent
3447Since the recursive use of @code{expseq1} is the leftmost symbol in the
3448right hand side, we call this @dfn{left recursion}.  By contrast, here
3449the same construct is defined using @dfn{right recursion}:
3450
3451@example
3452@group
3453expseq1:
3454  exp
3455| exp ',' expseq1
3456;
3457@end group
3458@end example
3459
3460@noindent
3461Any kind of sequence can be defined using either left recursion or right
3462recursion, but you should always use left recursion, because it can
3463parse a sequence of any number of elements with bounded stack space.
3464Right recursion uses up space on the Bison stack in proportion to the
3465number of elements in the sequence, because all the elements must be
3466shifted onto the stack before the rule can be applied even once.
3467@xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
3468of this.
3469
3470@cindex mutual recursion
3471@dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3472rule does not appear directly on its right hand side, but does appear
3473in rules for other nonterminals which do appear on its right hand
3474side.
3475
3476For example:
3477
3478@example
3479@group
3480expr:
3481  primary
3482| primary '+' primary
3483;
3484@end group
3485
3486@group
3487primary:
3488  constant
3489| '(' expr ')'
3490;
3491@end group
3492@end example
3493
3494@noindent
3495defines two mutually-recursive nonterminals, since each refers to the
3496other.
3497
3498@node Semantics
3499@section Defining Language Semantics
3500@cindex defining language semantics
3501@cindex language semantics, defining
3502
3503The grammar rules for a language determine only the syntax.  The semantics
3504are determined by the semantic values associated with various tokens and
3505groupings, and by the actions taken when various groupings are recognized.
3506
3507For example, the calculator calculates properly because the value
3508associated with each expression is the proper number; it adds properly
3509because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3510the numbers associated with @var{x} and @var{y}.
3511
3512@menu
3513* Value Type::        Specifying one data type for all semantic values.
3514* Multiple Types::    Specifying several alternative data types.
3515* Actions::           An action is the semantic definition of a grammar rule.
3516* Action Types::      Specifying data types for actions to operate on.
3517* Mid-Rule Actions::  Most actions go at the end of a rule.
3518                      This says when, why and how to use the exceptional
3519                        action in the middle of a rule.
3520@end menu
3521
3522@node Value Type
3523@subsection Data Types of Semantic Values
3524@cindex semantic value type
3525@cindex value type, semantic
3526@cindex data types of semantic values
3527@cindex default data type
3528
3529In a simple program it may be sufficient to use the same data type for
3530the semantic values of all language constructs.  This was true in the
3531RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
3532Notation Calculator}).
3533
3534Bison normally uses the type @code{int} for semantic values if your
3535program uses the same data type for all language constructs.  To
3536specify some other type, define @code{YYSTYPE} as a macro, like this:
3537
3538@example
3539#define YYSTYPE double
3540@end example
3541
3542@noindent
3543@code{YYSTYPE}'s replacement list should be a type name
3544that does not contain parentheses or square brackets.
3545This macro definition must go in the prologue of the grammar file
3546(@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
3547
3548@node Multiple Types
3549@subsection More Than One Value Type
3550
3551In most programs, you will need different data types for different kinds
3552of tokens and groupings.  For example, a numeric constant may need type
3553@code{int} or @code{long int}, while a string constant needs type
3554@code{char *}, and an identifier might need a pointer to an entry in the
3555symbol table.
3556
3557To use more than one data type for semantic values in one parser, Bison
3558requires you to do two things:
3559
3560@itemize @bullet
3561@item
3562Specify the entire collection of possible data types, either by using the
3563@code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
3564Value Types}), or by using a @code{typedef} or a @code{#define} to
3565define @code{YYSTYPE} to be a union type whose member names are
3566the type tags.
3567
3568@item
3569Choose one of those types for each symbol (terminal or nonterminal) for
3570which semantic values are used.  This is done for tokens with the
3571@code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
3572and for groupings with the @code{%type} Bison declaration (@pxref{Type
3573Decl, ,Nonterminal Symbols}).
3574@end itemize
3575
3576@node Actions
3577@subsection Actions
3578@cindex action
3579@vindex $$
3580@vindex $@var{n}
3581@vindex $@var{name}
3582@vindex $[@var{name}]
3583
3584An action accompanies a syntactic rule and contains C code to be executed
3585each time an instance of that rule is recognized.  The task of most actions
3586is to compute a semantic value for the grouping built by the rule from the
3587semantic values associated with tokens or smaller groupings.
3588
3589An action consists of braced code containing C statements, and can be
3590placed at any position in the rule;
3591it is executed at that position.  Most rules have just one action at the
3592end of the rule, following all the components.  Actions in the middle of
3593a rule are tricky and used only for special purposes (@pxref{Mid-Rule
3594Actions, ,Actions in Mid-Rule}).
3595
3596The C code in an action can refer to the semantic values of the
3597components matched by the rule with the construct @code{$@var{n}},
3598which stands for the value of the @var{n}th component.  The semantic
3599value for the grouping being constructed is @code{$$}.  In addition,
3600the semantic values of symbols can be accessed with the named
3601references construct @code{$@var{name}} or @code{$[@var{name}]}.
3602Bison translates both of these constructs into expressions of the
3603appropriate type when it copies the actions into the parser
3604implementation file.  @code{$$} (or @code{$@var{name}}, when it stands
3605for the current grouping) is translated to a modifiable lvalue, so it
3606can be assigned to.
3607
3608Here is a typical example:
3609
3610@example
3611@group
3612exp:
3613@dots{}
3614| exp '+' exp     @{ $$ = $1 + $3; @}
3615@end group
3616@end example
3617
3618Or, in terms of named references:
3619
3620@example
3621@group
3622exp[result]:
3623@dots{}
3624| exp[left] '+' exp[right]  @{ $result = $left + $right; @}
3625@end group
3626@end example
3627
3628@noindent
3629This rule constructs an @code{exp} from two smaller @code{exp} groupings
3630connected by a plus-sign token.  In the action, @code{$1} and @code{$3}
3631(@code{$left} and @code{$right})
3632refer to the semantic values of the two component @code{exp} groupings,
3633which are the first and third symbols on the right hand side of the rule.
3634The sum is stored into @code{$$} (@code{$result}) so that it becomes the
3635semantic value of
3636the addition-expression just recognized by the rule.  If there were a
3637useful semantic value associated with the @samp{+} token, it could be
3638referred to as @code{$2}.
3639
3640@xref{Named References}, for more information about using the named
3641references construct.
3642
3643Note that the vertical-bar character @samp{|} is really a rule
3644separator, and actions are attached to a single rule.  This is a
3645difference with tools like Flex, for which @samp{|} stands for either
3646``or'', or ``the same action as that of the next rule''.  In the
3647following example, the action is triggered only when @samp{b} is found:
3648
3649@example
3650@group
3651a-or-b: 'a'|'b'   @{ a_or_b_found = 1; @};
3652@end group
3653@end example
3654
3655@cindex default action
3656If you don't specify an action for a rule, Bison supplies a default:
3657@w{@code{$$ = $1}.}  Thus, the value of the first symbol in the rule
3658becomes the value of the whole rule.  Of course, the default action is
3659valid only if the two data types match.  There is no meaningful default
3660action for an empty rule; every empty rule must have an explicit action
3661unless the rule's value does not matter.
3662
3663@code{$@var{n}} with @var{n} zero or negative is allowed for reference
3664to tokens and groupings on the stack @emph{before} those that match the
3665current rule.  This is a very risky practice, and to use it reliably
3666you must be certain of the context in which the rule is applied.  Here
3667is a case in which you can use this reliably:
3668
3669@example
3670@group
3671foo:
3672  expr bar '+' expr  @{ @dots{} @}
3673| expr bar '-' expr  @{ @dots{} @}
3674;
3675@end group
3676
3677@group
3678bar:
3679  /* empty */    @{ previous_expr = $0; @}
3680;
3681@end group
3682@end example
3683
3684As long as @code{bar} is used only in the fashion shown here, @code{$0}
3685always refers to the @code{expr} which precedes @code{bar} in the
3686definition of @code{foo}.
3687
3688@vindex yylval
3689It is also possible to access the semantic value of the lookahead token, if
3690any, from a semantic action.
3691This semantic value is stored in @code{yylval}.
3692@xref{Action Features, ,Special Features for Use in Actions}.
3693
3694@node Action Types
3695@subsection Data Types of Values in Actions
3696@cindex action data types
3697@cindex data types in actions
3698
3699If you have chosen a single data type for semantic values, the @code{$$}
3700and @code{$@var{n}} constructs always have that data type.
3701
3702If you have used @code{%union} to specify a variety of data types, then you
3703must declare a choice among these types for each terminal or nonterminal
3704symbol that can have a semantic value.  Then each time you use @code{$$} or
3705@code{$@var{n}}, its data type is determined by which symbol it refers to
3706in the rule.  In this example,
3707
3708@example
3709@group
3710exp:
3711  @dots{}
3712| exp '+' exp    @{ $$ = $1 + $3; @}
3713@end group
3714@end example
3715
3716@noindent
3717@code{$1} and @code{$3} refer to instances of @code{exp}, so they all
3718have the data type declared for the nonterminal symbol @code{exp}.  If
3719@code{$2} were used, it would have the data type declared for the
3720terminal symbol @code{'+'}, whatever that might be.
3721
3722Alternatively, you can specify the data type when you refer to the value,
3723by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
3724reference.  For example, if you have defined types as shown here:
3725
3726@example
3727@group
3728%union @{
3729  int itype;
3730  double dtype;
3731@}
3732@end group
3733@end example
3734
3735@noindent
3736then you can write @code{$<itype>1} to refer to the first subunit of the
3737rule as an integer, or @code{$<dtype>1} to refer to it as a double.
3738
3739@node Mid-Rule Actions
3740@subsection Actions in Mid-Rule
3741@cindex actions in mid-rule
3742@cindex mid-rule actions
3743
3744Occasionally it is useful to put an action in the middle of a rule.
3745These actions are written just like usual end-of-rule actions, but they
3746are executed before the parser even recognizes the following components.
3747
3748@menu
3749* Using Mid-Rule Actions::       Putting an action in the middle of a rule.
3750* Mid-Rule Action Translation::  How mid-rule actions are actually processed.
3751* Mid-Rule Conflicts::           Mid-rule actions can cause conflicts.
3752@end menu
3753
3754@node Using Mid-Rule Actions
3755@subsubsection Using Mid-Rule Actions
3756
3757A mid-rule action may refer to the components preceding it using
3758@code{$@var{n}}, but it may not refer to subsequent components because
3759it is run before they are parsed.
3760
3761The mid-rule action itself counts as one of the components of the rule.
3762This makes a difference when there is another action later in the same rule
3763(and usually there is another at the end): you have to count the actions
3764along with the symbols when working out which number @var{n} to use in
3765@code{$@var{n}}.
3766
3767The mid-rule action can also have a semantic value.  The action can set
3768its value with an assignment to @code{$$}, and actions later in the rule
3769can refer to the value using @code{$@var{n}}.  Since there is no symbol
3770to name the action, there is no way to declare a data type for the value
3771in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
3772specify a data type each time you refer to this value.
3773
3774There is no way to set the value of the entire rule with a mid-rule
3775action, because assignments to @code{$$} do not have that effect.  The
3776only way to set the value for the entire rule is with an ordinary action
3777at the end of the rule.
3778
3779Here is an example from a hypothetical compiler, handling a @code{let}
3780statement that looks like @samp{let (@var{variable}) @var{statement}} and
3781serves to create a variable named @var{variable} temporarily for the
3782duration of @var{statement}.  To parse this construct, we must put
3783@var{variable} into the symbol table while @var{statement} is parsed, then
3784remove it afterward.  Here is how it is done:
3785
3786@example
3787@group
3788stmt:
3789  "let" '(' var ')'
3790    @{
3791      $<context>$ = push_context ();
3792      declare_variable ($3);
3793    @}
3794  stmt
3795    @{
3796      $$ = $6;
3797      pop_context ($<context>5);
3798    @}
3799@end group
3800@end example
3801
3802@noindent
3803As soon as @samp{let (@var{variable})} has been recognized, the first
3804action is run.  It saves a copy of the current semantic context (the
3805list of accessible variables) as its semantic value, using alternative
3806@code{context} in the data-type union.  Then it calls
3807@code{declare_variable} to add the new variable to that list.  Once the
3808first action is finished, the embedded statement @code{stmt} can be
3809parsed.
3810
3811Note that the mid-rule action is component number 5, so the @samp{stmt} is
3812component number 6.  Named references can be used to improve the readability
3813and maintainability (@pxref{Named References}):
3814
3815@example
3816@group
3817stmt:
3818  "let" '(' var ')'
3819    @{
3820      $<context>let = push_context ();
3821      declare_variable ($3);
3822    @}[let]
3823  stmt
3824    @{
3825      $$ = $6;
3826      pop_context ($<context>let);
3827    @}
3828@end group
3829@end example
3830
3831After the embedded statement is parsed, its semantic value becomes the
3832value of the entire @code{let}-statement.  Then the semantic value from the
3833earlier action is used to restore the prior list of variables.  This
3834removes the temporary @code{let}-variable from the list so that it won't
3835appear to exist while the rest of the program is parsed.
3836
3837@findex %destructor
3838@cindex discarded symbols, mid-rule actions
3839@cindex error recovery, mid-rule actions
3840In the above example, if the parser initiates error recovery (@pxref{Error
3841Recovery}) while parsing the tokens in the embedded statement @code{stmt},
3842it might discard the previous semantic context @code{$<context>5} without
3843restoring it.
3844Thus, @code{$<context>5} needs a destructor (@pxref{Destructor Decl, , Freeing
3845Discarded Symbols}).
3846However, Bison currently provides no means to declare a destructor specific to
3847a particular mid-rule action's semantic value.
3848
3849One solution is to bury the mid-rule action inside a nonterminal symbol and to
3850declare a destructor for that symbol:
3851
3852@example
3853@group
3854%type <context> let
3855%destructor @{ pop_context ($$); @} let
3856
3857%%
3858
3859stmt:
3860  let stmt
3861    @{
3862      $$ = $2;
3863      pop_context ($let);
3864    @};
3865
3866let:
3867  "let" '(' var ')'
3868    @{
3869      $let = push_context ();
3870      declare_variable ($3);
3871    @};
3872
3873@end group
3874@end example
3875
3876@noindent
3877Note that the action is now at the end of its rule.
3878Any mid-rule action can be converted to an end-of-rule action in this way, and
3879this is what Bison actually does to implement mid-rule actions.
3880
3881@node Mid-Rule Action Translation
3882@subsubsection Mid-Rule Action Translation
3883@vindex $@@@var{n}
3884@vindex @@@var{n}
3885
3886As hinted earlier, mid-rule actions are actually transformed into regular
3887rules and actions.  The various reports generated by Bison (textual,
3888graphical, etc., see @ref{Understanding, , Understanding Your Parser})
3889reveal this translation, best explained by means of an example.  The
3890following rule:
3891
3892@example
3893exp: @{ a(); @} "b" @{ c(); @} @{ d(); @} "e" @{ f(); @};
3894@end example
3895
3896@noindent
3897is translated into:
3898
3899@example
3900$@@1: /* empty */ @{ a(); @};
3901$@@2: /* empty */ @{ c(); @};
3902$@@3: /* empty */ @{ d(); @};
3903exp: $@@1 "b" $@@2 $@@3 "e" @{ f(); @};
3904@end example
3905
3906@noindent
3907with new nonterminal symbols @code{$@@@var{n}}, where @var{n} is a number.
3908
3909A mid-rule action is expected to generate a value if it uses @code{$$}, or
3910the (final) action uses @code{$@var{n}} where @var{n} denote the mid-rule
3911action.  In that case its nonterminal is rather named @code{@@@var{n}}:
3912
3913@example
3914exp: @{ a(); @} "b" @{ $$ = c(); @} @{ d(); @} "e" @{ f = $1; @};
3915@end example
3916
3917@noindent
3918is translated into
3919
3920@example
3921@@1: /* empty */ @{ a(); @};
3922@@2: /* empty */ @{ $$ = c(); @};
3923$@@3: /* empty */ @{ d(); @};
3924exp: @@1 "b" @@2 $@@3 "e" @{ f = $1; @}
3925@end example
3926
3927There are probably two errors in the above example: the first mid-rule
3928action does not generate a value (it does not use @code{$$} although the
3929final action uses it), and the value of the second one is not used (the
3930final action does not use @code{$3}).  Bison reports these errors when the
3931@code{midrule-value} warnings are enabled (@pxref{Invocation, ,Invoking
3932Bison}):
3933
3934@example
3935$ bison -fcaret -Wmidrule-value mid.y
3936@group
3937mid.y:2.6-13: warning: unset value: $$
3938 exp: @{ a(); @} "b" @{ $$ = c(); @} @{ d(); @} "e" @{ f = $1; @};
3939      ^^^^^^^^
3940@end group
3941@group
3942mid.y:2.19-31: warning: unused value: $3
3943 exp: @{ a(); @} "b" @{ $$ = c(); @} @{ d(); @} "e" @{ f = $1; @};
3944                   ^^^^^^^^^^^^^
3945@end group
3946@end example
3947
3948
3949@node Mid-Rule Conflicts
3950@subsubsection Conflicts due to Mid-Rule Actions
3951Taking action before a rule is completely recognized often leads to
3952conflicts since the parser must commit to a parse in order to execute the
3953action.  For example, the following two rules, without mid-rule actions,
3954can coexist in a working parser because the parser can shift the open-brace
3955token and look at what follows before deciding whether there is a
3956declaration or not:
3957
3958@example
3959@group
3960compound:
3961  '@{' declarations statements '@}'
3962| '@{' statements '@}'
3963;
3964@end group
3965@end example
3966
3967@noindent
3968But when we add a mid-rule action as follows, the rules become nonfunctional:
3969
3970@example
3971@group
3972compound:
3973  @{ prepare_for_local_variables (); @}
3974     '@{' declarations statements '@}'
3975@end group
3976@group
3977|    '@{' statements '@}'
3978;
3979@end group
3980@end example
3981
3982@noindent
3983Now the parser is forced to decide whether to run the mid-rule action
3984when it has read no farther than the open-brace.  In other words, it
3985must commit to using one rule or the other, without sufficient
3986information to do it correctly.  (The open-brace token is what is called
3987the @dfn{lookahead} token at this time, since the parser is still
3988deciding what to do about it.  @xref{Lookahead, ,Lookahead Tokens}.)
3989
3990You might think that you could correct the problem by putting identical
3991actions into the two rules, like this:
3992
3993@example
3994@group
3995compound:
3996  @{ prepare_for_local_variables (); @}
3997    '@{' declarations statements '@}'
3998| @{ prepare_for_local_variables (); @}
3999    '@{' statements '@}'
4000;
4001@end group
4002@end example
4003
4004@noindent
4005But this does not help, because Bison does not realize that the two actions
4006are identical.  (Bison never tries to understand the C code in an action.)
4007
4008If the grammar is such that a declaration can be distinguished from a
4009statement by the first token (which is true in C), then one solution which
4010does work is to put the action after the open-brace, like this:
4011
4012@example
4013@group
4014compound:
4015  '@{' @{ prepare_for_local_variables (); @}
4016    declarations statements '@}'
4017| '@{' statements '@}'
4018;
4019@end group
4020@end example
4021
4022@noindent
4023Now the first token of the following declaration or statement,
4024which would in any case tell Bison which rule to use, can still do so.
4025
4026Another solution is to bury the action inside a nonterminal symbol which
4027serves as a subroutine:
4028
4029@example
4030@group
4031subroutine:
4032  /* empty */  @{ prepare_for_local_variables (); @}
4033;
4034@end group
4035
4036@group
4037compound:
4038  subroutine '@{' declarations statements '@}'
4039| subroutine '@{' statements '@}'
4040;
4041@end group
4042@end example
4043
4044@noindent
4045Now Bison can execute the action in the rule for @code{subroutine} without
4046deciding which rule for @code{compound} it will eventually use.
4047
4048
4049@node Tracking Locations
4050@section Tracking Locations
4051@cindex location
4052@cindex textual location
4053@cindex location, textual
4054
4055Though grammar rules and semantic actions are enough to write a fully
4056functional parser, it can be useful to process some additional information,
4057especially symbol locations.
4058
4059The way locations are handled is defined by providing a data type, and
4060actions to take when rules are matched.
4061
4062@menu
4063* Location Type::               Specifying a data type for locations.
4064* Actions and Locations::       Using locations in actions.
4065* Location Default Action::     Defining a general way to compute locations.
4066@end menu
4067
4068@node Location Type
4069@subsection Data Type of Locations
4070@cindex data type of locations
4071@cindex default location type
4072
4073Defining a data type for locations is much simpler than for semantic values,
4074since all tokens and groupings always use the same type.
4075
4076You can specify the type of locations by defining a macro called
4077@code{YYLTYPE}, just as you can specify the semantic value type by
4078defining a @code{YYSTYPE} macro (@pxref{Value Type}).
4079When @code{YYLTYPE} is not defined, Bison uses a default structure type with
4080four members:
4081
4082@example
4083typedef struct YYLTYPE
4084@{
4085  int first_line;
4086  int first_column;
4087  int last_line;
4088  int last_column;
4089@} YYLTYPE;
4090@end example
4091
4092When @code{YYLTYPE} is not defined, at the beginning of the parsing, Bison
4093initializes all these fields to 1 for @code{yylloc}.  To initialize
4094@code{yylloc} with a custom location type (or to chose a different
4095initialization), use the @code{%initial-action} directive.  @xref{Initial
4096Action Decl, , Performing Actions before Parsing}.
4097
4098@node Actions and Locations
4099@subsection Actions and Locations
4100@cindex location actions
4101@cindex actions, location
4102@vindex @@$
4103@vindex @@@var{n}
4104@vindex @@@var{name}
4105@vindex @@[@var{name}]
4106
4107Actions are not only useful for defining language semantics, but also for
4108describing the behavior of the output parser with locations.
4109
4110The most obvious way for building locations of syntactic groupings is very
4111similar to the way semantic values are computed.  In a given rule, several
4112constructs can be used to access the locations of the elements being matched.
4113The location of the @var{n}th component of the right hand side is
4114@code{@@@var{n}}, while the location of the left hand side grouping is
4115@code{@@$}.
4116
4117In addition, the named references construct @code{@@@var{name}} and
4118@code{@@[@var{name}]} may also be used to address the symbol locations.
4119@xref{Named References}, for more information about using the named
4120references construct.
4121
4122Here is a basic example using the default data type for locations:
4123
4124@example
4125@group
4126exp:
4127  @dots{}
4128| exp '/' exp
4129    @{
4130      @@$.first_column = @@1.first_column;
4131      @@$.first_line = @@1.first_line;
4132      @@$.last_column = @@3.last_column;
4133      @@$.last_line = @@3.last_line;
4134      if ($3)
4135        $$ = $1 / $3;
4136      else
4137        @{
4138          $$ = 1;
4139          fprintf (stderr,
4140                   "Division by zero, l%d,c%d-l%d,c%d",
4141                   @@3.first_line, @@3.first_column,
4142                   @@3.last_line, @@3.last_column);
4143        @}
4144    @}
4145@end group
4146@end example
4147
4148As for semantic values, there is a default action for locations that is
4149run each time a rule is matched.  It sets the beginning of @code{@@$} to the
4150beginning of the first symbol, and the end of @code{@@$} to the end of the
4151last symbol.
4152
4153With this default action, the location tracking can be fully automatic.  The
4154example above simply rewrites this way:
4155
4156@example
4157@group
4158exp:
4159  @dots{}
4160| exp '/' exp
4161    @{
4162      if ($3)
4163        $$ = $1 / $3;
4164      else
4165        @{
4166          $$ = 1;
4167          fprintf (stderr,
4168                   "Division by zero, l%d,c%d-l%d,c%d",
4169                   @@3.first_line, @@3.first_column,
4170                   @@3.last_line, @@3.last_column);
4171        @}
4172    @}
4173@end group
4174@end example
4175
4176@vindex yylloc
4177It is also possible to access the location of the lookahead token, if any,
4178from a semantic action.
4179This location is stored in @code{yylloc}.
4180@xref{Action Features, ,Special Features for Use in Actions}.
4181
4182@node Location Default Action
4183@subsection Default Action for Locations
4184@vindex YYLLOC_DEFAULT
4185@cindex GLR parsers and @code{YYLLOC_DEFAULT}
4186
4187Actually, actions are not the best place to compute locations.  Since
4188locations are much more general than semantic values, there is room in
4189the output parser to redefine the default action to take for each
4190rule.  The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
4191matched, before the associated action is run.  It is also invoked
4192while processing a syntax error, to compute the error's location.
4193Before reporting an unresolvable syntactic ambiguity, a GLR
4194parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
4195of that ambiguity.
4196
4197Most of the time, this macro is general enough to suppress location
4198dedicated code from semantic actions.
4199
4200The @code{YYLLOC_DEFAULT} macro takes three parameters.  The first one is
4201the location of the grouping (the result of the computation).  When a
4202rule is matched, the second parameter identifies locations of
4203all right hand side elements of the rule being matched, and the third
4204parameter is the size of the rule's right hand side.
4205When a GLR parser reports an ambiguity, which of multiple candidate
4206right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
4207When processing a syntax error, the second parameter identifies locations
4208of the symbols that were discarded during error processing, and the third
4209parameter is the number of discarded symbols.
4210
4211By default, @code{YYLLOC_DEFAULT} is defined this way:
4212
4213@example
4214@group
4215# define YYLLOC_DEFAULT(Cur, Rhs, N)                      \
4216do                                                        \
4217  if (N)                                                  \
4218    @{                                                     \
4219      (Cur).first_line   = YYRHSLOC(Rhs, 1).first_line;   \
4220      (Cur).first_column = YYRHSLOC(Rhs, 1).first_column; \
4221      (Cur).last_line    = YYRHSLOC(Rhs, N).last_line;    \
4222      (Cur).last_column  = YYRHSLOC(Rhs, N).last_column;  \
4223    @}                                                     \
4224  else                                                    \
4225    @{                                                     \
4226      (Cur).first_line   = (Cur).last_line   =            \
4227        YYRHSLOC(Rhs, 0).last_line;                       \
4228      (Cur).first_column = (Cur).last_column =            \
4229        YYRHSLOC(Rhs, 0).last_column;                     \
4230    @}                                                     \
4231while (0)
4232@end group
4233@end example
4234
4235@noindent
4236where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
4237in @var{rhs} when @var{k} is positive, and the location of the symbol
4238just before the reduction when @var{k} and @var{n} are both zero.
4239
4240When defining @code{YYLLOC_DEFAULT}, you should consider that:
4241
4242@itemize @bullet
4243@item
4244All arguments are free of side-effects.  However, only the first one (the
4245result) should be modified by @code{YYLLOC_DEFAULT}.
4246
4247@item
4248For consistency with semantic actions, valid indexes within the
4249right hand side range from 1 to @var{n}.  When @var{n} is zero, only 0 is a
4250valid index, and it refers to the symbol just before the reduction.
4251During error processing @var{n} is always positive.
4252
4253@item
4254Your macro should parenthesize its arguments, if need be, since the
4255actual arguments may not be surrounded by parentheses.  Also, your
4256macro should expand to something that can be used as a single
4257statement when it is followed by a semicolon.
4258@end itemize
4259
4260@node Named References
4261@section Named References
4262@cindex named references
4263
4264As described in the preceding sections, the traditional way to refer to any
4265semantic value or location is a @dfn{positional reference}, which takes the
4266form @code{$@var{n}}, @code{$$}, @code{@@@var{n}}, and @code{@@$}.  However,
4267such a reference is not very descriptive.  Moreover, if you later decide to
4268insert or remove symbols in the right-hand side of a grammar rule, the need
4269to renumber such references can be tedious and error-prone.
4270
4271To avoid these issues, you can also refer to a semantic value or location
4272using a @dfn{named reference}.  First of all, original symbol names may be
4273used as named references.  For example:
4274
4275@example
4276@group
4277invocation: op '(' args ')'
4278  @{ $invocation = new_invocation ($op, $args, @@invocation); @}
4279@end group
4280@end example
4281
4282@noindent
4283Positional and named references can be mixed arbitrarily.  For example:
4284
4285@example
4286@group
4287invocation: op '(' args ')'
4288  @{ $$ = new_invocation ($op, $args, @@$); @}
4289@end group
4290@end example
4291
4292@noindent
4293However, sometimes regular symbol names are not sufficient due to
4294ambiguities:
4295
4296@example
4297@group
4298exp: exp '/' exp
4299  @{ $exp = $exp / $exp; @} // $exp is ambiguous.
4300
4301exp: exp '/' exp
4302  @{ $$ = $1 / $exp; @} // One usage is ambiguous.
4303
4304exp: exp '/' exp
4305  @{ $$ = $1 / $3; @} // No error.
4306@end group
4307@end example
4308
4309@noindent
4310When ambiguity occurs, explicitly declared names may be used for values and
4311locations.  Explicit names are declared as a bracketed name after a symbol
4312appearance in rule definitions.  For example:
4313@example
4314@group
4315exp[result]: exp[left] '/' exp[right]
4316  @{ $result = $left / $right; @}
4317@end group
4318@end example
4319
4320@noindent
4321In order to access a semantic value generated by a mid-rule action, an
4322explicit name may also be declared by putting a bracketed name after the
4323closing brace of the mid-rule action code:
4324@example
4325@group
4326exp[res]: exp[x] '+' @{$left = $x;@}[left] exp[right]
4327  @{ $res = $left + $right; @}
4328@end group
4329@end example
4330
4331@noindent
4332
4333In references, in order to specify names containing dots and dashes, an explicit
4334bracketed syntax @code{$[name]} and @code{@@[name]} must be used:
4335@example
4336@group
4337if-stmt: "if" '(' expr ')' "then" then.stmt ';'
4338  @{ $[if-stmt] = new_if_stmt ($expr, $[then.stmt]); @}
4339@end group
4340@end example
4341
4342It often happens that named references are followed by a dot, dash or other
4343C punctuation marks and operators.  By default, Bison will read
4344@samp{$name.suffix} as a reference to symbol value @code{$name} followed by
4345@samp{.suffix}, i.e., an access to the @code{suffix} field of the semantic
4346value.  In order to force Bison to recognize @samp{name.suffix} in its
4347entirety as the name of a semantic value, the bracketed syntax
4348@samp{$[name.suffix]} must be used.
4349
4350The named references feature is experimental.  More user feedback will help
4351to stabilize it.
4352
4353@node Declarations
4354@section Bison Declarations
4355@cindex declarations, Bison
4356@cindex Bison declarations
4357
4358The @dfn{Bison declarations} section of a Bison grammar defines the symbols
4359used in formulating the grammar and the data types of semantic values.
4360@xref{Symbols}.
4361
4362All token type names (but not single-character literal tokens such as
4363@code{'+'} and @code{'*'}) must be declared.  Nonterminal symbols must be
4364declared if you need to specify which data type to use for the semantic
4365value (@pxref{Multiple Types, ,More Than One Value Type}).
4366
4367The first rule in the grammar file also specifies the start symbol, by
4368default.  If you want some other symbol to be the start symbol, you
4369must declare it explicitly (@pxref{Language and Grammar, ,Languages
4370and Context-Free Grammars}).
4371
4372@menu
4373* Require Decl::      Requiring a Bison version.
4374* Token Decl::        Declaring terminal symbols.
4375* Precedence Decl::   Declaring terminals with precedence and associativity.
4376* Union Decl::        Declaring the set of all semantic value types.
4377* Type Decl::         Declaring the choice of type for a nonterminal symbol.
4378* Initial Action Decl::  Code run before parsing starts.
4379* Destructor Decl::   Declaring how symbols are freed.
4380* Printer Decl::      Declaring how symbol values are displayed.
4381* Expect Decl::       Suppressing warnings about parsing conflicts.
4382* Start Decl::        Specifying the start symbol.
4383* Pure Decl::         Requesting a reentrant parser.
4384* Push Decl::         Requesting a push parser.
4385* Decl Summary::      Table of all Bison declarations.
4386* %define Summary::   Defining variables to adjust Bison's behavior.
4387* %code Summary::     Inserting code into the parser source.
4388@end menu
4389
4390@node Require Decl
4391@subsection Require a Version of Bison
4392@cindex version requirement
4393@cindex requiring a version of Bison
4394@findex %require
4395
4396You may require the minimum version of Bison to process the grammar.  If
4397the requirement is not met, @command{bison} exits with an error (exit
4398status 63).
4399
4400@example
4401%require "@var{version}"
4402@end example
4403
4404@node Token Decl
4405@subsection Token Type Names
4406@cindex declaring token type names
4407@cindex token type names, declaring
4408@cindex declaring literal string tokens
4409@findex %token
4410
4411The basic way to declare a token type name (terminal symbol) is as follows:
4412
4413@example
4414%token @var{name}
4415@end example
4416
4417Bison will convert this into a @code{#define} directive in
4418the parser, so that the function @code{yylex} (if it is in this file)
4419can use the name @var{name} to stand for this token type's code.
4420
4421Alternatively, you can use @code{%left}, @code{%right}, or
4422@code{%nonassoc} instead of @code{%token}, if you wish to specify
4423associativity and precedence.  @xref{Precedence Decl, ,Operator
4424Precedence}.
4425
4426You can explicitly specify the numeric code for a token type by appending
4427a nonnegative decimal or hexadecimal integer value in the field immediately
4428following the token name:
4429
4430@example
4431%token NUM 300
4432%token XNUM 0x12d // a GNU extension
4433@end example
4434
4435@noindent
4436It is generally best, however, to let Bison choose the numeric codes for
4437all token types.  Bison will automatically select codes that don't conflict
4438with each other or with normal characters.
4439
4440In the event that the stack type is a union, you must augment the
4441@code{%token} or other token declaration to include the data type
4442alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
4443Than One Value Type}).
4444
4445For example:
4446
4447@example
4448@group
4449%union @{              /* define stack type */
4450  double val;
4451  symrec *tptr;
4452@}
4453%token <val> NUM      /* define token NUM and its type */
4454@end group
4455@end example
4456
4457You can associate a literal string token with a token type name by
4458writing the literal string at the end of a @code{%token}
4459declaration which declares the name.  For example:
4460
4461@example
4462%token arrow "=>"
4463@end example
4464
4465@noindent
4466For example, a grammar for the C language might specify these names with
4467equivalent literal string tokens:
4468
4469@example
4470%token  <operator>  OR      "||"
4471%token  <operator>  LE 134  "<="
4472%left  OR  "<="
4473@end example
4474
4475@noindent
4476Once you equate the literal string and the token name, you can use them
4477interchangeably in further declarations or the grammar rules.  The
4478@code{yylex} function can use the token name or the literal string to
4479obtain the token type code number (@pxref{Calling Convention}).
4480Syntax error messages passed to @code{yyerror} from the parser will reference
4481the literal string instead of the token name.
4482
4483The token numbered as 0 corresponds to end of file; the following line
4484allows for nicer error messages referring to ``end of file'' instead
4485of ``$end'':
4486
4487@example
4488%token END 0 "end of file"
4489@end example
4490
4491@node Precedence Decl
4492@subsection Operator Precedence
4493@cindex precedence declarations
4494@cindex declaring operator precedence
4495@cindex operator precedence, declaring
4496
4497Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
4498declare a token and specify its precedence and associativity, all at
4499once.  These are called @dfn{precedence declarations}.
4500@xref{Precedence, ,Operator Precedence}, for general information on
4501operator precedence.
4502
4503The syntax of a precedence declaration is nearly the same as that of
4504@code{%token}: either
4505
4506@example
4507%left @var{symbols}@dots{}
4508@end example
4509
4510@noindent
4511or
4512
4513@example
4514%left <@var{type}> @var{symbols}@dots{}
4515@end example
4516
4517And indeed any of these declarations serves the purposes of @code{%token}.
4518But in addition, they specify the associativity and relative precedence for
4519all the @var{symbols}:
4520
4521@itemize @bullet
4522@item
4523The associativity of an operator @var{op} determines how repeated uses
4524of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
4525@var{z}} is parsed by grouping @var{x} with @var{y} first or by
4526grouping @var{y} with @var{z} first.  @code{%left} specifies
4527left-associativity (grouping @var{x} with @var{y} first) and
4528@code{%right} specifies right-associativity (grouping @var{y} with
4529@var{z} first).  @code{%nonassoc} specifies no associativity, which
4530means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
4531considered a syntax error.
4532
4533@item
4534The precedence of an operator determines how it nests with other operators.
4535All the tokens declared in a single precedence declaration have equal
4536precedence and nest together according to their associativity.
4537When two tokens declared in different precedence declarations associate,
4538the one declared later has the higher precedence and is grouped first.
4539@end itemize
4540
4541For backward compatibility, there is a confusing difference between the
4542argument lists of @code{%token} and precedence declarations.
4543Only a @code{%token} can associate a literal string with a token type name.
4544A precedence declaration always interprets a literal string as a reference to a
4545separate token.
4546For example:
4547
4548@example
4549%left  OR "<="         // Does not declare an alias.
4550%left  OR 134 "<=" 135 // Declares 134 for OR and 135 for "<=".
4551@end example
4552
4553@node Union Decl
4554@subsection The Collection of Value Types
4555@cindex declaring value types
4556@cindex value types, declaring
4557@findex %union
4558
4559The @code{%union} declaration specifies the entire collection of
4560possible data types for semantic values.  The keyword @code{%union} is
4561followed by braced code containing the same thing that goes inside a
4562@code{union} in C@.
4563
4564For example:
4565
4566@example
4567@group
4568%union @{
4569  double val;
4570  symrec *tptr;
4571@}
4572@end group
4573@end example
4574
4575@noindent
4576This says that the two alternative types are @code{double} and @code{symrec
4577*}.  They are given names @code{val} and @code{tptr}; these names are used
4578in the @code{%token} and @code{%type} declarations to pick one of the types
4579for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
4580
4581As an extension to POSIX, a tag is allowed after the
4582@code{union}.  For example:
4583
4584@example
4585@group
4586%union value @{
4587  double val;
4588  symrec *tptr;
4589@}
4590@end group
4591@end example
4592
4593@noindent
4594specifies the union tag @code{value}, so the corresponding C type is
4595@code{union value}.  If you do not specify a tag, it defaults to
4596@code{YYSTYPE}.
4597
4598As another extension to POSIX, you may specify multiple
4599@code{%union} declarations; their contents are concatenated.  However,
4600only the first @code{%union} declaration can specify a tag.
4601
4602Note that, unlike making a @code{union} declaration in C, you need not write
4603a semicolon after the closing brace.
4604
4605Instead of @code{%union}, you can define and use your own union type
4606@code{YYSTYPE} if your grammar contains at least one
4607@samp{<@var{type}>} tag.  For example, you can put the following into
4608a header file @file{parser.h}:
4609
4610@example
4611@group
4612union YYSTYPE @{
4613  double val;
4614  symrec *tptr;
4615@};
4616typedef union YYSTYPE YYSTYPE;
4617@end group
4618@end example
4619
4620@noindent
4621and then your grammar can use the following
4622instead of @code{%union}:
4623
4624@example
4625@group
4626%@{
4627#include "parser.h"
4628%@}
4629%type <val> expr
4630%token <tptr> ID
4631@end group
4632@end example
4633
4634@node Type Decl
4635@subsection Nonterminal Symbols
4636@cindex declaring value types, nonterminals
4637@cindex value types, nonterminals, declaring
4638@findex %type
4639
4640@noindent
4641When you use @code{%union} to specify multiple value types, you must
4642declare the value type of each nonterminal symbol for which values are
4643used.  This is done with a @code{%type} declaration, like this:
4644
4645@example
4646%type <@var{type}> @var{nonterminal}@dots{}
4647@end example
4648
4649@noindent
4650Here @var{nonterminal} is the name of a nonterminal symbol, and
4651@var{type} is the name given in the @code{%union} to the alternative
4652that you want (@pxref{Union Decl, ,The Collection of Value Types}).  You
4653can give any number of nonterminal symbols in the same @code{%type}
4654declaration, if they have the same value type.  Use spaces to separate
4655the symbol names.
4656
4657You can also declare the value type of a terminal symbol.  To do this,
4658use the same @code{<@var{type}>} construction in a declaration for the
4659terminal symbol.  All kinds of token declarations allow
4660@code{<@var{type}>}.
4661
4662@node Initial Action Decl
4663@subsection Performing Actions before Parsing
4664@findex %initial-action
4665
4666Sometimes your parser needs to perform some initializations before
4667parsing.  The @code{%initial-action} directive allows for such arbitrary
4668code.
4669
4670@deffn {Directive} %initial-action @{ @var{code} @}
4671@findex %initial-action
4672Declare that the braced @var{code} must be invoked before parsing each time
4673@code{yyparse} is called.  The @var{code} may use @code{$$} (or
4674@code{$<@var{tag}>$}) and @code{@@$} --- initial value and location of the
4675lookahead --- and the @code{%parse-param}.
4676@end deffn
4677
4678For instance, if your locations use a file name, you may use
4679
4680@example
4681%parse-param @{ char const *file_name @};
4682%initial-action
4683@{
4684  @@$.initialize (file_name);
4685@};
4686@end example
4687
4688
4689@node Destructor Decl
4690@subsection Freeing Discarded Symbols
4691@cindex freeing discarded symbols
4692@findex %destructor
4693@findex <*>
4694@findex <>
4695During error recovery (@pxref{Error Recovery}), symbols already pushed
4696on the stack and tokens coming from the rest of the file are discarded
4697until the parser falls on its feet.  If the parser runs out of memory,
4698or if it returns via @code{YYABORT} or @code{YYACCEPT}, all the
4699symbols on the stack must be discarded.  Even if the parser succeeds, it
4700must discard the start symbol.
4701
4702When discarded symbols convey heap based information, this memory is
4703lost.  While this behavior can be tolerable for batch parsers, such as
4704in traditional compilers, it is unacceptable for programs like shells or
4705protocol implementations that may parse and execute indefinitely.
4706
4707The @code{%destructor} directive defines code that is called when a
4708symbol is automatically discarded.
4709
4710@deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
4711@findex %destructor
4712Invoke the braced @var{code} whenever the parser discards one of the
4713@var{symbols}.  Within @var{code}, @code{$$} (or @code{$<@var{tag}>$})
4714designates the semantic value associated with the discarded symbol, and
4715@code{@@$} designates its location.  The additional parser parameters are
4716also available (@pxref{Parser Function, , The Parser Function
4717@code{yyparse}}).
4718
4719When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
4720per-symbol @code{%destructor}.
4721You may also define a per-type @code{%destructor} by listing a semantic type
4722tag among @var{symbols}.
4723In that case, the parser will invoke this @var{code} whenever it discards any
4724grammar symbol that has that semantic type tag unless that symbol has its own
4725per-symbol @code{%destructor}.
4726
4727Finally, you can define two different kinds of default @code{%destructor}s.
4728(These default forms are experimental.
4729More user feedback will help to determine whether they should become permanent
4730features.)
4731You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
4732exactly one @code{%destructor} declaration in your grammar file.
4733The parser will invoke the @var{code} associated with one of these whenever it
4734discards any user-defined grammar symbol that has no per-symbol and no per-type
4735@code{%destructor}.
4736The parser uses the @var{code} for @code{<*>} in the case of such a grammar
4737symbol for which you have formally declared a semantic type tag (@code{%type}
4738counts as such a declaration, but @code{$<tag>$} does not).
4739The parser uses the @var{code} for @code{<>} in the case of such a grammar
4740symbol that has no declared semantic type tag.
4741@end deffn
4742
4743@noindent
4744For example:
4745
4746@example
4747%union @{ char *string; @}
4748%token <string> STRING1
4749%token <string> STRING2
4750%type  <string> string1
4751%type  <string> string2
4752%union @{ char character; @}
4753%token <character> CHR
4754%type  <character> chr
4755%token TAGLESS
4756
4757%destructor @{ @} <character>
4758%destructor @{ free ($$); @} <*>
4759%destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
4760%destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
4761@end example
4762
4763@noindent
4764guarantees that, when the parser discards any user-defined symbol that has a
4765semantic type tag other than @code{<character>}, it passes its semantic value
4766to @code{free} by default.
4767However, when the parser discards a @code{STRING1} or a @code{string1}, it also
4768prints its line number to @code{stdout}.
4769It performs only the second @code{%destructor} in this case, so it invokes
4770@code{free} only once.
4771Finally, the parser merely prints a message whenever it discards any symbol,
4772such as @code{TAGLESS}, that has no semantic type tag.
4773
4774A Bison-generated parser invokes the default @code{%destructor}s only for
4775user-defined as opposed to Bison-defined symbols.
4776For example, the parser will not invoke either kind of default
4777@code{%destructor} for the special Bison-defined symbols @code{$accept},
4778@code{$undefined}, or @code{$end} (@pxref{Table of Symbols, ,Bison Symbols}),
4779none of which you can reference in your grammar.
4780It also will not invoke either for the @code{error} token (@pxref{Table of
4781Symbols, ,error}), which is always defined by Bison regardless of whether you
4782reference it in your grammar.
4783However, it may invoke one of them for the end token (token 0) if you
4784redefine it from @code{$end} to, for example, @code{END}:
4785
4786@example
4787%token END 0
4788@end example
4789
4790@cindex actions in mid-rule
4791@cindex mid-rule actions
4792Finally, Bison will never invoke a @code{%destructor} for an unreferenced
4793mid-rule semantic value (@pxref{Mid-Rule Actions,,Actions in Mid-Rule}).
4794That is, Bison does not consider a mid-rule to have a semantic value if you
4795do not reference @code{$$} in the mid-rule's action or @code{$@var{n}}
4796(where @var{n} is the right-hand side symbol position of the mid-rule) in
4797any later action in that rule.  However, if you do reference either, the
4798Bison-generated parser will invoke the @code{<>} @code{%destructor} whenever
4799it discards the mid-rule symbol.
4800
4801@ignore
4802@noindent
4803In the future, it may be possible to redefine the @code{error} token as a
4804nonterminal that captures the discarded symbols.
4805In that case, the parser will invoke the default destructor for it as well.
4806@end ignore
4807
4808@sp 1
4809
4810@cindex discarded symbols
4811@dfn{Discarded symbols} are the following:
4812
4813@itemize
4814@item
4815stacked symbols popped during the first phase of error recovery,
4816@item
4817incoming terminals during the second phase of error recovery,
4818@item
4819the current lookahead and the entire stack (except the current
4820right-hand side symbols) when the parser returns immediately, and
4821@item
4822the current lookahead and the entire stack (including the current right-hand
4823side symbols) when the C++ parser (@file{lalr1.cc}) catches an exception in
4824@code{parse},
4825@item
4826the start symbol, when the parser succeeds.
4827@end itemize
4828
4829The parser can @dfn{return immediately} because of an explicit call to
4830@code{YYABORT} or @code{YYACCEPT}, or failed error recovery, or memory
4831exhaustion.
4832
4833Right-hand side symbols of a rule that explicitly triggers a syntax
4834error via @code{YYERROR} are not discarded automatically.  As a rule
4835of thumb, destructors are invoked only when user actions cannot manage
4836the memory.
4837
4838@node Printer Decl
4839@subsection Printing Semantic Values
4840@cindex printing semantic values
4841@findex %printer
4842@findex <*>
4843@findex <>
4844When run-time traces are enabled (@pxref{Tracing, ,Tracing Your Parser}),
4845the parser reports its actions, such as reductions.  When a symbol involved
4846in an action is reported, only its kind is displayed, as the parser cannot
4847know how semantic values should be formatted.
4848
4849The @code{%printer} directive defines code that is called when a symbol is
4850reported.  Its syntax is the same as @code{%destructor} (@pxref{Destructor
4851Decl, , Freeing Discarded Symbols}).
4852
4853@deffn {Directive} %printer @{ @var{code} @} @var{symbols}
4854@findex %printer
4855@vindex yyoutput
4856@c This is the same text as for %destructor.
4857Invoke the braced @var{code} whenever the parser displays one of the
4858@var{symbols}.  Within @var{code}, @code{yyoutput} denotes the output stream
4859(a @code{FILE*} in C, and an @code{std::ostream&} in C++), @code{$$} (or
4860@code{$<@var{tag}>$}) designates the semantic value associated with the
4861symbol, and @code{@@$} its location.  The additional parser parameters are
4862also available (@pxref{Parser Function, , The Parser Function
4863@code{yyparse}}).
4864
4865The @var{symbols} are defined as for @code{%destructor} (@pxref{Destructor
4866Decl, , Freeing Discarded Symbols}.): they can be per-type (e.g.,
4867@samp{<ival>}), per-symbol (e.g., @samp{exp}, @samp{NUM}, @samp{"float"}),
4868typed per-default (i.e., @samp{<*>}, or untyped per-default (i.e.,
4869@samp{<>}).
4870@end deffn
4871
4872@noindent
4873For example:
4874
4875@example
4876%union @{ char *string; @}
4877%token <string> STRING1
4878%token <string> STRING2
4879%type  <string> string1
4880%type  <string> string2
4881%union @{ char character; @}
4882%token <character> CHR
4883%type  <character> chr
4884%token TAGLESS
4885
4886%printer @{ fprintf (yyoutput, "'%c'", $$); @} <character>
4887%printer @{ fprintf (yyoutput, "&%p", $$); @} <*>
4888%printer @{ fprintf (yyoutput, "\"%s\"", $$); @} STRING1 string1
4889%printer @{ fprintf (yyoutput, "<>"); @} <>
4890@end example
4891
4892@noindent
4893guarantees that, when the parser print any symbol that has a semantic type
4894tag other than @code{<character>}, it display the address of the semantic
4895value by default.  However, when the parser displays a @code{STRING1} or a
4896@code{string1}, it formats it as a string in double quotes.  It performs
4897only the second @code{%printer} in this case, so it prints only once.
4898Finally, the parser print @samp{<>} for any symbol, such as @code{TAGLESS},
4899that has no semantic type tag.  See also
4900
4901
4902@node Expect Decl
4903@subsection Suppressing Conflict Warnings
4904@cindex suppressing conflict warnings
4905@cindex preventing warnings about conflicts
4906@cindex warnings, preventing
4907@cindex conflicts, suppressing warnings of
4908@findex %expect
4909@findex %expect-rr
4910
4911Bison normally warns if there are any conflicts in the grammar
4912(@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
4913have harmless shift/reduce conflicts which are resolved in a predictable
4914way and would be difficult to eliminate.  It is desirable to suppress
4915the warning about these conflicts unless the number of conflicts
4916changes.  You can do this with the @code{%expect} declaration.
4917
4918The declaration looks like this:
4919
4920@example
4921%expect @var{n}
4922@end example
4923
4924Here @var{n} is a decimal integer.  The declaration says there should
4925be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
4926Bison reports an error if the number of shift/reduce conflicts differs
4927from @var{n}, or if there are any reduce/reduce conflicts.
4928
4929For deterministic parsers, reduce/reduce conflicts are more
4930serious, and should be eliminated entirely.  Bison will always report
4931reduce/reduce conflicts for these parsers.  With GLR
4932parsers, however, both kinds of conflicts are routine; otherwise,
4933there would be no need to use GLR parsing.  Therefore, it is
4934also possible to specify an expected number of reduce/reduce conflicts
4935in GLR parsers, using the declaration:
4936
4937@example
4938%expect-rr @var{n}
4939@end example
4940
4941In general, using @code{%expect} involves these steps:
4942
4943@itemize @bullet
4944@item
4945Compile your grammar without @code{%expect}.  Use the @samp{-v} option
4946to get a verbose list of where the conflicts occur.  Bison will also
4947print the number of conflicts.
4948
4949@item
4950Check each of the conflicts to make sure that Bison's default
4951resolution is what you really want.  If not, rewrite the grammar and
4952go back to the beginning.
4953
4954@item
4955Add an @code{%expect} declaration, copying the number @var{n} from the
4956number which Bison printed.  With GLR parsers, add an
4957@code{%expect-rr} declaration as well.
4958@end itemize
4959
4960Now Bison will report an error if you introduce an unexpected conflict,
4961but will keep silent otherwise.
4962
4963@node Start Decl
4964@subsection The Start-Symbol
4965@cindex declaring the start symbol
4966@cindex start symbol, declaring
4967@cindex default start symbol
4968@findex %start
4969
4970Bison assumes by default that the start symbol for the grammar is the first
4971nonterminal specified in the grammar specification section.  The programmer
4972may override this restriction with the @code{%start} declaration as follows:
4973
4974@example
4975%start @var{symbol}
4976@end example
4977
4978@node Pure Decl
4979@subsection A Pure (Reentrant) Parser
4980@cindex reentrant parser
4981@cindex pure parser
4982@findex %define api.pure
4983
4984A @dfn{reentrant} program is one which does not alter in the course of
4985execution; in other words, it consists entirely of @dfn{pure} (read-only)
4986code.  Reentrancy is important whenever asynchronous execution is possible;
4987for example, a nonreentrant program may not be safe to call from a signal
4988handler.  In systems with multiple threads of control, a nonreentrant
4989program must be called only within interlocks.
4990
4991Normally, Bison generates a parser which is not reentrant.  This is
4992suitable for most uses, and it permits compatibility with Yacc.  (The
4993standard Yacc interfaces are inherently nonreentrant, because they use
4994statically allocated variables for communication with @code{yylex},
4995including @code{yylval} and @code{yylloc}.)
4996
4997Alternatively, you can generate a pure, reentrant parser.  The Bison
4998declaration @code{%define api.pure} says that you want the parser to be
4999reentrant.  It looks like this:
5000
5001@example
5002%define api.pure full
5003@end example
5004
5005The result is that the communication variables @code{yylval} and
5006@code{yylloc} become local variables in @code{yyparse}, and a different
5007calling convention is used for the lexical analyzer function
5008@code{yylex}.  @xref{Pure Calling, ,Calling Conventions for Pure
5009Parsers}, for the details of this.  The variable @code{yynerrs}
5010becomes local in @code{yyparse} in pull mode but it becomes a member
5011of yypstate in push mode.  (@pxref{Error Reporting, ,The Error
5012Reporting Function @code{yyerror}}).  The convention for calling
5013@code{yyparse} itself is unchanged.
5014
5015Whether the parser is pure has nothing to do with the grammar rules.
5016You can generate either a pure parser or a nonreentrant parser from any
5017valid grammar.
5018
5019@node Push Decl
5020@subsection A Push Parser
5021@cindex push parser
5022@cindex push parser
5023@findex %define api.push-pull
5024
5025(The current push parsing interface is experimental and may evolve.
5026More user feedback will help to stabilize it.)
5027
5028A pull parser is called once and it takes control until all its input
5029is completely parsed.  A push parser, on the other hand, is called
5030each time a new token is made available.
5031
5032A push parser is typically useful when the parser is part of a
5033main event loop in the client's application.  This is typically
5034a requirement of a GUI, when the main event loop needs to be triggered
5035within a certain time period.
5036
5037Normally, Bison generates a pull parser.
5038The following Bison declaration says that you want the parser to be a push
5039parser (@pxref{%define Summary,,api.push-pull}):
5040
5041@example
5042%define api.push-pull push
5043@end example
5044
5045In almost all cases, you want to ensure that your push parser is also
5046a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).  The only
5047time you should create an impure push parser is to have backwards
5048compatibility with the impure Yacc pull mode interface.  Unless you know
5049what you are doing, your declarations should look like this:
5050
5051@example
5052%define api.pure full
5053%define api.push-pull push
5054@end example
5055
5056There is a major notable functional difference between the pure push parser
5057and the impure push parser.  It is acceptable for a pure push parser to have
5058many parser instances, of the same type of parser, in memory at the same time.
5059An impure push parser should only use one parser at a time.
5060
5061When a push parser is selected, Bison will generate some new symbols in
5062the generated parser.  @code{yypstate} is a structure that the generated
5063parser uses to store the parser's state.  @code{yypstate_new} is the
5064function that will create a new parser instance.  @code{yypstate_delete}
5065will free the resources associated with the corresponding parser instance.
5066Finally, @code{yypush_parse} is the function that should be called whenever a
5067token is available to provide the parser.  A trivial example
5068of using a pure push parser would look like this:
5069
5070@example
5071int status;
5072yypstate *ps = yypstate_new ();
5073do @{
5074  status = yypush_parse (ps, yylex (), NULL);
5075@} while (status == YYPUSH_MORE);
5076yypstate_delete (ps);
5077@end example
5078
5079If the user decided to use an impure push parser, a few things about
5080the generated parser will change.  The @code{yychar} variable becomes
5081a global variable instead of a variable in the @code{yypush_parse} function.
5082For this reason, the signature of the @code{yypush_parse} function is
5083changed to remove the token as a parameter.  A nonreentrant push parser
5084example would thus look like this:
5085
5086@example
5087extern int yychar;
5088int status;
5089yypstate *ps = yypstate_new ();
5090do @{
5091  yychar = yylex ();
5092  status = yypush_parse (ps);
5093@} while (status == YYPUSH_MORE);
5094yypstate_delete (ps);
5095@end example
5096
5097That's it. Notice the next token is put into the global variable @code{yychar}
5098for use by the next invocation of the @code{yypush_parse} function.
5099
5100Bison also supports both the push parser interface along with the pull parser
5101interface in the same generated parser.  In order to get this functionality,
5102you should replace the @code{%define api.push-pull push} declaration with the
5103@code{%define api.push-pull both} declaration.  Doing this will create all of
5104the symbols mentioned earlier along with the two extra symbols, @code{yyparse}
5105and @code{yypull_parse}.  @code{yyparse} can be used exactly as it normally
5106would be used.  However, the user should note that it is implemented in the
5107generated parser by calling @code{yypull_parse}.
5108This makes the @code{yyparse} function that is generated with the
5109@code{%define api.push-pull both} declaration slower than the normal
5110@code{yyparse} function.  If the user
5111calls the @code{yypull_parse} function it will parse the rest of the input
5112stream.  It is possible to @code{yypush_parse} tokens to select a subgrammar
5113and then @code{yypull_parse} the rest of the input stream.  If you would like
5114to switch back and forth between between parsing styles, you would have to
5115write your own @code{yypull_parse} function that knows when to quit looking
5116for input.  An example of using the @code{yypull_parse} function would look
5117like this:
5118
5119@example
5120yypstate *ps = yypstate_new ();
5121yypull_parse (ps); /* Will call the lexer */
5122yypstate_delete (ps);
5123@end example
5124
5125Adding the @code{%define api.pure full} declaration does exactly the same thing
5126to the generated parser with @code{%define api.push-pull both} as it did for
5127@code{%define api.push-pull push}.
5128
5129@node Decl Summary
5130@subsection Bison Declaration Summary
5131@cindex Bison declaration summary
5132@cindex declaration summary
5133@cindex summary, Bison declaration
5134
5135Here is a summary of the declarations used to define a grammar:
5136
5137@deffn {Directive} %union
5138Declare the collection of data types that semantic values may have
5139(@pxref{Union Decl, ,The Collection of Value Types}).
5140@end deffn
5141
5142@deffn {Directive} %token
5143Declare a terminal symbol (token type name) with no precedence
5144or associativity specified (@pxref{Token Decl, ,Token Type Names}).
5145@end deffn
5146
5147@deffn {Directive} %right
5148Declare a terminal symbol (token type name) that is right-associative
5149(@pxref{Precedence Decl, ,Operator Precedence}).
5150@end deffn
5151
5152@deffn {Directive} %left
5153Declare a terminal symbol (token type name) that is left-associative
5154(@pxref{Precedence Decl, ,Operator Precedence}).
5155@end deffn
5156
5157@deffn {Directive} %nonassoc
5158Declare a terminal symbol (token type name) that is nonassociative
5159(@pxref{Precedence Decl, ,Operator Precedence}).
5160Using it in a way that would be associative is a syntax error.
5161@end deffn
5162
5163@ifset defaultprec
5164@deffn {Directive} %default-prec
5165Assign a precedence to rules lacking an explicit @code{%prec} modifier
5166(@pxref{Contextual Precedence, ,Context-Dependent Precedence}).
5167@end deffn
5168@end ifset
5169
5170@deffn {Directive} %type
5171Declare the type of semantic values for a nonterminal symbol
5172(@pxref{Type Decl, ,Nonterminal Symbols}).
5173@end deffn
5174
5175@deffn {Directive} %start
5176Specify the grammar's start symbol (@pxref{Start Decl, ,The
5177Start-Symbol}).
5178@end deffn
5179
5180@deffn {Directive} %expect
5181Declare the expected number of shift-reduce conflicts
5182(@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
5183@end deffn
5184
5185
5186@sp 1
5187@noindent
5188In order to change the behavior of @command{bison}, use the following
5189directives:
5190
5191@deffn {Directive} %code @{@var{code}@}
5192@deffnx {Directive} %code @var{qualifier} @{@var{code}@}
5193@findex %code
5194Insert @var{code} verbatim into the output parser source at the
5195default location or at the location specified by @var{qualifier}.
5196@xref{%code Summary}.
5197@end deffn
5198
5199@deffn {Directive} %debug
5200In the parser implementation file, define the macro @code{YYDEBUG} (or
5201@code{@var{prefix}DEBUG} with @samp{%define api.prefix @var{prefix}}, see
5202@ref{Multiple Parsers, ,Multiple Parsers in the Same Program}) to 1 if it is
5203not already defined, so that the debugging facilities are compiled.
5204@xref{Tracing, ,Tracing Your Parser}.
5205@end deffn
5206
5207@deffn {Directive} %define @var{variable}
5208@deffnx {Directive} %define @var{variable} @var{value}
5209@deffnx {Directive} %define @var{variable} "@var{value}"
5210Define a variable to adjust Bison's behavior.  @xref{%define Summary}.
5211@end deffn
5212
5213@deffn {Directive} %defines
5214Write a parser header file containing macro definitions for the token
5215type names defined in the grammar as well as a few other declarations.
5216If the parser implementation file is named @file{@var{name}.c} then
5217the parser header file is named @file{@var{name}.h}.
5218
5219For C parsers, the parser header file declares @code{YYSTYPE} unless
5220@code{YYSTYPE} is already defined as a macro or you have used a
5221@code{<@var{type}>} tag without using @code{%union}.  Therefore, if
5222you are using a @code{%union} (@pxref{Multiple Types, ,More Than One
5223Value Type}) with components that require other definitions, or if you
5224have defined a @code{YYSTYPE} macro or type definition (@pxref{Value
5225Type, ,Data Types of Semantic Values}), you need to arrange for these
5226definitions to be propagated to all modules, e.g., by putting them in
5227a prerequisite header that is included both by your parser and by any
5228other module that needs @code{YYSTYPE}.
5229
5230Unless your parser is pure, the parser header file declares
5231@code{yylval} as an external variable.  @xref{Pure Decl, ,A Pure
5232(Reentrant) Parser}.
5233
5234If you have also used locations, the parser header file declares
5235@code{YYLTYPE} and @code{yylloc} using a protocol similar to that of the
5236@code{YYSTYPE} macro and @code{yylval}.  @xref{Tracking Locations}.
5237
5238This parser header file is normally essential if you wish to put the
5239definition of @code{yylex} in a separate source file, because
5240@code{yylex} typically needs to be able to refer to the
5241above-mentioned declarations and to the token type codes.  @xref{Token
5242Values, ,Semantic Values of Tokens}.
5243
5244@findex %code requires
5245@findex %code provides
5246If you have declared @code{%code requires} or @code{%code provides}, the output
5247header also contains their code.
5248@xref{%code Summary}.
5249
5250@cindex Header guard
5251The generated header is protected against multiple inclusions with a C
5252preprocessor guard: @samp{YY_@var{PREFIX}_@var{FILE}_INCLUDED}, where
5253@var{PREFIX} and @var{FILE} are the prefix (@pxref{Multiple Parsers,
5254,Multiple Parsers in the Same Program}) and generated file name turned
5255uppercase, with each series of non alphanumerical characters converted to a
5256single underscore.
5257
5258For instance with @samp{%define api.prefix "calc"} and @samp{%defines
5259"lib/parse.h"}, the header will be guarded as follows.
5260@example
5261#ifndef YY_CALC_LIB_PARSE_H_INCLUDED
5262# define YY_CALC_LIB_PARSE_H_INCLUDED
5263...
5264#endif /* ! YY_CALC_LIB_PARSE_H_INCLUDED */
5265@end example
5266@end deffn
5267
5268@deffn {Directive} %defines @var{defines-file}
5269Same as above, but save in the file @var{defines-file}.
5270@end deffn
5271
5272@deffn {Directive} %destructor
5273Specify how the parser should reclaim the memory associated to
5274discarded symbols.  @xref{Destructor Decl, , Freeing Discarded Symbols}.
5275@end deffn
5276
5277@deffn {Directive} %file-prefix "@var{prefix}"
5278Specify a prefix to use for all Bison output file names.  The names
5279are chosen as if the grammar file were named @file{@var{prefix}.y}.
5280@end deffn
5281
5282@deffn {Directive} %language "@var{language}"
5283Specify the programming language for the generated parser.  Currently
5284supported languages include C, C++, and Java.
5285@var{language} is case-insensitive.
5286
5287@end deffn
5288
5289@deffn {Directive} %locations
5290Generate the code processing the locations (@pxref{Action Features,
5291,Special Features for Use in Actions}).  This mode is enabled as soon as
5292the grammar uses the special @samp{@@@var{n}} tokens, but if your
5293grammar does not use it, using @samp{%locations} allows for more
5294accurate syntax error messages.
5295@end deffn
5296
5297@ifset defaultprec
5298@deffn {Directive} %no-default-prec
5299Do not assign a precedence to rules lacking an explicit @code{%prec}
5300modifier (@pxref{Contextual Precedence, ,Context-Dependent
5301Precedence}).
5302@end deffn
5303@end ifset
5304
5305@deffn {Directive} %no-lines
5306Don't generate any @code{#line} preprocessor commands in the parser
5307implementation file.  Ordinarily Bison writes these commands in the
5308parser implementation file so that the C compiler and debuggers will
5309associate errors and object code with your source file (the grammar
5310file).  This directive causes them to associate errors with the parser
5311implementation file, treating it as an independent source file in its
5312own right.
5313@end deffn
5314
5315@deffn {Directive} %output "@var{file}"
5316Specify @var{file} for the parser implementation file.
5317@end deffn
5318
5319@deffn {Directive} %pure-parser
5320Deprecated version of @code{%define api.pure} (@pxref{%define
5321Summary,,api.pure}), for which Bison is more careful to warn about
5322unreasonable usage.
5323@end deffn
5324
5325@deffn {Directive} %require "@var{version}"
5326Require version @var{version} or higher of Bison.  @xref{Require Decl, ,
5327Require a Version of Bison}.
5328@end deffn
5329
5330@deffn {Directive} %skeleton "@var{file}"
5331Specify the skeleton to use.
5332
5333@c You probably don't need this option unless you are developing Bison.
5334@c You should use @code{%language} if you want to specify the skeleton for a
5335@c different language, because it is clearer and because it will always choose the
5336@c correct skeleton for non-deterministic or push parsers.
5337
5338If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
5339file in the Bison installation directory.
5340If it does, @var{file} is an absolute file name or a file name relative to the
5341directory of the grammar file.
5342This is similar to how most shells resolve commands.
5343@end deffn
5344
5345@deffn {Directive} %token-table
5346Generate an array of token names in the parser implementation file.
5347The name of the array is @code{yytname}; @code{yytname[@var{i}]} is
5348the name of the token whose internal Bison token code number is
5349@var{i}.  The first three elements of @code{yytname} correspond to the
5350predefined tokens @code{"$end"}, @code{"error"}, and
5351@code{"$undefined"}; after these come the symbols defined in the
5352grammar file.
5353
5354The name in the table includes all the characters needed to represent
5355the token in Bison.  For single-character literals and literal
5356strings, this includes the surrounding quoting characters and any
5357escape sequences.  For example, the Bison single-character literal
5358@code{'+'} corresponds to a three-character name, represented in C as
5359@code{"'+'"}; and the Bison two-character literal string @code{"\\/"}
5360corresponds to a five-character name, represented in C as
5361@code{"\"\\\\/\""}.
5362
5363When you specify @code{%token-table}, Bison also generates macro
5364definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
5365@code{YYNRULES}, and @code{YYNSTATES}:
5366
5367@table @code
5368@item YYNTOKENS
5369The highest token number, plus one.
5370@item YYNNTS
5371The number of nonterminal symbols.
5372@item YYNRULES
5373The number of grammar rules,
5374@item YYNSTATES
5375The number of parser states (@pxref{Parser States}).
5376@end table
5377@end deffn
5378
5379@deffn {Directive} %verbose
5380Write an extra output file containing verbose descriptions of the
5381parser states and what is done for each type of lookahead token in
5382that state.  @xref{Understanding, , Understanding Your Parser}, for more
5383information.
5384@end deffn
5385
5386@deffn {Directive} %yacc
5387Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
5388including its naming conventions.  @xref{Bison Options}, for more.
5389@end deffn
5390
5391
5392@node %define Summary
5393@subsection %define Summary
5394
5395There are many features of Bison's behavior that can be controlled by
5396assigning the feature a single value.  For historical reasons, some
5397such features are assigned values by dedicated directives, such as
5398@code{%start}, which assigns the start symbol.  However, newer such
5399features are associated with variables, which are assigned by the
5400@code{%define} directive:
5401
5402@deffn {Directive} %define @var{variable}
5403@deffnx {Directive} %define @var{variable} @var{value}
5404@deffnx {Directive} %define @var{variable} "@var{value}"
5405Define @var{variable} to @var{value}.
5406
5407@var{value} must be placed in quotation marks if it contains any
5408character other than a letter, underscore, period, or non-initial dash
5409or digit.  Omitting @code{"@var{value}"} entirely is always equivalent
5410to specifying @code{""}.
5411
5412It is an error if a @var{variable} is defined by @code{%define}
5413multiple times, but see @ref{Bison Options,,-D
5414@var{name}[=@var{value}]}.
5415@end deffn
5416
5417The rest of this section summarizes variables and values that
5418@code{%define} accepts.
5419
5420Some @var{variable}s take Boolean values.  In this case, Bison will
5421complain if the variable definition does not meet one of the following
5422four conditions:
5423
5424@enumerate
5425@item @code{@var{value}} is @code{true}
5426
5427@item @code{@var{value}} is omitted (or @code{""} is specified).
5428This is equivalent to @code{true}.
5429
5430@item @code{@var{value}} is @code{false}.
5431
5432@item @var{variable} is never defined.
5433In this case, Bison selects a default value.
5434@end enumerate
5435
5436What @var{variable}s are accepted, as well as their meanings and default
5437values, depend on the selected target language and/or the parser
5438skeleton (@pxref{Decl Summary,,%language}, @pxref{Decl
5439Summary,,%skeleton}).
5440Unaccepted @var{variable}s produce an error.
5441Some of the accepted @var{variable}s are:
5442
5443@itemize @bullet
5444@c ================================================== api.location.type
5445@item @code{api.location.type}
5446@findex %define api.location.type
5447
5448@itemize @bullet
5449@item Language(s): C++, Java
5450
5451@item Purpose: Define the location type.
5452@xref{User Defined Location Type}.
5453
5454@item Accepted Values: String
5455
5456@item Default Value: none
5457
5458@item History: introduced in Bison 2.7
5459@end itemize
5460
5461@c ================================================== api.prefix
5462@item @code{api.prefix}
5463@findex %define api.prefix
5464
5465@itemize @bullet
5466@item Language(s): All
5467
5468@item Purpose: Rename exported symbols.
5469@xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
5470
5471@item Accepted Values: String
5472
5473@item Default Value: @code{yy}
5474
5475@item History: introduced in Bison 2.6
5476@end itemize
5477
5478@c ================================================== api.pure
5479@item @code{api.pure}
5480@findex %define api.pure
5481
5482@itemize @bullet
5483@item Language(s): C
5484
5485@item Purpose: Request a pure (reentrant) parser program.
5486@xref{Pure Decl, ,A Pure (Reentrant) Parser}.
5487
5488@item Accepted Values: @code{true}, @code{false}, @code{full}
5489
5490The value may be omitted: this is equivalent to specifying @code{true}, as is
5491the case for Boolean values.
5492
5493When @code{%define api.pure full} is used, the parser is made reentrant. This
5494changes the signature for @code{yylex} (@pxref{Pure Calling}), and also that of
5495@code{yyerror} when the tracking of locations has been activated, as shown
5496below.
5497
5498The @code{true} value is very similar to the @code{full} value, the only
5499difference is in the signature of @code{yyerror} on Yacc parsers without
5500@code{%parse-param}, for historical reasons.
5501
5502I.e., if @samp{%locations %define api.pure} is passed then the prototypes for
5503@code{yyerror} are:
5504
5505@example
5506void yyerror (char const *msg);                 // Yacc parsers.
5507void yyerror (YYLTYPE *locp, char const *msg);  // GLR parsers.
5508@end example
5509
5510But if @samp{%locations %define api.pure %parse-param @{int *nastiness@}} is
5511used, then both parsers have the same signature:
5512
5513@example
5514void yyerror (YYLTYPE *llocp, int *nastiness, char const *msg);
5515@end example
5516
5517(@pxref{Error Reporting, ,The Error
5518Reporting Function @code{yyerror}})
5519
5520@item Default Value: @code{false}
5521
5522@item History: the @code{full} value was introduced in Bison 2.7
5523@end itemize
5524
5525@c ================================================== api.push-pull
5526
5527@item @code{api.push-pull}
5528@findex %define api.push-pull
5529
5530@itemize @bullet
5531@item Language(s): C (deterministic parsers only)
5532
5533@item Purpose: Request a pull parser, a push parser, or both.
5534@xref{Push Decl, ,A Push Parser}.
5535(The current push parsing interface is experimental and may evolve.
5536More user feedback will help to stabilize it.)
5537
5538@item Accepted Values: @code{pull}, @code{push}, @code{both}
5539
5540@item Default Value: @code{pull}
5541@end itemize
5542
5543@c ================================================== lr.default-reductions
5544
5545@item @code{lr.default-reductions}
5546@findex %define lr.default-reductions
5547
5548@itemize @bullet
5549@item Language(s): all
5550
5551@item Purpose: Specify the kind of states that are permitted to
5552contain default reductions.  @xref{Default Reductions}.  (The ability to
5553specify where default reductions should be used is experimental.  More user
5554feedback will help to stabilize it.)
5555
5556@item Accepted Values: @code{most}, @code{consistent}, @code{accepting}
5557@item Default Value:
5558@itemize
5559@item @code{accepting} if @code{lr.type} is @code{canonical-lr}.
5560@item @code{most} otherwise.
5561@end itemize
5562@end itemize
5563
5564@c ============================================ lr.keep-unreachable-states
5565
5566@item @code{lr.keep-unreachable-states}
5567@findex %define lr.keep-unreachable-states
5568
5569@itemize @bullet
5570@item Language(s): all
5571@item Purpose: Request that Bison allow unreachable parser states to
5572remain in the parser tables.  @xref{Unreachable States}.
5573@item Accepted Values: Boolean
5574@item Default Value: @code{false}
5575@end itemize
5576
5577@c ================================================== lr.type
5578
5579@item @code{lr.type}
5580@findex %define lr.type
5581
5582@itemize @bullet
5583@item Language(s): all
5584
5585@item Purpose: Specify the type of parser tables within the
5586LR(1) family.  @xref{LR Table Construction}.  (This feature is experimental.
5587More user feedback will help to stabilize it.)
5588
5589@item Accepted Values: @code{lalr}, @code{ielr}, @code{canonical-lr}
5590
5591@item Default Value: @code{lalr}
5592@end itemize
5593
5594@c ================================================== namespace
5595
5596@item @code{namespace}
5597@findex %define namespace
5598
5599@itemize
5600@item Languages(s): C++
5601
5602@item Purpose: Specify the namespace for the parser class.
5603For example, if you specify:
5604
5605@smallexample
5606%define namespace "foo::bar"
5607@end smallexample
5608
5609Bison uses @code{foo::bar} verbatim in references such as:
5610
5611@smallexample
5612foo::bar::parser::semantic_type
5613@end smallexample
5614
5615However, to open a namespace, Bison removes any leading @code{::} and then
5616splits on any remaining occurrences:
5617
5618@smallexample
5619namespace foo @{ namespace bar @{
5620  class position;
5621  class location;
5622@} @}
5623@end smallexample
5624
5625@item Accepted Values: Any absolute or relative C++ namespace reference without
5626a trailing @code{"::"}.
5627For example, @code{"foo"} or @code{"::foo::bar"}.
5628
5629@item Default Value: The value specified by @code{%name-prefix}, which defaults
5630to @code{yy}.
5631This usage of @code{%name-prefix} is for backward compatibility and can be
5632confusing since @code{%name-prefix} also specifies the textual prefix for the
5633lexical analyzer function.
5634Thus, if you specify @code{%name-prefix}, it is best to also specify
5635@code{%define namespace} so that @code{%name-prefix} @emph{only} affects the
5636lexical analyzer function.
5637For example, if you specify:
5638
5639@smallexample
5640%define namespace "foo"
5641%name-prefix "bar::"
5642@end smallexample
5643
5644The parser namespace is @code{foo} and @code{yylex} is referenced as
5645@code{bar::lex}.
5646@end itemize
5647
5648@c ================================================== parse.lac
5649@item @code{parse.lac}
5650@findex %define parse.lac
5651
5652@itemize
5653@item Languages(s): C (deterministic parsers only)
5654
5655@item Purpose: Enable LAC (lookahead correction) to improve
5656syntax error handling.  @xref{LAC}.
5657@item Accepted Values: @code{none}, @code{full}
5658@item Default Value: @code{none}
5659@end itemize
5660@end itemize
5661
5662
5663@node %code Summary
5664@subsection %code Summary
5665@findex %code
5666@cindex Prologue
5667
5668The @code{%code} directive inserts code verbatim into the output
5669parser source at any of a predefined set of locations.  It thus serves
5670as a flexible and user-friendly alternative to the traditional Yacc
5671prologue, @code{%@{@var{code}%@}}.  This section summarizes the
5672functionality of @code{%code} for the various target languages
5673supported by Bison.  For a detailed discussion of how to use
5674@code{%code} in place of @code{%@{@var{code}%@}} for C/C++ and why it
5675is advantageous to do so, @pxref{Prologue Alternatives}.
5676
5677@deffn {Directive} %code @{@var{code}@}
5678This is the unqualified form of the @code{%code} directive.  It
5679inserts @var{code} verbatim at a language-dependent default location
5680in the parser implementation.
5681
5682For C/C++, the default location is the parser implementation file
5683after the usual contents of the parser header file.  Thus, the
5684unqualified form replaces @code{%@{@var{code}%@}} for most purposes.
5685
5686For Java, the default location is inside the parser class.
5687@end deffn
5688
5689@deffn {Directive} %code @var{qualifier} @{@var{code}@}
5690This is the qualified form of the @code{%code} directive.
5691@var{qualifier} identifies the purpose of @var{code} and thus the
5692location(s) where Bison should insert it.  That is, if you need to
5693specify location-sensitive @var{code} that does not belong at the
5694default location selected by the unqualified @code{%code} form, use
5695this form instead.
5696@end deffn
5697
5698For any particular qualifier or for the unqualified form, if there are
5699multiple occurrences of the @code{%code} directive, Bison concatenates
5700the specified code in the order in which it appears in the grammar
5701file.
5702
5703Not all qualifiers are accepted for all target languages.  Unaccepted
5704qualifiers produce an error.  Some of the accepted qualifiers are:
5705
5706@itemize @bullet
5707@item requires
5708@findex %code requires
5709
5710@itemize @bullet
5711@item Language(s): C, C++
5712
5713@item Purpose: This is the best place to write dependency code required for
5714@code{YYSTYPE} and @code{YYLTYPE}.
5715In other words, it's the best place to define types referenced in @code{%union}
5716directives, and it's the best place to override Bison's default @code{YYSTYPE}
5717and @code{YYLTYPE} definitions.
5718
5719@item Location(s): The parser header file and the parser implementation file
5720before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
5721definitions.
5722@end itemize
5723
5724@item provides
5725@findex %code provides
5726
5727@itemize @bullet
5728@item Language(s): C, C++
5729
5730@item Purpose: This is the best place to write additional definitions and
5731declarations that should be provided to other modules.
5732
5733@item Location(s): The parser header file and the parser implementation
5734file after the Bison-generated @code{YYSTYPE}, @code{YYLTYPE}, and
5735token definitions.
5736@end itemize
5737
5738@item top
5739@findex %code top
5740
5741@itemize @bullet
5742@item Language(s): C, C++
5743
5744@item Purpose: The unqualified @code{%code} or @code{%code requires}
5745should usually be more appropriate than @code{%code top}.  However,
5746occasionally it is necessary to insert code much nearer the top of the
5747parser implementation file.  For example:
5748
5749@example
5750%code top @{
5751  #define _GNU_SOURCE
5752  #include <stdio.h>
5753@}
5754@end example
5755
5756@item Location(s): Near the top of the parser implementation file.
5757@end itemize
5758
5759@item imports
5760@findex %code imports
5761
5762@itemize @bullet
5763@item Language(s): Java
5764
5765@item Purpose: This is the best place to write Java import directives.
5766
5767@item Location(s): The parser Java file after any Java package directive and
5768before any class definitions.
5769@end itemize
5770@end itemize
5771
5772Though we say the insertion locations are language-dependent, they are
5773technically skeleton-dependent.  Writers of non-standard skeletons
5774however should choose their locations consistently with the behavior
5775of the standard Bison skeletons.
5776
5777
5778@node Multiple Parsers
5779@section Multiple Parsers in the Same Program
5780
5781Most programs that use Bison parse only one language and therefore contain
5782only one Bison parser.  But what if you want to parse more than one language
5783with the same program?  Then you need to avoid name conflicts between
5784different definitions of functions and variables such as @code{yyparse},
5785@code{yylval}.  To use different parsers from the same compilation unit, you
5786also need to avoid conflicts on types and macros (e.g., @code{YYSTYPE})
5787exported in the generated header.
5788
5789The easy way to do this is to define the @code{%define} variable
5790@code{api.prefix}.  With different @code{api.prefix}s it is guaranteed that
5791headers do not conflict when included together, and that compiled objects
5792can be linked together too.  Specifying @samp{%define api.prefix
5793@var{prefix}} (or passing the option @samp{-Dapi.prefix=@var{prefix}}, see
5794@ref{Invocation, ,Invoking Bison}) renames the interface functions and
5795variables of the Bison parser to start with @var{prefix} instead of
5796@samp{yy}, and all the macros to start by @var{PREFIX} (i.e., @var{prefix}
5797upper-cased) instead of @samp{YY}.
5798
5799The renamed symbols include @code{yyparse}, @code{yylex}, @code{yyerror},
5800@code{yynerrs}, @code{yylval}, @code{yylloc}, @code{yychar} and
5801@code{yydebug}.  If you use a push parser, @code{yypush_parse},
5802@code{yypull_parse}, @code{yypstate}, @code{yypstate_new} and
5803@code{yypstate_delete} will also be renamed.  The renamed macros include
5804@code{YYSTYPE}, @code{YYLTYPE}, and @code{YYDEBUG}, which is treated
5805specifically --- more about this below.
5806
5807For example, if you use @samp{%define api.prefix c}, the names become
5808@code{cparse}, @code{clex}, @dots{}, @code{CSTYPE}, @code{CLTYPE}, and so
5809on.
5810
5811The @code{%define} variable @code{api.prefix} works in two different ways.
5812In the implementation file, it works by adding macro definitions to the
5813beginning of the parser implementation file, defining @code{yyparse} as
5814@code{@var{prefix}parse}, and so on:
5815
5816@example
5817#define YYSTYPE CTYPE
5818#define yyparse cparse
5819#define yylval  clval
5820...
5821YYSTYPE yylval;
5822int yyparse (void);
5823@end example
5824
5825This effectively substitutes one name for the other in the entire parser
5826implementation file, thus the ``original'' names (@code{yylex},
5827@code{YYSTYPE}, @dots{}) are also usable in the parser implementation file.
5828
5829However, in the parser header file, the symbols are defined renamed, for
5830instance:
5831
5832@example
5833extern CSTYPE clval;
5834int cparse (void);
5835@end example
5836
5837The macro @code{YYDEBUG} is commonly used to enable the tracing support in
5838parsers.  To comply with this tradition, when @code{api.prefix} is used,
5839@code{YYDEBUG} (not renamed) is used as a default value:
5840
5841@example
5842/* Enabling traces.  */
5843#ifndef CDEBUG
5844# if defined YYDEBUG
5845#  if YYDEBUG
5846#   define CDEBUG 1
5847#  else
5848#   define CDEBUG 0
5849#  endif
5850# else
5851#  define CDEBUG 0
5852# endif
5853#endif
5854#if CDEBUG
5855extern int cdebug;
5856#endif
5857@end example
5858
5859@sp 2
5860
5861Prior to Bison 2.6, a feature similar to @code{api.prefix} was provided by
5862the obsolete directive @code{%name-prefix} (@pxref{Table of Symbols, ,Bison
5863Symbols}) and the option @code{--name-prefix} (@pxref{Bison Options}).
5864
5865@node Interface
5866@chapter Parser C-Language Interface
5867@cindex C-language interface
5868@cindex interface
5869
5870The Bison parser is actually a C function named @code{yyparse}.  Here we
5871describe the interface conventions of @code{yyparse} and the other
5872functions that it needs to use.
5873
5874Keep in mind that the parser uses many C identifiers starting with
5875@samp{yy} and @samp{YY} for internal purposes.  If you use such an
5876identifier (aside from those in this manual) in an action or in epilogue
5877in the grammar file, you are likely to run into trouble.
5878
5879@menu
5880* Parser Function::         How to call @code{yyparse} and what it returns.
5881* Push Parser Function::    How to call @code{yypush_parse} and what it returns.
5882* Pull Parser Function::    How to call @code{yypull_parse} and what it returns.
5883* Parser Create Function::  How to call @code{yypstate_new} and what it returns.
5884* Parser Delete Function::  How to call @code{yypstate_delete} and what it returns.
5885* Lexical::                 You must supply a function @code{yylex}
5886                              which reads tokens.
5887* Error Reporting::         You must supply a function @code{yyerror}.
5888* Action Features::         Special features for use in actions.
5889* Internationalization::    How to let the parser speak in the user's
5890                              native language.
5891@end menu
5892
5893@node Parser Function
5894@section The Parser Function @code{yyparse}
5895@findex yyparse
5896
5897You call the function @code{yyparse} to cause parsing to occur.  This
5898function reads tokens, executes actions, and ultimately returns when it
5899encounters end-of-input or an unrecoverable syntax error.  You can also
5900write an action which directs @code{yyparse} to return immediately
5901without reading further.
5902
5903
5904@deftypefun int yyparse (void)
5905The value returned by @code{yyparse} is 0 if parsing was successful (return
5906is due to end-of-input).
5907
5908The value is 1 if parsing failed because of invalid input, i.e., input
5909that contains a syntax error or that causes @code{YYABORT} to be
5910invoked.
5911
5912The value is 2 if parsing failed due to memory exhaustion.
5913@end deftypefun
5914
5915In an action, you can cause immediate return from @code{yyparse} by using
5916these macros:
5917
5918@defmac YYACCEPT
5919@findex YYACCEPT
5920Return immediately with value 0 (to report success).
5921@end defmac
5922
5923@defmac YYABORT
5924@findex YYABORT
5925Return immediately with value 1 (to report failure).
5926@end defmac
5927
5928If you use a reentrant parser, you can optionally pass additional
5929parameter information to it in a reentrant way.  To do so, use the
5930declaration @code{%parse-param}:
5931
5932@deffn {Directive} %parse-param @{@var{argument-declaration}@}
5933@findex %parse-param
5934Declare that an argument declared by the braced-code
5935@var{argument-declaration} is an additional @code{yyparse} argument.
5936The @var{argument-declaration} is used when declaring
5937functions or prototypes.  The last identifier in
5938@var{argument-declaration} must be the argument name.
5939@end deffn
5940
5941Here's an example.  Write this in the parser:
5942
5943@example
5944%parse-param @{int *nastiness@}
5945%parse-param @{int *randomness@}
5946@end example
5947
5948@noindent
5949Then call the parser like this:
5950
5951@example
5952@{
5953  int nastiness, randomness;
5954  @dots{}  /* @r{Store proper data in @code{nastiness} and @code{randomness}.}  */
5955  value = yyparse (&nastiness, &randomness);
5956  @dots{}
5957@}
5958@end example
5959
5960@noindent
5961In the grammar actions, use expressions like this to refer to the data:
5962
5963@example
5964exp: @dots{}    @{ @dots{}; *randomness += 1; @dots{} @}
5965@end example
5966
5967@noindent
5968Using the following:
5969@example
5970%parse-param @{int *randomness@}
5971@end example
5972
5973Results in these signatures:
5974@example
5975void yyerror (int *randomness, const char *msg);
5976int  yyparse (int *randomness);
5977@end example
5978
5979@noindent
5980Or, if both @code{%define api.pure full} (or just @code{%define api.pure})
5981and @code{%locations} are used:
5982
5983@example
5984void yyerror (YYLTYPE *llocp, int *randomness, const char *msg);
5985int  yyparse (int *randomness);
5986@end example
5987
5988@node Push Parser Function
5989@section The Push Parser Function @code{yypush_parse}
5990@findex yypush_parse
5991
5992(The current push parsing interface is experimental and may evolve.
5993More user feedback will help to stabilize it.)
5994
5995You call the function @code{yypush_parse} to parse a single token.  This
5996function is available if either the @code{%define api.push-pull push} or
5997@code{%define api.push-pull both} declaration is used.
5998@xref{Push Decl, ,A Push Parser}.
5999
6000@deftypefun int yypush_parse (yypstate *yyps)
6001The value returned by @code{yypush_parse} is the same as for yyparse with
6002the following exception: it returns @code{YYPUSH_MORE} if more input is
6003required to finish parsing the grammar.
6004@end deftypefun
6005
6006@node Pull Parser Function
6007@section The Pull Parser Function @code{yypull_parse}
6008@findex yypull_parse
6009
6010(The current push parsing interface is experimental and may evolve.
6011More user feedback will help to stabilize it.)
6012
6013You call the function @code{yypull_parse} to parse the rest of the input
6014stream.  This function is available if the @code{%define api.push-pull both}
6015declaration is used.
6016@xref{Push Decl, ,A Push Parser}.
6017
6018@deftypefun int yypull_parse (yypstate *yyps)
6019The value returned by @code{yypull_parse} is the same as for @code{yyparse}.
6020@end deftypefun
6021
6022@node Parser Create Function
6023@section The Parser Create Function @code{yystate_new}
6024@findex yypstate_new
6025
6026(The current push parsing interface is experimental and may evolve.
6027More user feedback will help to stabilize it.)
6028
6029You call the function @code{yypstate_new} to create a new parser instance.
6030This function is available if either the @code{%define api.push-pull push} or
6031@code{%define api.push-pull both} declaration is used.
6032@xref{Push Decl, ,A Push Parser}.
6033
6034@deftypefun {yypstate*} yypstate_new (void)
6035The function will return a valid parser instance if there was memory available
6036or 0 if no memory was available.
6037In impure mode, it will also return 0 if a parser instance is currently
6038allocated.
6039@end deftypefun
6040
6041@node Parser Delete Function
6042@section The Parser Delete Function @code{yystate_delete}
6043@findex yypstate_delete
6044
6045(The current push parsing interface is experimental and may evolve.
6046More user feedback will help to stabilize it.)
6047
6048You call the function @code{yypstate_delete} to delete a parser instance.
6049function is available if either the @code{%define api.push-pull push} or
6050@code{%define api.push-pull both} declaration is used.
6051@xref{Push Decl, ,A Push Parser}.
6052
6053@deftypefun void yypstate_delete (yypstate *yyps)
6054This function will reclaim the memory associated with a parser instance.
6055After this call, you should no longer attempt to use the parser instance.
6056@end deftypefun
6057
6058@node Lexical
6059@section The Lexical Analyzer Function @code{yylex}
6060@findex yylex
6061@cindex lexical analyzer
6062
6063The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
6064the input stream and returns them to the parser.  Bison does not create
6065this function automatically; you must write it so that @code{yyparse} can
6066call it.  The function is sometimes referred to as a lexical scanner.
6067
6068In simple programs, @code{yylex} is often defined at the end of the
6069Bison grammar file.  If @code{yylex} is defined in a separate source
6070file, you need to arrange for the token-type macro definitions to be
6071available there.  To do this, use the @samp{-d} option when you run
6072Bison, so that it will write these macro definitions into the separate
6073parser header file, @file{@var{name}.tab.h}, which you can include in
6074the other source files that need it.  @xref{Invocation, ,Invoking
6075Bison}.
6076
6077@menu
6078* Calling Convention::  How @code{yyparse} calls @code{yylex}.
6079* Token Values::        How @code{yylex} must return the semantic value
6080                          of the token it has read.
6081* Token Locations::     How @code{yylex} must return the text location
6082                          (line number, etc.) of the token, if the
6083                          actions want that.
6084* Pure Calling::        How the calling convention differs in a pure parser
6085                          (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
6086@end menu
6087
6088@node Calling Convention
6089@subsection Calling Convention for @code{yylex}
6090
6091The value that @code{yylex} returns must be the positive numeric code
6092for the type of token it has just found; a zero or negative value
6093signifies end-of-input.
6094
6095When a token is referred to in the grammar rules by a name, that name
6096in the parser implementation file becomes a C macro whose definition
6097is the proper numeric code for that token type.  So @code{yylex} can
6098use the name to indicate that type.  @xref{Symbols}.
6099
6100When a token is referred to in the grammar rules by a character literal,
6101the numeric code for that character is also the code for the token type.
6102So @code{yylex} can simply return that character code, possibly converted
6103to @code{unsigned char} to avoid sign-extension.  The null character
6104must not be used this way, because its code is zero and that
6105signifies end-of-input.
6106
6107Here is an example showing these things:
6108
6109@example
6110int
6111yylex (void)
6112@{
6113  @dots{}
6114  if (c == EOF)    /* Detect end-of-input.  */
6115    return 0;
6116  @dots{}
6117  if (c == '+' || c == '-')
6118    return c;      /* Assume token type for `+' is '+'.  */
6119  @dots{}
6120  return INT;      /* Return the type of the token.  */
6121  @dots{}
6122@}
6123@end example
6124
6125@noindent
6126This interface has been designed so that the output from the @code{lex}
6127utility can be used without change as the definition of @code{yylex}.
6128
6129If the grammar uses literal string tokens, there are two ways that
6130@code{yylex} can determine the token type codes for them:
6131
6132@itemize @bullet
6133@item
6134If the grammar defines symbolic token names as aliases for the
6135literal string tokens, @code{yylex} can use these symbolic names like
6136all others.  In this case, the use of the literal string tokens in
6137the grammar file has no effect on @code{yylex}.
6138
6139@item
6140@code{yylex} can find the multicharacter token in the @code{yytname}
6141table.  The index of the token in the table is the token type's code.
6142The name of a multicharacter token is recorded in @code{yytname} with a
6143double-quote, the token's characters, and another double-quote.  The
6144token's characters are escaped as necessary to be suitable as input
6145to Bison.
6146
6147Here's code for looking up a multicharacter token in @code{yytname},
6148assuming that the characters of the token are stored in
6149@code{token_buffer}, and assuming that the token does not contain any
6150characters like @samp{"} that require escaping.
6151
6152@example
6153for (i = 0; i < YYNTOKENS; i++)
6154  @{
6155    if (yytname[i] != 0
6156        && yytname[i][0] == '"'
6157        && ! strncmp (yytname[i] + 1, token_buffer,
6158                      strlen (token_buffer))
6159        && yytname[i][strlen (token_buffer) + 1] == '"'
6160        && yytname[i][strlen (token_buffer) + 2] == 0)
6161      break;
6162  @}
6163@end example
6164
6165The @code{yytname} table is generated only if you use the
6166@code{%token-table} declaration.  @xref{Decl Summary}.
6167@end itemize
6168
6169@node Token Values
6170@subsection Semantic Values of Tokens
6171
6172@vindex yylval
6173In an ordinary (nonreentrant) parser, the semantic value of the token must
6174be stored into the global variable @code{yylval}.  When you are using
6175just one data type for semantic values, @code{yylval} has that type.
6176Thus, if the type is @code{int} (the default), you might write this in
6177@code{yylex}:
6178
6179@example
6180@group
6181  @dots{}
6182  yylval = value;  /* Put value onto Bison stack.  */
6183  return INT;      /* Return the type of the token.  */
6184  @dots{}
6185@end group
6186@end example
6187
6188When you are using multiple data types, @code{yylval}'s type is a union
6189made from the @code{%union} declaration (@pxref{Union Decl, ,The
6190Collection of Value Types}).  So when you store a token's value, you
6191must use the proper member of the union.  If the @code{%union}
6192declaration looks like this:
6193
6194@example
6195@group
6196%union @{
6197  int intval;
6198  double val;
6199  symrec *tptr;
6200@}
6201@end group
6202@end example
6203
6204@noindent
6205then the code in @code{yylex} might look like this:
6206
6207@example
6208@group
6209  @dots{}
6210  yylval.intval = value; /* Put value onto Bison stack.  */
6211  return INT;            /* Return the type of the token.  */
6212  @dots{}
6213@end group
6214@end example
6215
6216@node Token Locations
6217@subsection Textual Locations of Tokens
6218
6219@vindex yylloc
6220If you are using the @samp{@@@var{n}}-feature (@pxref{Tracking Locations})
6221in actions to keep track of the textual locations of tokens and groupings,
6222then you must provide this information in @code{yylex}.  The function
6223@code{yyparse} expects to find the textual location of a token just parsed
6224in the global variable @code{yylloc}.  So @code{yylex} must store the proper
6225data in that variable.
6226
6227By default, the value of @code{yylloc} is a structure and you need only
6228initialize the members that are going to be used by the actions.  The
6229four members are called @code{first_line}, @code{first_column},
6230@code{last_line} and @code{last_column}.  Note that the use of this
6231feature makes the parser noticeably slower.
6232
6233@tindex YYLTYPE
6234The data type of @code{yylloc} has the name @code{YYLTYPE}.
6235
6236@node Pure Calling
6237@subsection Calling Conventions for Pure Parsers
6238
6239When you use the Bison declaration @code{%define api.pure full} to request a
6240pure, reentrant parser, the global communication variables @code{yylval}
6241and @code{yylloc} cannot be used.  (@xref{Pure Decl, ,A Pure (Reentrant)
6242Parser}.)  In such parsers the two global variables are replaced by
6243pointers passed as arguments to @code{yylex}.  You must declare them as
6244shown here, and pass the information back by storing it through those
6245pointers.
6246
6247@example
6248int
6249yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
6250@{
6251  @dots{}
6252  *lvalp = value;  /* Put value onto Bison stack.  */
6253  return INT;      /* Return the type of the token.  */
6254  @dots{}
6255@}
6256@end example
6257
6258If the grammar file does not use the @samp{@@} constructs to refer to
6259textual locations, then the type @code{YYLTYPE} will not be defined.  In
6260this case, omit the second argument; @code{yylex} will be called with
6261only one argument.
6262
6263
6264If you wish to pass the additional parameter data to @code{yylex}, use
6265@code{%lex-param} just like @code{%parse-param} (@pxref{Parser
6266Function}).
6267
6268@deffn {Directive} lex-param @{@var{argument-declaration}@}
6269@findex %lex-param
6270Declare that the braced-code @var{argument-declaration} is an
6271additional @code{yylex} argument declaration.
6272@end deffn
6273
6274@noindent
6275For instance:
6276
6277@example
6278%lex-param   @{int *nastiness@}
6279@end example
6280
6281@noindent
6282results in the following signature:
6283
6284@example
6285int yylex (int *nastiness);
6286@end example
6287
6288@noindent
6289If @code{%define api.pure full} (or just @code{%define api.pure}) is added:
6290
6291@example
6292int yylex (YYSTYPE *lvalp, int *nastiness);
6293@end example
6294
6295@node Error Reporting
6296@section The Error Reporting Function @code{yyerror}
6297@cindex error reporting function
6298@findex yyerror
6299@cindex parse error
6300@cindex syntax error
6301
6302The Bison parser detects a @dfn{syntax error} or @dfn{parse error}
6303whenever it reads a token which cannot satisfy any syntax rule.  An
6304action in the grammar can also explicitly proclaim an error, using the
6305macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
6306in Actions}).
6307
6308The Bison parser expects to report the error by calling an error
6309reporting function named @code{yyerror}, which you must supply.  It is
6310called by @code{yyparse} whenever a syntax error is found, and it
6311receives one argument.  For a syntax error, the string is normally
6312@w{@code{"syntax error"}}.
6313
6314@findex %error-verbose
6315If you invoke the directive @code{%error-verbose} in the Bison declarations
6316section (@pxref{Bison Declarations, ,The Bison Declarations Section}), then
6317Bison provides a more verbose and specific error message string instead of
6318just plain @w{@code{"syntax error"}}.  However, that message sometimes
6319contains incorrect information if LAC is not enabled (@pxref{LAC}).
6320
6321The parser can detect one other kind of error: memory exhaustion.  This
6322can happen when the input contains constructions that are very deeply
6323nested.  It isn't likely you will encounter this, since the Bison
6324parser normally extends its stack automatically up to a very large limit.  But
6325if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
6326fashion, except that the argument string is @w{@code{"memory exhausted"}}.
6327
6328In some cases diagnostics like @w{@code{"syntax error"}} are
6329translated automatically from English to some other language before
6330they are passed to @code{yyerror}.  @xref{Internationalization}.
6331
6332The following definition suffices in simple programs:
6333
6334@example
6335@group
6336void
6337yyerror (char const *s)
6338@{
6339@end group
6340@group
6341  fprintf (stderr, "%s\n", s);
6342@}
6343@end group
6344@end example
6345
6346After @code{yyerror} returns to @code{yyparse}, the latter will attempt
6347error recovery if you have written suitable error recovery grammar rules
6348(@pxref{Error Recovery}).  If recovery is impossible, @code{yyparse} will
6349immediately return 1.
6350
6351Obviously, in location tracking pure parsers, @code{yyerror} should have
6352an access to the current location. With @code{%define api.pure}, this is
6353indeed the case for the GLR parsers, but not for the Yacc parser, for
6354historical reasons, and this is the why @code{%define api.pure full} should be
6355prefered over @code{%define api.pure}.
6356
6357When @code{%locations %define api.pure full} is used, @code{yyerror} has the
6358following signature:
6359
6360@example
6361void yyerror (YYLTYPE *locp, char const *msg);
6362@end example
6363
6364@noindent
6365The prototypes are only indications of how the code produced by Bison
6366uses @code{yyerror}.  Bison-generated code always ignores the returned
6367value, so @code{yyerror} can return any type, including @code{void}.
6368Also, @code{yyerror} can be a variadic function; that is why the
6369message is always passed last.
6370
6371Traditionally @code{yyerror} returns an @code{int} that is always
6372ignored, but this is purely for historical reasons, and @code{void} is
6373preferable since it more accurately describes the return type for
6374@code{yyerror}.
6375
6376@vindex yynerrs
6377The variable @code{yynerrs} contains the number of syntax errors
6378reported so far.  Normally this variable is global; but if you
6379request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
6380then it is a local variable which only the actions can access.
6381
6382@node Action Features
6383@section Special Features for Use in Actions
6384@cindex summary, action features
6385@cindex action features summary
6386
6387Here is a table of Bison constructs, variables and macros that
6388are useful in actions.
6389
6390@deffn {Variable} $$
6391Acts like a variable that contains the semantic value for the
6392grouping made by the current rule.  @xref{Actions}.
6393@end deffn
6394
6395@deffn {Variable} $@var{n}
6396Acts like a variable that contains the semantic value for the
6397@var{n}th component of the current rule.  @xref{Actions}.
6398@end deffn
6399
6400@deffn {Variable} $<@var{typealt}>$
6401Like @code{$$} but specifies alternative @var{typealt} in the union
6402specified by the @code{%union} declaration.  @xref{Action Types, ,Data
6403Types of Values in Actions}.
6404@end deffn
6405
6406@deffn {Variable} $<@var{typealt}>@var{n}
6407Like @code{$@var{n}} but specifies alternative @var{typealt} in the
6408union specified by the @code{%union} declaration.
6409@xref{Action Types, ,Data Types of Values in Actions}.
6410@end deffn
6411
6412@deffn {Macro} YYABORT @code{;}
6413Return immediately from @code{yyparse}, indicating failure.
6414@xref{Parser Function, ,The Parser Function @code{yyparse}}.
6415@end deffn
6416
6417@deffn {Macro} YYACCEPT @code{;}
6418Return immediately from @code{yyparse}, indicating success.
6419@xref{Parser Function, ,The Parser Function @code{yyparse}}.
6420@end deffn
6421
6422@deffn {Macro} YYBACKUP (@var{token}, @var{value})@code{;}
6423@findex YYBACKUP
6424Unshift a token.  This macro is allowed only for rules that reduce
6425a single value, and only when there is no lookahead token.
6426It is also disallowed in GLR parsers.
6427It installs a lookahead token with token type @var{token} and
6428semantic value @var{value}; then it discards the value that was
6429going to be reduced by this rule.
6430
6431If the macro is used when it is not valid, such as when there is
6432a lookahead token already, then it reports a syntax error with
6433a message @samp{cannot back up} and performs ordinary error
6434recovery.
6435
6436In either case, the rest of the action is not executed.
6437@end deffn
6438
6439@deffn {Macro} YYEMPTY
6440Value stored in @code{yychar} when there is no lookahead token.
6441@end deffn
6442
6443@deffn {Macro} YYEOF
6444Value stored in @code{yychar} when the lookahead is the end of the input
6445stream.
6446@end deffn
6447
6448@deffn {Macro} YYERROR @code{;}
6449Cause an immediate syntax error.  This statement initiates error
6450recovery just as if the parser itself had detected an error; however, it
6451does not call @code{yyerror}, and does not print any message.  If you
6452want to print an error message, call @code{yyerror} explicitly before
6453the @samp{YYERROR;} statement.  @xref{Error Recovery}.
6454@end deffn
6455
6456@deffn {Macro} YYRECOVERING
6457@findex YYRECOVERING
6458The expression @code{YYRECOVERING ()} yields 1 when the parser
6459is recovering from a syntax error, and 0 otherwise.
6460@xref{Error Recovery}.
6461@end deffn
6462
6463@deffn {Variable} yychar
6464Variable containing either the lookahead token, or @code{YYEOF} when the
6465lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
6466has been performed so the next token is not yet known.
6467Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
6468Actions}).
6469@xref{Lookahead, ,Lookahead Tokens}.
6470@end deffn
6471
6472@deffn {Macro} yyclearin @code{;}
6473Discard the current lookahead token.  This is useful primarily in
6474error rules.
6475Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
6476Semantic Actions}).
6477@xref{Error Recovery}.
6478@end deffn
6479
6480@deffn {Macro} yyerrok @code{;}
6481Resume generating error messages immediately for subsequent syntax
6482errors.  This is useful primarily in error rules.
6483@xref{Error Recovery}.
6484@end deffn
6485
6486@deffn {Variable} yylloc
6487Variable containing the lookahead token location when @code{yychar} is not set
6488to @code{YYEMPTY} or @code{YYEOF}.
6489Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
6490Actions}).
6491@xref{Actions and Locations, ,Actions and Locations}.
6492@end deffn
6493
6494@deffn {Variable} yylval
6495Variable containing the lookahead token semantic value when @code{yychar} is
6496not set to @code{YYEMPTY} or @code{YYEOF}.
6497Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
6498Actions}).
6499@xref{Actions, ,Actions}.
6500@end deffn
6501
6502@deffn {Value} @@$
6503Acts like a structure variable containing information on the textual
6504location of the grouping made by the current rule.  @xref{Tracking
6505Locations}.
6506
6507@c Check if those paragraphs are still useful or not.
6508
6509@c @example
6510@c struct @{
6511@c   int first_line, last_line;
6512@c   int first_column, last_column;
6513@c @};
6514@c @end example
6515
6516@c Thus, to get the starting line number of the third component, you would
6517@c use @samp{@@3.first_line}.
6518
6519@c In order for the members of this structure to contain valid information,
6520@c you must make @code{yylex} supply this information about each token.
6521@c If you need only certain members, then @code{yylex} need only fill in
6522@c those members.
6523
6524@c The use of this feature makes the parser noticeably slower.
6525@end deffn
6526
6527@deffn {Value} @@@var{n}
6528@findex @@@var{n}
6529Acts like a structure variable containing information on the textual
6530location of the @var{n}th component of the current rule.  @xref{Tracking
6531Locations}.
6532@end deffn
6533
6534@node Internationalization
6535@section Parser Internationalization
6536@cindex internationalization
6537@cindex i18n
6538@cindex NLS
6539@cindex gettext
6540@cindex bison-po
6541
6542A Bison-generated parser can print diagnostics, including error and
6543tracing messages.  By default, they appear in English.  However, Bison
6544also supports outputting diagnostics in the user's native language.  To
6545make this work, the user should set the usual environment variables.
6546@xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
6547For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
6548set the user's locale to French Canadian using the UTF-8
6549encoding.  The exact set of available locales depends on the user's
6550installation.
6551
6552The maintainer of a package that uses a Bison-generated parser enables
6553the internationalization of the parser's output through the following
6554steps.  Here we assume a package that uses GNU Autoconf and
6555GNU Automake.
6556
6557@enumerate
6558@item
6559@cindex bison-i18n.m4
6560Into the directory containing the GNU Autoconf macros used
6561by the package ---often called @file{m4}--- copy the
6562@file{bison-i18n.m4} file installed by Bison under
6563@samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
6564For example:
6565
6566@example
6567cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
6568@end example
6569
6570@item
6571@findex BISON_I18N
6572@vindex BISON_LOCALEDIR
6573@vindex YYENABLE_NLS
6574In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
6575invocation, add an invocation of @code{BISON_I18N}.  This macro is
6576defined in the file @file{bison-i18n.m4} that you copied earlier.  It
6577causes @samp{configure} to find the value of the
6578@code{BISON_LOCALEDIR} variable, and it defines the source-language
6579symbol @code{YYENABLE_NLS} to enable translations in the
6580Bison-generated parser.
6581
6582@item
6583In the @code{main} function of your program, designate the directory
6584containing Bison's runtime message catalog, through a call to
6585@samp{bindtextdomain} with domain name @samp{bison-runtime}.
6586For example:
6587
6588@example
6589bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
6590@end example
6591
6592Typically this appears after any other call @code{bindtextdomain
6593(PACKAGE, LOCALEDIR)} that your package already has.  Here we rely on
6594@samp{BISON_LOCALEDIR} to be defined as a string through the
6595@file{Makefile}.
6596
6597@item
6598In the @file{Makefile.am} that controls the compilation of the @code{main}
6599function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
6600either in @samp{DEFS} or in @samp{AM_CPPFLAGS}.  For example:
6601
6602@example
6603DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6604@end example
6605
6606or:
6607
6608@example
6609AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6610@end example
6611
6612@item
6613Finally, invoke the command @command{autoreconf} to generate the build
6614infrastructure.
6615@end enumerate
6616
6617
6618@node Algorithm
6619@chapter The Bison Parser Algorithm
6620@cindex Bison parser algorithm
6621@cindex algorithm of parser
6622@cindex shifting
6623@cindex reduction
6624@cindex parser stack
6625@cindex stack, parser
6626
6627As Bison reads tokens, it pushes them onto a stack along with their
6628semantic values.  The stack is called the @dfn{parser stack}.  Pushing a
6629token is traditionally called @dfn{shifting}.
6630
6631For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
6632@samp{3} to come.  The stack will have four elements, one for each token
6633that was shifted.
6634
6635But the stack does not always have an element for each token read.  When
6636the last @var{n} tokens and groupings shifted match the components of a
6637grammar rule, they can be combined according to that rule.  This is called
6638@dfn{reduction}.  Those tokens and groupings are replaced on the stack by a
6639single grouping whose symbol is the result (left hand side) of that rule.
6640Running the rule's action is part of the process of reduction, because this
6641is what computes the semantic value of the resulting grouping.
6642
6643For example, if the infix calculator's parser stack contains this:
6644
6645@example
66461 + 5 * 3
6647@end example
6648
6649@noindent
6650and the next input token is a newline character, then the last three
6651elements can be reduced to 15 via the rule:
6652
6653@example
6654expr: expr '*' expr;
6655@end example
6656
6657@noindent
6658Then the stack contains just these three elements:
6659
6660@example
66611 + 15
6662@end example
6663
6664@noindent
6665At this point, another reduction can be made, resulting in the single value
666616.  Then the newline token can be shifted.
6667
6668The parser tries, by shifts and reductions, to reduce the entire input down
6669to a single grouping whose symbol is the grammar's start-symbol
6670(@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
6671
6672This kind of parser is known in the literature as a bottom-up parser.
6673
6674@menu
6675* Lookahead::         Parser looks one token ahead when deciding what to do.
6676* Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
6677* Precedence::        Operator precedence works by resolving conflicts.
6678* Contextual Precedence::  When an operator's precedence depends on context.
6679* Parser States::     The parser is a finite-state-machine with stack.
6680* Reduce/Reduce::     When two rules are applicable in the same situation.
6681* Mysterious Conflicts:: Conflicts that look unjustified.
6682* Tuning LR::         How to tune fundamental aspects of LR-based parsing.
6683* Generalized LR Parsing::  Parsing arbitrary context-free grammars.
6684* Memory Management:: What happens when memory is exhausted.  How to avoid it.
6685@end menu
6686
6687@node Lookahead
6688@section Lookahead Tokens
6689@cindex lookahead token
6690
6691The Bison parser does @emph{not} always reduce immediately as soon as the
6692last @var{n} tokens and groupings match a rule.  This is because such a
6693simple strategy is inadequate to handle most languages.  Instead, when a
6694reduction is possible, the parser sometimes ``looks ahead'' at the next
6695token in order to decide what to do.
6696
6697When a token is read, it is not immediately shifted; first it becomes the
6698@dfn{lookahead token}, which is not on the stack.  Now the parser can
6699perform one or more reductions of tokens and groupings on the stack, while
6700the lookahead token remains off to the side.  When no more reductions
6701should take place, the lookahead token is shifted onto the stack.  This
6702does not mean that all possible reductions have been done; depending on the
6703token type of the lookahead token, some rules may choose to delay their
6704application.
6705
6706Here is a simple case where lookahead is needed.  These three rules define
6707expressions which contain binary addition operators and postfix unary
6708factorial operators (@samp{!}), and allow parentheses for grouping.
6709
6710@example
6711@group
6712expr:
6713  term '+' expr
6714| term
6715;
6716@end group
6717
6718@group
6719term:
6720  '(' expr ')'
6721| term '!'
6722| "number"
6723;
6724@end group
6725@end example
6726
6727Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
6728should be done?  If the following token is @samp{)}, then the first three
6729tokens must be reduced to form an @code{expr}.  This is the only valid
6730course, because shifting the @samp{)} would produce a sequence of symbols
6731@w{@code{term ')'}}, and no rule allows this.
6732
6733If the following token is @samp{!}, then it must be shifted immediately so
6734that @w{@samp{2 !}} can be reduced to make a @code{term}.  If instead the
6735parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
6736@code{expr}.  It would then be impossible to shift the @samp{!} because
6737doing so would produce on the stack the sequence of symbols @code{expr
6738'!'}.  No rule allows that sequence.
6739
6740@vindex yychar
6741@vindex yylval
6742@vindex yylloc
6743The lookahead token is stored in the variable @code{yychar}.
6744Its semantic value and location, if any, are stored in the variables
6745@code{yylval} and @code{yylloc}.
6746@xref{Action Features, ,Special Features for Use in Actions}.
6747
6748@node Shift/Reduce
6749@section Shift/Reduce Conflicts
6750@cindex conflicts
6751@cindex shift/reduce conflicts
6752@cindex dangling @code{else}
6753@cindex @code{else}, dangling
6754
6755Suppose we are parsing a language which has if-then and if-then-else
6756statements, with a pair of rules like this:
6757
6758@example
6759@group
6760if_stmt:
6761  "if" expr "then" stmt
6762| "if" expr "then" stmt "else" stmt
6763;
6764@end group
6765@end example
6766
6767@noindent
6768Here @code{"if"}, @code{"then"} and @code{"else"} are terminal symbols for
6769specific keyword tokens.
6770
6771When the @code{"else"} token is read and becomes the lookahead token, the
6772contents of the stack (assuming the input is valid) are just right for
6773reduction by the first rule.  But it is also legitimate to shift the
6774@code{"else"}, because that would lead to eventual reduction by the second
6775rule.
6776
6777This situation, where either a shift or a reduction would be valid, is
6778called a @dfn{shift/reduce conflict}.  Bison is designed to resolve
6779these conflicts by choosing to shift, unless otherwise directed by
6780operator precedence declarations.  To see the reason for this, let's
6781contrast it with the other alternative.
6782
6783Since the parser prefers to shift the @code{"else"}, the result is to attach
6784the else-clause to the innermost if-statement, making these two inputs
6785equivalent:
6786
6787@example
6788if x then if y then win; else lose;
6789
6790if x then do; if y then win; else lose; end;
6791@end example
6792
6793But if the parser chose to reduce when possible rather than shift, the
6794result would be to attach the else-clause to the outermost if-statement,
6795making these two inputs equivalent:
6796
6797@example
6798if x then if y then win; else lose;
6799
6800if x then do; if y then win; end; else lose;
6801@end example
6802
6803The conflict exists because the grammar as written is ambiguous: either
6804parsing of the simple nested if-statement is legitimate.  The established
6805convention is that these ambiguities are resolved by attaching the
6806else-clause to the innermost if-statement; this is what Bison accomplishes
6807by choosing to shift rather than reduce.  (It would ideally be cleaner to
6808write an unambiguous grammar, but that is very hard to do in this case.)
6809This particular ambiguity was first encountered in the specifications of
6810Algol 60 and is called the ``dangling @code{else}'' ambiguity.
6811
6812To avoid warnings from Bison about predictable, legitimate shift/reduce
6813conflicts, you can use the @code{%expect @var{n}} declaration.
6814There will be no warning as long as the number of shift/reduce conflicts
6815is exactly @var{n}, and Bison will report an error if there is a
6816different number.
6817@xref{Expect Decl, ,Suppressing Conflict Warnings}.  However, we don't
6818recommend the use of @code{%expect} (except @samp{%expect 0}!), as an equal
6819number of conflicts does not mean that they are the @emph{same}.  When
6820possible, you should rather use precedence directives to @emph{fix} the
6821conflicts explicitly (@pxref{Non Operators,, Using Precedence For Non
6822Operators}).
6823
6824The definition of @code{if_stmt} above is solely to blame for the
6825conflict, but the conflict does not actually appear without additional
6826rules.  Here is a complete Bison grammar file that actually manifests
6827the conflict:
6828
6829@example
6830@group
6831%%
6832@end group
6833@group
6834stmt:
6835  expr
6836| if_stmt
6837;
6838@end group
6839
6840@group
6841if_stmt:
6842  "if" expr "then" stmt
6843| "if" expr "then" stmt "else" stmt
6844;
6845@end group
6846
6847expr:
6848  "identifier"
6849;
6850@end example
6851
6852@node Precedence
6853@section Operator Precedence
6854@cindex operator precedence
6855@cindex precedence of operators
6856
6857Another situation where shift/reduce conflicts appear is in arithmetic
6858expressions.  Here shifting is not always the preferred resolution; the
6859Bison declarations for operator precedence allow you to specify when to
6860shift and when to reduce.
6861
6862@menu
6863* Why Precedence::    An example showing why precedence is needed.
6864* Using Precedence::  How to specify precedence in Bison grammars.
6865* Precedence Examples::  How these features are used in the previous example.
6866* How Precedence::    How they work.
6867* Non Operators::     Using precedence for general conflicts.
6868@end menu
6869
6870@node Why Precedence
6871@subsection When Precedence is Needed
6872
6873Consider the following ambiguous grammar fragment (ambiguous because the
6874input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
6875
6876@example
6877@group
6878expr:
6879  expr '-' expr
6880| expr '*' expr
6881| expr '<' expr
6882| '(' expr ')'
6883@dots{}
6884;
6885@end group
6886@end example
6887
6888@noindent
6889Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
6890should it reduce them via the rule for the subtraction operator?  It
6891depends on the next token.  Of course, if the next token is @samp{)}, we
6892must reduce; shifting is invalid because no single rule can reduce the
6893token sequence @w{@samp{- 2 )}} or anything starting with that.  But if
6894the next token is @samp{*} or @samp{<}, we have a choice: either
6895shifting or reduction would allow the parse to complete, but with
6896different results.
6897
6898To decide which one Bison should do, we must consider the results.  If
6899the next operator token @var{op} is shifted, then it must be reduced
6900first in order to permit another opportunity to reduce the difference.
6901The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}.  On the other
6902hand, if the subtraction is reduced before shifting @var{op}, the result
6903is @w{@samp{(1 - 2) @var{op} 3}}.  Clearly, then, the choice of shift or
6904reduce should depend on the relative precedence of the operators
6905@samp{-} and @var{op}: @samp{*} should be shifted first, but not
6906@samp{<}.
6907
6908@cindex associativity
6909What about input such as @w{@samp{1 - 2 - 5}}; should this be
6910@w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}?  For most
6911operators we prefer the former, which is called @dfn{left association}.
6912The latter alternative, @dfn{right association}, is desirable for
6913assignment operators.  The choice of left or right association is a
6914matter of whether the parser chooses to shift or reduce when the stack
6915contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
6916makes right-associativity.
6917
6918@node Using Precedence
6919@subsection Specifying Operator Precedence
6920@findex %left
6921@findex %right
6922@findex %nonassoc
6923
6924Bison allows you to specify these choices with the operator precedence
6925declarations @code{%left} and @code{%right}.  Each such declaration
6926contains a list of tokens, which are operators whose precedence and
6927associativity is being declared.  The @code{%left} declaration makes all
6928those operators left-associative and the @code{%right} declaration makes
6929them right-associative.  A third alternative is @code{%nonassoc}, which
6930declares that it is a syntax error to find the same operator twice ``in a
6931row''.
6932
6933The relative precedence of different operators is controlled by the
6934order in which they are declared.  The first @code{%left} or
6935@code{%right} declaration in the file declares the operators whose
6936precedence is lowest, the next such declaration declares the operators
6937whose precedence is a little higher, and so on.
6938
6939@node Precedence Examples
6940@subsection Precedence Examples
6941
6942In our example, we would want the following declarations:
6943
6944@example
6945%left '<'
6946%left '-'
6947%left '*'
6948@end example
6949
6950In a more complete example, which supports other operators as well, we
6951would declare them in groups of equal precedence.  For example, @code{'+'} is
6952declared with @code{'-'}:
6953
6954@example
6955%left '<' '>' '=' "!=" "<=" ">="
6956%left '+' '-'
6957%left '*' '/'
6958@end example
6959
6960@node How Precedence
6961@subsection How Precedence Works
6962
6963The first effect of the precedence declarations is to assign precedence
6964levels to the terminal symbols declared.  The second effect is to assign
6965precedence levels to certain rules: each rule gets its precedence from
6966the last terminal symbol mentioned in the components.  (You can also
6967specify explicitly the precedence of a rule.  @xref{Contextual
6968Precedence, ,Context-Dependent Precedence}.)
6969
6970Finally, the resolution of conflicts works by comparing the precedence
6971of the rule being considered with that of the lookahead token.  If the
6972token's precedence is higher, the choice is to shift.  If the rule's
6973precedence is higher, the choice is to reduce.  If they have equal
6974precedence, the choice is made based on the associativity of that
6975precedence level.  The verbose output file made by @samp{-v}
6976(@pxref{Invocation, ,Invoking Bison}) says how each conflict was
6977resolved.
6978
6979Not all rules and not all tokens have precedence.  If either the rule or
6980the lookahead token has no precedence, then the default is to shift.
6981
6982@node Non Operators
6983@subsection Using Precedence For Non Operators
6984
6985Using properly precedence and associativity directives can help fixing
6986shift/reduce conflicts that do not involve arithmetics-like operators.  For
6987instance, the ``dangling @code{else}'' problem (@pxref{Shift/Reduce, ,
6988Shift/Reduce Conflicts}) can be solved elegantly in two different ways.
6989
6990In the present case, the conflict is between the token @code{"else"} willing
6991to be shifted, and the rule @samp{if_stmt: "if" expr "then" stmt}, asking
6992for reduction.  By default, the precedence of a rule is that of its last
6993token, here @code{"then"}, so the conflict will be solved appropriately
6994by giving @code{"else"} a precedence higher than that of @code{"then"}, for
6995instance as follows:
6996
6997@example
6998@group
6999%nonassoc "then"
7000%nonassoc "else"
7001@end group
7002@end example
7003
7004Alternatively, you may give both tokens the same precedence, in which case
7005associativity is used to solve the conflict.  To preserve the shift action,
7006use right associativity:
7007
7008@example
7009%right "then" "else"
7010@end example
7011
7012Neither solution is perfect however.  Since Bison does not provide, so far,
7013support for ``scoped'' precedence, both force you to declare the precedence
7014of these keywords with respect to the other operators your grammar.
7015Therefore, instead of being warned about new conflicts you would be unaware
7016of (e.g., a shift/reduce conflict due to @samp{if test then 1 else 2 + 3}
7017being ambiguous: @samp{if test then 1 else (2 + 3)} or @samp{(if test then 1
7018else 2) + 3}?), the conflict will be already ``fixed''.
7019
7020@node Contextual Precedence
7021@section Context-Dependent Precedence
7022@cindex context-dependent precedence
7023@cindex unary operator precedence
7024@cindex precedence, context-dependent
7025@cindex precedence, unary operator
7026@findex %prec
7027
7028Often the precedence of an operator depends on the context.  This sounds
7029outlandish at first, but it is really very common.  For example, a minus
7030sign typically has a very high precedence as a unary operator, and a
7031somewhat lower precedence (lower than multiplication) as a binary operator.
7032
7033The Bison precedence declarations, @code{%left}, @code{%right} and
7034@code{%nonassoc}, can only be used once for a given token; so a token has
7035only one precedence declared in this way.  For context-dependent
7036precedence, you need to use an additional mechanism: the @code{%prec}
7037modifier for rules.
7038
7039The @code{%prec} modifier declares the precedence of a particular rule by
7040specifying a terminal symbol whose precedence should be used for that rule.
7041It's not necessary for that symbol to appear otherwise in the rule.  The
7042modifier's syntax is:
7043
7044@example
7045%prec @var{terminal-symbol}
7046@end example
7047
7048@noindent
7049and it is written after the components of the rule.  Its effect is to
7050assign the rule the precedence of @var{terminal-symbol}, overriding
7051the precedence that would be deduced for it in the ordinary way.  The
7052altered rule precedence then affects how conflicts involving that rule
7053are resolved (@pxref{Precedence, ,Operator Precedence}).
7054
7055Here is how @code{%prec} solves the problem of unary minus.  First, declare
7056a precedence for a fictitious terminal symbol named @code{UMINUS}.  There
7057are no tokens of this type, but the symbol serves to stand for its
7058precedence:
7059
7060@example
7061@dots{}
7062%left '+' '-'
7063%left '*'
7064%left UMINUS
7065@end example
7066
7067Now the precedence of @code{UMINUS} can be used in specific rules:
7068
7069@example
7070@group
7071exp:
7072  @dots{}
7073| exp '-' exp
7074  @dots{}
7075| '-' exp %prec UMINUS
7076@end group
7077@end example
7078
7079@ifset defaultprec
7080If you forget to append @code{%prec UMINUS} to the rule for unary
7081minus, Bison silently assumes that minus has its usual precedence.
7082This kind of problem can be tricky to debug, since one typically
7083discovers the mistake only by testing the code.
7084
7085The @code{%no-default-prec;} declaration makes it easier to discover
7086this kind of problem systematically.  It causes rules that lack a
7087@code{%prec} modifier to have no precedence, even if the last terminal
7088symbol mentioned in their components has a declared precedence.
7089
7090If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
7091for all rules that participate in precedence conflict resolution.
7092Then you will see any shift/reduce conflict until you tell Bison how
7093to resolve it, either by changing your grammar or by adding an
7094explicit precedence.  This will probably add declarations to the
7095grammar, but it helps to protect against incorrect rule precedences.
7096
7097The effect of @code{%no-default-prec;} can be reversed by giving
7098@code{%default-prec;}, which is the default.
7099@end ifset
7100
7101@node Parser States
7102@section Parser States
7103@cindex finite-state machine
7104@cindex parser state
7105@cindex state (of parser)
7106
7107The function @code{yyparse} is implemented using a finite-state machine.
7108The values pushed on the parser stack are not simply token type codes; they
7109represent the entire sequence of terminal and nonterminal symbols at or
7110near the top of the stack.  The current state collects all the information
7111about previous input which is relevant to deciding what to do next.
7112
7113Each time a lookahead token is read, the current parser state together
7114with the type of lookahead token are looked up in a table.  This table
7115entry can say, ``Shift the lookahead token.''  In this case, it also
7116specifies the new parser state, which is pushed onto the top of the
7117parser stack.  Or it can say, ``Reduce using rule number @var{n}.''
7118This means that a certain number of tokens or groupings are taken off
7119the top of the stack, and replaced by one grouping.  In other words,
7120that number of states are popped from the stack, and one new state is
7121pushed.
7122
7123There is one other alternative: the table can say that the lookahead token
7124is erroneous in the current state.  This causes error processing to begin
7125(@pxref{Error Recovery}).
7126
7127@node Reduce/Reduce
7128@section Reduce/Reduce Conflicts
7129@cindex reduce/reduce conflict
7130@cindex conflicts, reduce/reduce
7131
7132A reduce/reduce conflict occurs if there are two or more rules that apply
7133to the same sequence of input.  This usually indicates a serious error
7134in the grammar.
7135
7136For example, here is an erroneous attempt to define a sequence
7137of zero or more @code{word} groupings.
7138
7139@example
7140@group
7141sequence:
7142  /* empty */    @{ printf ("empty sequence\n"); @}
7143| maybeword
7144| sequence word  @{ printf ("added word %s\n", $2); @}
7145;
7146@end group
7147
7148@group
7149maybeword:
7150  /* empty */   @{ printf ("empty maybeword\n"); @}
7151| word          @{ printf ("single word %s\n", $1); @}
7152;
7153@end group
7154@end example
7155
7156@noindent
7157The error is an ambiguity: there is more than one way to parse a single
7158@code{word} into a @code{sequence}.  It could be reduced to a
7159@code{maybeword} and then into a @code{sequence} via the second rule.
7160Alternatively, nothing-at-all could be reduced into a @code{sequence}
7161via the first rule, and this could be combined with the @code{word}
7162using the third rule for @code{sequence}.
7163
7164There is also more than one way to reduce nothing-at-all into a
7165@code{sequence}.  This can be done directly via the first rule,
7166or indirectly via @code{maybeword} and then the second rule.
7167
7168You might think that this is a distinction without a difference, because it
7169does not change whether any particular input is valid or not.  But it does
7170affect which actions are run.  One parsing order runs the second rule's
7171action; the other runs the first rule's action and the third rule's action.
7172In this example, the output of the program changes.
7173
7174Bison resolves a reduce/reduce conflict by choosing to use the rule that
7175appears first in the grammar, but it is very risky to rely on this.  Every
7176reduce/reduce conflict must be studied and usually eliminated.  Here is the
7177proper way to define @code{sequence}:
7178
7179@example
7180@group
7181sequence:
7182  /* empty */    @{ printf ("empty sequence\n"); @}
7183| sequence word  @{ printf ("added word %s\n", $2); @}
7184;
7185@end group
7186@end example
7187
7188Here is another common error that yields a reduce/reduce conflict:
7189
7190@example
7191sequence:
7192@group
7193  /* empty */
7194| sequence words
7195| sequence redirects
7196;
7197@end group
7198
7199@group
7200words:
7201  /* empty */
7202| words word
7203;
7204@end group
7205
7206@group
7207redirects:
7208  /* empty */
7209| redirects redirect
7210;
7211@end group
7212@end example
7213
7214@noindent
7215The intention here is to define a sequence which can contain either
7216@code{word} or @code{redirect} groupings.  The individual definitions of
7217@code{sequence}, @code{words} and @code{redirects} are error-free, but the
7218three together make a subtle ambiguity: even an empty input can be parsed
7219in infinitely many ways!
7220
7221Consider: nothing-at-all could be a @code{words}.  Or it could be two
7222@code{words} in a row, or three, or any number.  It could equally well be a
7223@code{redirects}, or two, or any number.  Or it could be a @code{words}
7224followed by three @code{redirects} and another @code{words}.  And so on.
7225
7226Here are two ways to correct these rules.  First, to make it a single level
7227of sequence:
7228
7229@example
7230sequence:
7231  /* empty */
7232| sequence word
7233| sequence redirect
7234;
7235@end example
7236
7237Second, to prevent either a @code{words} or a @code{redirects}
7238from being empty:
7239
7240@example
7241@group
7242sequence:
7243  /* empty */
7244| sequence words
7245| sequence redirects
7246;
7247@end group
7248
7249@group
7250words:
7251  word
7252| words word
7253;
7254@end group
7255
7256@group
7257redirects:
7258  redirect
7259| redirects redirect
7260;
7261@end group
7262@end example
7263
7264Yet this proposal introduces another kind of ambiguity!  The input
7265@samp{word word} can be parsed as a single @code{words} composed of two
7266@samp{word}s, or as two one-@code{word} @code{words} (and likewise for
7267@code{redirect}/@code{redirects}).  However this ambiguity is now a
7268shift/reduce conflict, and therefore it can now be addressed with precedence
7269directives.
7270
7271To simplify the matter, we will proceed with @code{word} and @code{redirect}
7272being tokens: @code{"word"} and @code{"redirect"}.
7273
7274To prefer the longest @code{words}, the conflict between the token
7275@code{"word"} and the rule @samp{sequence: sequence words} must be resolved
7276as a shift.  To this end, we use the same techniques as exposed above, see
7277@ref{Non Operators,, Using Precedence For Non Operators}.  One solution
7278relies on precedences: use @code{%prec} to give a lower precedence to the
7279rule:
7280
7281@example
7282%nonassoc "word"
7283%nonassoc "sequence"
7284%%
7285@group
7286sequence:
7287  /* empty */
7288| sequence word      %prec "sequence"
7289| sequence redirect  %prec "sequence"
7290;
7291@end group
7292
7293@group
7294words:
7295  word
7296| words "word"
7297;
7298@end group
7299@end example
7300
7301Another solution relies on associativity: provide both the token and the
7302rule with the same precedence, but make them right-associative:
7303
7304@example
7305%right "word" "redirect"
7306%%
7307@group
7308sequence:
7309  /* empty */
7310| sequence word      %prec "word"
7311| sequence redirect  %prec "redirect"
7312;
7313@end group
7314@end example
7315
7316@node Mysterious Conflicts
7317@section Mysterious Conflicts
7318@cindex Mysterious Conflicts
7319
7320Sometimes reduce/reduce conflicts can occur that don't look warranted.
7321Here is an example:
7322
7323@example
7324@group
7325%%
7326def: param_spec return_spec ',';
7327param_spec:
7328  type
7329| name_list ':' type
7330;
7331@end group
7332@group
7333return_spec:
7334  type
7335| name ':' type
7336;
7337@end group
7338@group
7339type: "id";
7340@end group
7341@group
7342name: "id";
7343name_list:
7344  name
7345| name ',' name_list
7346;
7347@end group
7348@end example
7349
7350It would seem that this grammar can be parsed with only a single token of
7351lookahead: when a @code{param_spec} is being read, an @code{"id"} is a
7352@code{name} if a comma or colon follows, or a @code{type} if another
7353@code{"id"} follows.  In other words, this grammar is LR(1).
7354
7355@cindex LR
7356@cindex LALR
7357However, for historical reasons, Bison cannot by default handle all
7358LR(1) grammars.
7359In this grammar, two contexts, that after an @code{"id"} at the beginning
7360of a @code{param_spec} and likewise at the beginning of a
7361@code{return_spec}, are similar enough that Bison assumes they are the
7362same.
7363They appear similar because the same set of rules would be
7364active---the rule for reducing to a @code{name} and that for reducing to
7365a @code{type}.  Bison is unable to determine at that stage of processing
7366that the rules would require different lookahead tokens in the two
7367contexts, so it makes a single parser state for them both.  Combining
7368the two contexts causes a conflict later.  In parser terminology, this
7369occurrence means that the grammar is not LALR(1).
7370
7371@cindex IELR
7372@cindex canonical LR
7373For many practical grammars (specifically those that fall into the non-LR(1)
7374class), the limitations of LALR(1) result in difficulties beyond just
7375mysterious reduce/reduce conflicts.  The best way to fix all these problems
7376is to select a different parser table construction algorithm.  Either
7377IELR(1) or canonical LR(1) would suffice, but the former is more efficient
7378and easier to debug during development.  @xref{LR Table Construction}, for
7379details.  (Bison's IELR(1) and canonical LR(1) implementations are
7380experimental.  More user feedback will help to stabilize them.)
7381
7382If you instead wish to work around LALR(1)'s limitations, you
7383can often fix a mysterious conflict by identifying the two parser states
7384that are being confused, and adding something to make them look
7385distinct.  In the above example, adding one rule to
7386@code{return_spec} as follows makes the problem go away:
7387
7388@example
7389@group
7390@dots{}
7391return_spec:
7392  type
7393| name ':' type
7394| "id" "bogus"       /* This rule is never used.  */
7395;
7396@end group
7397@end example
7398
7399This corrects the problem because it introduces the possibility of an
7400additional active rule in the context after the @code{"id"} at the beginning of
7401@code{return_spec}.  This rule is not active in the corresponding context
7402in a @code{param_spec}, so the two contexts receive distinct parser states.
7403As long as the token @code{"bogus"} is never generated by @code{yylex},
7404the added rule cannot alter the way actual input is parsed.
7405
7406In this particular example, there is another way to solve the problem:
7407rewrite the rule for @code{return_spec} to use @code{"id"} directly
7408instead of via @code{name}.  This also causes the two confusing
7409contexts to have different sets of active rules, because the one for
7410@code{return_spec} activates the altered rule for @code{return_spec}
7411rather than the one for @code{name}.
7412
7413@example
7414param_spec:
7415  type
7416| name_list ':' type
7417;
7418return_spec:
7419  type
7420| "id" ':' type
7421;
7422@end example
7423
7424For a more detailed exposition of LALR(1) parsers and parser
7425generators, @pxref{Bibliography,,DeRemer 1982}.
7426
7427@node Tuning LR
7428@section Tuning LR
7429
7430The default behavior of Bison's LR-based parsers is chosen mostly for
7431historical reasons, but that behavior is often not robust.  For example, in
7432the previous section, we discussed the mysterious conflicts that can be
7433produced by LALR(1), Bison's default parser table construction algorithm.
7434Another example is Bison's @code{%error-verbose} directive, which instructs
7435the generated parser to produce verbose syntax error messages, which can
7436sometimes contain incorrect information.
7437
7438In this section, we explore several modern features of Bison that allow you
7439to tune fundamental aspects of the generated LR-based parsers.  Some of
7440these features easily eliminate shortcomings like those mentioned above.
7441Others can be helpful purely for understanding your parser.
7442
7443Most of the features discussed in this section are still experimental.  More
7444user feedback will help to stabilize them.
7445
7446@menu
7447* LR Table Construction:: Choose a different construction algorithm.
7448* Default Reductions::    Disable default reductions.
7449* LAC::                   Correct lookahead sets in the parser states.
7450* Unreachable States::    Keep unreachable parser states for debugging.
7451@end menu
7452
7453@node LR Table Construction
7454@subsection LR Table Construction
7455@cindex Mysterious Conflict
7456@cindex LALR
7457@cindex IELR
7458@cindex canonical LR
7459@findex %define lr.type
7460
7461For historical reasons, Bison constructs LALR(1) parser tables by default.
7462However, LALR does not possess the full language-recognition power of LR.
7463As a result, the behavior of parsers employing LALR parser tables is often
7464mysterious.  We presented a simple example of this effect in @ref{Mysterious
7465Conflicts}.
7466
7467As we also demonstrated in that example, the traditional approach to
7468eliminating such mysterious behavior is to restructure the grammar.
7469Unfortunately, doing so correctly is often difficult.  Moreover, merely
7470discovering that LALR causes mysterious behavior in your parser can be
7471difficult as well.
7472
7473Fortunately, Bison provides an easy way to eliminate the possibility of such
7474mysterious behavior altogether.  You simply need to activate a more powerful
7475parser table construction algorithm by using the @code{%define lr.type}
7476directive.
7477
7478@deffn {Directive} {%define lr.type} @var{type}
7479Specify the type of parser tables within the LR(1) family.  The accepted
7480values for @var{type} are:
7481
7482@itemize
7483@item @code{lalr} (default)
7484@item @code{ielr}
7485@item @code{canonical-lr}
7486@end itemize
7487
7488(This feature is experimental. More user feedback will help to stabilize
7489it.)
7490@end deffn
7491
7492For example, to activate IELR, you might add the following directive to you
7493grammar file:
7494
7495@example
7496%define lr.type ielr
7497@end example
7498
7499@noindent For the example in @ref{Mysterious Conflicts}, the mysterious
7500conflict is then eliminated, so there is no need to invest time in
7501comprehending the conflict or restructuring the grammar to fix it.  If,
7502during future development, the grammar evolves such that all mysterious
7503behavior would have disappeared using just LALR, you need not fear that
7504continuing to use IELR will result in unnecessarily large parser tables.
7505That is, IELR generates LALR tables when LALR (using a deterministic parsing
7506algorithm) is sufficient to support the full language-recognition power of
7507LR.  Thus, by enabling IELR at the start of grammar development, you can
7508safely and completely eliminate the need to consider LALR's shortcomings.
7509
7510While IELR is almost always preferable, there are circumstances where LALR
7511or the canonical LR parser tables described by Knuth
7512(@pxref{Bibliography,,Knuth 1965}) can be useful.  Here we summarize the
7513relative advantages of each parser table construction algorithm within
7514Bison:
7515
7516@itemize
7517@item LALR
7518
7519There are at least two scenarios where LALR can be worthwhile:
7520
7521@itemize
7522@item GLR without static conflict resolution.
7523
7524@cindex GLR with LALR
7525When employing GLR parsers (@pxref{GLR Parsers}), if you do not resolve any
7526conflicts statically (for example, with @code{%left} or @code{%prec}), then
7527the parser explores all potential parses of any given input.  In this case,
7528the choice of parser table construction algorithm is guaranteed not to alter
7529the language accepted by the parser.  LALR parser tables are the smallest
7530parser tables Bison can currently construct, so they may then be preferable.
7531Nevertheless, once you begin to resolve conflicts statically, GLR behaves
7532more like a deterministic parser in the syntactic contexts where those
7533conflicts appear, and so either IELR or canonical LR can then be helpful to
7534avoid LALR's mysterious behavior.
7535
7536@item Malformed grammars.
7537
7538Occasionally during development, an especially malformed grammar with a
7539major recurring flaw may severely impede the IELR or canonical LR parser
7540table construction algorithm.  LALR can be a quick way to construct parser
7541tables in order to investigate such problems while ignoring the more subtle
7542differences from IELR and canonical LR.
7543@end itemize
7544
7545@item IELR
7546
7547IELR (Inadequacy Elimination LR) is a minimal LR algorithm.  That is, given
7548any grammar (LR or non-LR), parsers using IELR or canonical LR parser tables
7549always accept exactly the same set of sentences.  However, like LALR, IELR
7550merges parser states during parser table construction so that the number of
7551parser states is often an order of magnitude less than for canonical LR.
7552More importantly, because canonical LR's extra parser states may contain
7553duplicate conflicts in the case of non-LR grammars, the number of conflicts
7554for IELR is often an order of magnitude less as well.  This effect can
7555significantly reduce the complexity of developing a grammar.
7556
7557@item Canonical LR
7558
7559@cindex delayed syntax error detection
7560@cindex LAC
7561@findex %nonassoc
7562While inefficient, canonical LR parser tables can be an interesting means to
7563explore a grammar because they possess a property that IELR and LALR tables
7564do not.  That is, if @code{%nonassoc} is not used and default reductions are
7565left disabled (@pxref{Default Reductions}), then, for every left context of
7566every canonical LR state, the set of tokens accepted by that state is
7567guaranteed to be the exact set of tokens that is syntactically acceptable in
7568that left context.  It might then seem that an advantage of canonical LR
7569parsers in production is that, under the above constraints, they are
7570guaranteed to detect a syntax error as soon as possible without performing
7571any unnecessary reductions.  However, IELR parsers that use LAC are also
7572able to achieve this behavior without sacrificing @code{%nonassoc} or
7573default reductions.  For details and a few caveats of LAC, @pxref{LAC}.
7574@end itemize
7575
7576For a more detailed exposition of the mysterious behavior in LALR parsers
7577and the benefits of IELR, @pxref{Bibliography,,Denny 2008 March}, and
7578@ref{Bibliography,,Denny 2010 November}.
7579
7580@node Default Reductions
7581@subsection Default Reductions
7582@cindex default reductions
7583@findex %define lr.default-reductions
7584@findex %nonassoc
7585
7586After parser table construction, Bison identifies the reduction with the
7587largest lookahead set in each parser state.  To reduce the size of the
7588parser state, traditional Bison behavior is to remove that lookahead set and
7589to assign that reduction to be the default parser action.  Such a reduction
7590is known as a @dfn{default reduction}.
7591
7592Default reductions affect more than the size of the parser tables.  They
7593also affect the behavior of the parser:
7594
7595@itemize
7596@item Delayed @code{yylex} invocations.
7597
7598@cindex delayed yylex invocations
7599@cindex consistent states
7600@cindex defaulted states
7601A @dfn{consistent state} is a state that has only one possible parser
7602action.  If that action is a reduction and is encoded as a default
7603reduction, then that consistent state is called a @dfn{defaulted state}.
7604Upon reaching a defaulted state, a Bison-generated parser does not bother to
7605invoke @code{yylex} to fetch the next token before performing the reduction.
7606In other words, whether default reductions are enabled in consistent states
7607determines how soon a Bison-generated parser invokes @code{yylex} for a
7608token: immediately when it @emph{reaches} that token in the input or when it
7609eventually @emph{needs} that token as a lookahead to determine the next
7610parser action.  Traditionally, default reductions are enabled, and so the
7611parser exhibits the latter behavior.
7612
7613The presence of defaulted states is an important consideration when
7614designing @code{yylex} and the grammar file.  That is, if the behavior of
7615@code{yylex} can influence or be influenced by the semantic actions
7616associated with the reductions in defaulted states, then the delay of the
7617next @code{yylex} invocation until after those reductions is significant.
7618For example, the semantic actions might pop a scope stack that @code{yylex}
7619uses to determine what token to return.  Thus, the delay might be necessary
7620to ensure that @code{yylex} does not look up the next token in a scope that
7621should already be considered closed.
7622
7623@item Delayed syntax error detection.
7624
7625@cindex delayed syntax error detection
7626When the parser fetches a new token by invoking @code{yylex}, it checks
7627whether there is an action for that token in the current parser state.  The
7628parser detects a syntax error if and only if either (1) there is no action
7629for that token or (2) the action for that token is the error action (due to
7630the use of @code{%nonassoc}).  However, if there is a default reduction in
7631that state (which might or might not be a defaulted state), then it is
7632impossible for condition 1 to exist.  That is, all tokens have an action.
7633Thus, the parser sometimes fails to detect the syntax error until it reaches
7634a later state.
7635
7636@cindex LAC
7637@c If there's an infinite loop, default reductions can prevent an incorrect
7638@c sentence from being rejected.
7639While default reductions never cause the parser to accept syntactically
7640incorrect sentences, the delay of syntax error detection can have unexpected
7641effects on the behavior of the parser.  However, the delay can be caused
7642anyway by parser state merging and the use of @code{%nonassoc}, and it can
7643be fixed by another Bison feature, LAC.  We discuss the effects of delayed
7644syntax error detection and LAC more in the next section (@pxref{LAC}).
7645@end itemize
7646
7647For canonical LR, the only default reduction that Bison enables by default
7648is the accept action, which appears only in the accepting state, which has
7649no other action and is thus a defaulted state.  However, the default accept
7650action does not delay any @code{yylex} invocation or syntax error detection
7651because the accept action ends the parse.
7652
7653For LALR and IELR, Bison enables default reductions in nearly all states by
7654default.  There are only two exceptions.  First, states that have a shift
7655action on the @code{error} token do not have default reductions because
7656delayed syntax error detection could then prevent the @code{error} token
7657from ever being shifted in that state.  However, parser state merging can
7658cause the same effect anyway, and LAC fixes it in both cases, so future
7659versions of Bison might drop this exception when LAC is activated.  Second,
7660GLR parsers do not record the default reduction as the action on a lookahead
7661token for which there is a conflict.  The correct action in this case is to
7662split the parse instead.
7663
7664To adjust which states have default reductions enabled, use the
7665@code{%define lr.default-reductions} directive.
7666
7667@deffn {Directive} {%define lr.default-reductions} @var{where}
7668Specify the kind of states that are permitted to contain default reductions.
7669The accepted values of @var{where} are:
7670@itemize
7671@item @code{most} (default for LALR and IELR)
7672@item @code{consistent}
7673@item @code{accepting} (default for canonical LR)
7674@end itemize
7675
7676(The ability to specify where default reductions are permitted is
7677experimental.  More user feedback will help to stabilize it.)
7678@end deffn
7679
7680@node LAC
7681@subsection LAC
7682@findex %define parse.lac
7683@cindex LAC
7684@cindex lookahead correction
7685
7686Canonical LR, IELR, and LALR can suffer from a couple of problems upon
7687encountering a syntax error.  First, the parser might perform additional
7688parser stack reductions before discovering the syntax error.  Such
7689reductions can perform user semantic actions that are unexpected because
7690they are based on an invalid token, and they cause error recovery to begin
7691in a different syntactic context than the one in which the invalid token was
7692encountered.  Second, when verbose error messages are enabled (@pxref{Error
7693Reporting}), the expected token list in the syntax error message can both
7694contain invalid tokens and omit valid tokens.
7695
7696The culprits for the above problems are @code{%nonassoc}, default reductions
7697in inconsistent states (@pxref{Default Reductions}), and parser state
7698merging.  Because IELR and LALR merge parser states, they suffer the most.
7699Canonical LR can suffer only if @code{%nonassoc} is used or if default
7700reductions are enabled for inconsistent states.
7701
7702LAC (Lookahead Correction) is a new mechanism within the parsing algorithm
7703that solves these problems for canonical LR, IELR, and LALR without
7704sacrificing @code{%nonassoc}, default reductions, or state merging.  You can
7705enable LAC with the @code{%define parse.lac} directive.
7706
7707@deffn {Directive} {%define parse.lac} @var{value}
7708Enable LAC to improve syntax error handling.
7709@itemize
7710@item @code{none} (default)
7711@item @code{full}
7712@end itemize
7713(This feature is experimental.  More user feedback will help to stabilize
7714it.  Moreover, it is currently only available for deterministic parsers in
7715C.)
7716@end deffn
7717
7718Conceptually, the LAC mechanism is straight-forward.  Whenever the parser
7719fetches a new token from the scanner so that it can determine the next
7720parser action, it immediately suspends normal parsing and performs an
7721exploratory parse using a temporary copy of the normal parser state stack.
7722During this exploratory parse, the parser does not perform user semantic
7723actions.  If the exploratory parse reaches a shift action, normal parsing
7724then resumes on the normal parser stacks.  If the exploratory parse reaches
7725an error instead, the parser reports a syntax error.  If verbose syntax
7726error messages are enabled, the parser must then discover the list of
7727expected tokens, so it performs a separate exploratory parse for each token
7728in the grammar.
7729
7730There is one subtlety about the use of LAC.  That is, when in a consistent
7731parser state with a default reduction, the parser will not attempt to fetch
7732a token from the scanner because no lookahead is needed to determine the
7733next parser action.  Thus, whether default reductions are enabled in
7734consistent states (@pxref{Default Reductions}) affects how soon the parser
7735detects a syntax error: immediately when it @emph{reaches} an erroneous
7736token or when it eventually @emph{needs} that token as a lookahead to
7737determine the next parser action.  The latter behavior is probably more
7738intuitive, so Bison currently provides no way to achieve the former behavior
7739while default reductions are enabled in consistent states.
7740
7741Thus, when LAC is in use, for some fixed decision of whether to enable
7742default reductions in consistent states, canonical LR and IELR behave almost
7743exactly the same for both syntactically acceptable and syntactically
7744unacceptable input.  While LALR still does not support the full
7745language-recognition power of canonical LR and IELR, LAC at least enables
7746LALR's syntax error handling to correctly reflect LALR's
7747language-recognition power.
7748
7749There are a few caveats to consider when using LAC:
7750
7751@itemize
7752@item Infinite parsing loops.
7753
7754IELR plus LAC does have one shortcoming relative to canonical LR.  Some
7755parsers generated by Bison can loop infinitely.  LAC does not fix infinite
7756parsing loops that occur between encountering a syntax error and detecting
7757it, but enabling canonical LR or disabling default reductions sometimes
7758does.
7759
7760@item Verbose error message limitations.
7761
7762Because of internationalization considerations, Bison-generated parsers
7763limit the size of the expected token list they are willing to report in a
7764verbose syntax error message.  If the number of expected tokens exceeds that
7765limit, the list is simply dropped from the message.  Enabling LAC can
7766increase the size of the list and thus cause the parser to drop it.  Of
7767course, dropping the list is better than reporting an incorrect list.
7768
7769@item Performance.
7770
7771Because LAC requires many parse actions to be performed twice, it can have a
7772performance penalty.  However, not all parse actions must be performed
7773twice.  Specifically, during a series of default reductions in consistent
7774states and shift actions, the parser never has to initiate an exploratory
7775parse.  Moreover, the most time-consuming tasks in a parse are often the
7776file I/O, the lexical analysis performed by the scanner, and the user's
7777semantic actions, but none of these are performed during the exploratory
7778parse.  Finally, the base of the temporary stack used during an exploratory
7779parse is a pointer into the normal parser state stack so that the stack is
7780never physically copied.  In our experience, the performance penalty of LAC
7781has proved insignificant for practical grammars.
7782@end itemize
7783
7784While the LAC algorithm shares techniques that have been recognized in the
7785parser community for years, for the publication that introduces LAC,
7786@pxref{Bibliography,,Denny 2010 May}.
7787
7788@node Unreachable States
7789@subsection Unreachable States
7790@findex %define lr.keep-unreachable-states
7791@cindex unreachable states
7792
7793If there exists no sequence of transitions from the parser's start state to
7794some state @var{s}, then Bison considers @var{s} to be an @dfn{unreachable
7795state}.  A state can become unreachable during conflict resolution if Bison
7796disables a shift action leading to it from a predecessor state.
7797
7798By default, Bison removes unreachable states from the parser after conflict
7799resolution because they are useless in the generated parser.  However,
7800keeping unreachable states is sometimes useful when trying to understand the
7801relationship between the parser and the grammar.
7802
7803@deffn {Directive} {%define lr.keep-unreachable-states} @var{value}
7804Request that Bison allow unreachable states to remain in the parser tables.
7805@var{value} must be a Boolean.  The default is @code{false}.
7806@end deffn
7807
7808There are a few caveats to consider:
7809
7810@itemize @bullet
7811@item Missing or extraneous warnings.
7812
7813Unreachable states may contain conflicts and may use rules not used in any
7814other state.  Thus, keeping unreachable states may induce warnings that are
7815irrelevant to your parser's behavior, and it may eliminate warnings that are
7816relevant.  Of course, the change in warnings may actually be relevant to a
7817parser table analysis that wants to keep unreachable states, so this
7818behavior will likely remain in future Bison releases.
7819
7820@item Other useless states.
7821
7822While Bison is able to remove unreachable states, it is not guaranteed to
7823remove other kinds of useless states.  Specifically, when Bison disables
7824reduce actions during conflict resolution, some goto actions may become
7825useless, and thus some additional states may become useless.  If Bison were
7826to compute which goto actions were useless and then disable those actions,
7827it could identify such states as unreachable and then remove those states.
7828However, Bison does not compute which goto actions are useless.
7829@end itemize
7830
7831@node Generalized LR Parsing
7832@section Generalized LR (GLR) Parsing
7833@cindex GLR parsing
7834@cindex generalized LR (GLR) parsing
7835@cindex ambiguous grammars
7836@cindex nondeterministic parsing
7837
7838Bison produces @emph{deterministic} parsers that choose uniquely
7839when to reduce and which reduction to apply
7840based on a summary of the preceding input and on one extra token of lookahead.
7841As a result, normal Bison handles a proper subset of the family of
7842context-free languages.
7843Ambiguous grammars, since they have strings with more than one possible
7844sequence of reductions cannot have deterministic parsers in this sense.
7845The same is true of languages that require more than one symbol of
7846lookahead, since the parser lacks the information necessary to make a
7847decision at the point it must be made in a shift-reduce parser.
7848Finally, as previously mentioned (@pxref{Mysterious Conflicts}),
7849there are languages where Bison's default choice of how to
7850summarize the input seen so far loses necessary information.
7851
7852When you use the @samp{%glr-parser} declaration in your grammar file,
7853Bison generates a parser that uses a different algorithm, called
7854Generalized LR (or GLR).  A Bison GLR
7855parser uses the same basic
7856algorithm for parsing as an ordinary Bison parser, but behaves
7857differently in cases where there is a shift-reduce conflict that has not
7858been resolved by precedence rules (@pxref{Precedence}) or a
7859reduce-reduce conflict.  When a GLR parser encounters such a
7860situation, it
7861effectively @emph{splits} into a several parsers, one for each possible
7862shift or reduction.  These parsers then proceed as usual, consuming
7863tokens in lock-step.  Some of the stacks may encounter other conflicts
7864and split further, with the result that instead of a sequence of states,
7865a Bison GLR parsing stack is what is in effect a tree of states.
7866
7867In effect, each stack represents a guess as to what the proper parse
7868is.  Additional input may indicate that a guess was wrong, in which case
7869the appropriate stack silently disappears.  Otherwise, the semantics
7870actions generated in each stack are saved, rather than being executed
7871immediately.  When a stack disappears, its saved semantic actions never
7872get executed.  When a reduction causes two stacks to become equivalent,
7873their sets of semantic actions are both saved with the state that
7874results from the reduction.  We say that two stacks are equivalent
7875when they both represent the same sequence of states,
7876and each pair of corresponding states represents a
7877grammar symbol that produces the same segment of the input token
7878stream.
7879
7880Whenever the parser makes a transition from having multiple
7881states to having one, it reverts to the normal deterministic parsing
7882algorithm, after resolving and executing the saved-up actions.
7883At this transition, some of the states on the stack will have semantic
7884values that are sets (actually multisets) of possible actions.  The
7885parser tries to pick one of the actions by first finding one whose rule
7886has the highest dynamic precedence, as set by the @samp{%dprec}
7887declaration.  Otherwise, if the alternative actions are not ordered by
7888precedence, but there the same merging function is declared for both
7889rules by the @samp{%merge} declaration,
7890Bison resolves and evaluates both and then calls the merge function on
7891the result.  Otherwise, it reports an ambiguity.
7892
7893It is possible to use a data structure for the GLR parsing tree that
7894permits the processing of any LR(1) grammar in linear time (in the
7895size of the input), any unambiguous (not necessarily
7896LR(1)) grammar in
7897quadratic worst-case time, and any general (possibly ambiguous)
7898context-free grammar in cubic worst-case time.  However, Bison currently
7899uses a simpler data structure that requires time proportional to the
7900length of the input times the maximum number of stacks required for any
7901prefix of the input.  Thus, really ambiguous or nondeterministic
7902grammars can require exponential time and space to process.  Such badly
7903behaving examples, however, are not generally of practical interest.
7904Usually, nondeterminism in a grammar is local---the parser is ``in
7905doubt'' only for a few tokens at a time.  Therefore, the current data
7906structure should generally be adequate.  On LR(1) portions of a
7907grammar, in particular, it is only slightly slower than with the
7908deterministic LR(1) Bison parser.
7909
7910For a more detailed exposition of GLR parsers, @pxref{Bibliography,,Scott
79112000}.
7912
7913@node Memory Management
7914@section Memory Management, and How to Avoid Memory Exhaustion
7915@cindex memory exhaustion
7916@cindex memory management
7917@cindex stack overflow
7918@cindex parser stack overflow
7919@cindex overflow of parser stack
7920
7921The Bison parser stack can run out of memory if too many tokens are shifted and
7922not reduced.  When this happens, the parser function @code{yyparse}
7923calls @code{yyerror} and then returns 2.
7924
7925Because Bison parsers have growing stacks, hitting the upper limit
7926usually results from using a right recursion instead of a left
7927recursion, see @ref{Recursion, ,Recursive Rules}.
7928
7929@vindex YYMAXDEPTH
7930By defining the macro @code{YYMAXDEPTH}, you can control how deep the
7931parser stack can become before memory is exhausted.  Define the
7932macro with a value that is an integer.  This value is the maximum number
7933of tokens that can be shifted (and not reduced) before overflow.
7934
7935The stack space allowed is not necessarily allocated.  If you specify a
7936large value for @code{YYMAXDEPTH}, the parser normally allocates a small
7937stack at first, and then makes it bigger by stages as needed.  This
7938increasing allocation happens automatically and silently.  Therefore,
7939you do not need to make @code{YYMAXDEPTH} painfully small merely to save
7940space for ordinary inputs that do not need much stack.
7941
7942However, do not allow @code{YYMAXDEPTH} to be a value so large that
7943arithmetic overflow could occur when calculating the size of the stack
7944space.  Also, do not allow @code{YYMAXDEPTH} to be less than
7945@code{YYINITDEPTH}.
7946
7947@cindex default stack limit
7948The default value of @code{YYMAXDEPTH}, if you do not define it, is
794910000.
7950
7951@vindex YYINITDEPTH
7952You can control how much stack is allocated initially by defining the
7953macro @code{YYINITDEPTH} to a positive integer.  For the deterministic
7954parser in C, this value must be a compile-time constant
7955unless you are assuming C99 or some other target language or compiler
7956that allows variable-length arrays.  The default is 200.
7957
7958Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
7959
7960@c FIXME: C++ output.
7961Because of semantic differences between C and C++, the deterministic
7962parsers in C produced by Bison cannot grow when compiled
7963by C++ compilers.  In this precise case (compiling a C parser as C++) you are
7964suggested to grow @code{YYINITDEPTH}.  The Bison maintainers hope to fix
7965this deficiency in a future release.
7966
7967@node Error Recovery
7968@chapter Error Recovery
7969@cindex error recovery
7970@cindex recovery from errors
7971
7972It is not usually acceptable to have a program terminate on a syntax
7973error.  For example, a compiler should recover sufficiently to parse the
7974rest of the input file and check it for errors; a calculator should accept
7975another expression.
7976
7977In a simple interactive command parser where each input is one line, it may
7978be sufficient to allow @code{yyparse} to return 1 on error and have the
7979caller ignore the rest of the input line when that happens (and then call
7980@code{yyparse} again).  But this is inadequate for a compiler, because it
7981forgets all the syntactic context leading up to the error.  A syntax error
7982deep within a function in the compiler input should not cause the compiler
7983to treat the following line like the beginning of a source file.
7984
7985@findex error
7986You can define how to recover from a syntax error by writing rules to
7987recognize the special token @code{error}.  This is a terminal symbol that
7988is always defined (you need not declare it) and reserved for error
7989handling.  The Bison parser generates an @code{error} token whenever a
7990syntax error happens; if you have provided a rule to recognize this token
7991in the current context, the parse can continue.
7992
7993For example:
7994
7995@example
7996stmts:
7997  /* empty string */
7998| stmts '\n'
7999| stmts exp '\n'
8000| stmts error '\n'
8001@end example
8002
8003The fourth rule in this example says that an error followed by a newline
8004makes a valid addition to any @code{stmts}.
8005
8006What happens if a syntax error occurs in the middle of an @code{exp}?  The
8007error recovery rule, interpreted strictly, applies to the precise sequence
8008of a @code{stmts}, an @code{error} and a newline.  If an error occurs in
8009the middle of an @code{exp}, there will probably be some additional tokens
8010and subexpressions on the stack after the last @code{stmts}, and there
8011will be tokens to read before the next newline.  So the rule is not
8012applicable in the ordinary way.
8013
8014But Bison can force the situation to fit the rule, by discarding part of
8015the semantic context and part of the input.  First it discards states
8016and objects from the stack until it gets back to a state in which the
8017@code{error} token is acceptable.  (This means that the subexpressions
8018already parsed are discarded, back to the last complete @code{stmts}.)
8019At this point the @code{error} token can be shifted.  Then, if the old
8020lookahead token is not acceptable to be shifted next, the parser reads
8021tokens and discards them until it finds a token which is acceptable.  In
8022this example, Bison reads and discards input until the next newline so
8023that the fourth rule can apply.  Note that discarded symbols are
8024possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
8025Discarded Symbols}, for a means to reclaim this memory.
8026
8027The choice of error rules in the grammar is a choice of strategies for
8028error recovery.  A simple and useful strategy is simply to skip the rest of
8029the current input line or current statement if an error is detected:
8030
8031@example
8032stmt: error ';'  /* On error, skip until ';' is read.  */
8033@end example
8034
8035It is also useful to recover to the matching close-delimiter of an
8036opening-delimiter that has already been parsed.  Otherwise the
8037close-delimiter will probably appear to be unmatched, and generate another,
8038spurious error message:
8039
8040@example
8041primary:
8042  '(' expr ')'
8043| '(' error ')'
8044@dots{}
8045;
8046@end example
8047
8048Error recovery strategies are necessarily guesses.  When they guess wrong,
8049one syntax error often leads to another.  In the above example, the error
8050recovery rule guesses that an error is due to bad input within one
8051@code{stmt}.  Suppose that instead a spurious semicolon is inserted in the
8052middle of a valid @code{stmt}.  After the error recovery rule recovers
8053from the first error, another syntax error will be found straightaway,
8054since the text following the spurious semicolon is also an invalid
8055@code{stmt}.
8056
8057To prevent an outpouring of error messages, the parser will output no error
8058message for another syntax error that happens shortly after the first; only
8059after three consecutive input tokens have been successfully shifted will
8060error messages resume.
8061
8062Note that rules which accept the @code{error} token may have actions, just
8063as any other rules can.
8064
8065@findex yyerrok
8066You can make error messages resume immediately by using the macro
8067@code{yyerrok} in an action.  If you do this in the error rule's action, no
8068error messages will be suppressed.  This macro requires no arguments;
8069@samp{yyerrok;} is a valid C statement.
8070
8071@findex yyclearin
8072The previous lookahead token is reanalyzed immediately after an error.  If
8073this is unacceptable, then the macro @code{yyclearin} may be used to clear
8074this token.  Write the statement @samp{yyclearin;} in the error rule's
8075action.
8076@xref{Action Features, ,Special Features for Use in Actions}.
8077
8078For example, suppose that on a syntax error, an error handling routine is
8079called that advances the input stream to some point where parsing should
8080once again commence.  The next symbol returned by the lexical scanner is
8081probably correct.  The previous lookahead token ought to be discarded
8082with @samp{yyclearin;}.
8083
8084@vindex YYRECOVERING
8085The expression @code{YYRECOVERING ()} yields 1 when the parser
8086is recovering from a syntax error, and 0 otherwise.
8087Syntax error diagnostics are suppressed while recovering from a syntax
8088error.
8089
8090@node Context Dependency
8091@chapter Handling Context Dependencies
8092
8093The Bison paradigm is to parse tokens first, then group them into larger
8094syntactic units.  In many languages, the meaning of a token is affected by
8095its context.  Although this violates the Bison paradigm, certain techniques
8096(known as @dfn{kludges}) may enable you to write Bison parsers for such
8097languages.
8098
8099@menu
8100* Semantic Tokens::   Token parsing can depend on the semantic context.
8101* Lexical Tie-ins::   Token parsing can depend on the syntactic context.
8102* Tie-in Recovery::   Lexical tie-ins have implications for how
8103                        error recovery rules must be written.
8104@end menu
8105
8106(Actually, ``kludge'' means any technique that gets its job done but is
8107neither clean nor robust.)
8108
8109@node Semantic Tokens
8110@section Semantic Info in Token Types
8111
8112The C language has a context dependency: the way an identifier is used
8113depends on what its current meaning is.  For example, consider this:
8114
8115@example
8116foo (x);
8117@end example
8118
8119This looks like a function call statement, but if @code{foo} is a typedef
8120name, then this is actually a declaration of @code{x}.  How can a Bison
8121parser for C decide how to parse this input?
8122
8123The method used in GNU C is to have two different token types,
8124@code{IDENTIFIER} and @code{TYPENAME}.  When @code{yylex} finds an
8125identifier, it looks up the current declaration of the identifier in order
8126to decide which token type to return: @code{TYPENAME} if the identifier is
8127declared as a typedef, @code{IDENTIFIER} otherwise.
8128
8129The grammar rules can then express the context dependency by the choice of
8130token type to recognize.  @code{IDENTIFIER} is accepted as an expression,
8131but @code{TYPENAME} is not.  @code{TYPENAME} can start a declaration, but
8132@code{IDENTIFIER} cannot.  In contexts where the meaning of the identifier
8133is @emph{not} significant, such as in declarations that can shadow a
8134typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
8135accepted---there is one rule for each of the two token types.
8136
8137This technique is simple to use if the decision of which kinds of
8138identifiers to allow is made at a place close to where the identifier is
8139parsed.  But in C this is not always so: C allows a declaration to
8140redeclare a typedef name provided an explicit type has been specified
8141earlier:
8142
8143@example
8144typedef int foo, bar;
8145int baz (void)
8146@group
8147@{
8148  static bar (bar);      /* @r{redeclare @code{bar} as static variable} */
8149  extern foo foo (foo);  /* @r{redeclare @code{foo} as function} */
8150  return foo (bar);
8151@}
8152@end group
8153@end example
8154
8155Unfortunately, the name being declared is separated from the declaration
8156construct itself by a complicated syntactic structure---the ``declarator''.
8157
8158As a result, part of the Bison parser for C needs to be duplicated, with
8159all the nonterminal names changed: once for parsing a declaration in
8160which a typedef name can be redefined, and once for parsing a
8161declaration in which that can't be done.  Here is a part of the
8162duplication, with actions omitted for brevity:
8163
8164@example
8165@group
8166initdcl:
8167  declarator maybeasm '=' init
8168| declarator maybeasm
8169;
8170@end group
8171
8172@group
8173notype_initdcl:
8174  notype_declarator maybeasm '=' init
8175| notype_declarator maybeasm
8176;
8177@end group
8178@end example
8179
8180@noindent
8181Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
8182cannot.  The distinction between @code{declarator} and
8183@code{notype_declarator} is the same sort of thing.
8184
8185There is some similarity between this technique and a lexical tie-in
8186(described next), in that information which alters the lexical analysis is
8187changed during parsing by other parts of the program.  The difference is
8188here the information is global, and is used for other purposes in the
8189program.  A true lexical tie-in has a special-purpose flag controlled by
8190the syntactic context.
8191
8192@node Lexical Tie-ins
8193@section Lexical Tie-ins
8194@cindex lexical tie-in
8195
8196One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
8197which is set by Bison actions, whose purpose is to alter the way tokens are
8198parsed.
8199
8200For example, suppose we have a language vaguely like C, but with a special
8201construct @samp{hex (@var{hex-expr})}.  After the keyword @code{hex} comes
8202an expression in parentheses in which all integers are hexadecimal.  In
8203particular, the token @samp{a1b} must be treated as an integer rather than
8204as an identifier if it appears in that context.  Here is how you can do it:
8205
8206@example
8207@group
8208%@{
8209  int hexflag;
8210  int yylex (void);
8211  void yyerror (char const *);
8212%@}
8213%%
8214@dots{}
8215@end group
8216@group
8217expr:
8218  IDENTIFIER
8219| constant
8220| HEX '('        @{ hexflag = 1; @}
8221    expr ')'     @{ hexflag = 0; $$ = $4; @}
8222| expr '+' expr  @{ $$ = make_sum ($1, $3); @}
8223@dots{}
8224;
8225@end group
8226
8227@group
8228constant:
8229  INTEGER
8230| STRING
8231;
8232@end group
8233@end example
8234
8235@noindent
8236Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
8237it is nonzero, all integers are parsed in hexadecimal, and tokens starting
8238with letters are parsed as integers if possible.
8239
8240The declaration of @code{hexflag} shown in the prologue of the grammar
8241file is needed to make it accessible to the actions (@pxref{Prologue,
8242,The Prologue}).  You must also write the code in @code{yylex} to obey
8243the flag.
8244
8245@node Tie-in Recovery
8246@section Lexical Tie-ins and Error Recovery
8247
8248Lexical tie-ins make strict demands on any error recovery rules you have.
8249@xref{Error Recovery}.
8250
8251The reason for this is that the purpose of an error recovery rule is to
8252abort the parsing of one construct and resume in some larger construct.
8253For example, in C-like languages, a typical error recovery rule is to skip
8254tokens until the next semicolon, and then start a new statement, like this:
8255
8256@example
8257stmt:
8258  expr ';'
8259| IF '(' expr ')' stmt @{ @dots{} @}
8260@dots{}
8261| error ';'  @{ hexflag = 0; @}
8262;
8263@end example
8264
8265If there is a syntax error in the middle of a @samp{hex (@var{expr})}
8266construct, this error rule will apply, and then the action for the
8267completed @samp{hex (@var{expr})} will never run.  So @code{hexflag} would
8268remain set for the entire rest of the input, or until the next @code{hex}
8269keyword, causing identifiers to be misinterpreted as integers.
8270
8271To avoid this problem the error recovery rule itself clears @code{hexflag}.
8272
8273There may also be an error recovery rule that works within expressions.
8274For example, there could be a rule which applies within parentheses
8275and skips to the close-parenthesis:
8276
8277@example
8278@group
8279expr:
8280  @dots{}
8281| '(' expr ')'   @{ $$ = $2; @}
8282| '(' error ')'
8283@dots{}
8284@end group
8285@end example
8286
8287If this rule acts within the @code{hex} construct, it is not going to abort
8288that construct (since it applies to an inner level of parentheses within
8289the construct).  Therefore, it should not clear the flag: the rest of
8290the @code{hex} construct should be parsed with the flag still in effect.
8291
8292What if there is an error recovery rule which might abort out of the
8293@code{hex} construct or might not, depending on circumstances?  There is no
8294way you can write the action to determine whether a @code{hex} construct is
8295being aborted or not.  So if you are using a lexical tie-in, you had better
8296make sure your error recovery rules are not of this kind.  Each rule must
8297be such that you can be sure that it always will, or always won't, have to
8298clear the flag.
8299
8300@c ================================================== Debugging Your Parser
8301
8302@node Debugging
8303@chapter Debugging Your Parser
8304
8305Developing a parser can be a challenge, especially if you don't understand
8306the algorithm (@pxref{Algorithm, ,The Bison Parser Algorithm}).  This
8307chapter explains how understand and debug a parser.
8308
8309The first sections focus on the static part of the parser: its structure.
8310They explain how to generate and read the detailed description of the
8311automaton.  There are several formats available:
8312@itemize @minus
8313@item
8314as text, see @ref{Understanding, , Understanding Your Parser};
8315
8316@item
8317as a graph, see @ref{Graphviz,, Visualizing Your Parser};
8318
8319@item
8320or as a markup report that can be turned, for instance, into HTML, see
8321@ref{Xml,, Visualizing your parser in multiple formats}.
8322@end itemize
8323
8324The last section focuses on the dynamic part of the parser: how to enable
8325and understand the parser run-time traces (@pxref{Tracing, ,Tracing Your
8326Parser}).
8327
8328@menu
8329* Understanding::     Understanding the structure of your parser.
8330* Graphviz::          Getting a visual representation of the parser.
8331* Xml::               Getting a markup representation of the parser.
8332* Tracing::           Tracing the execution of your parser.
8333@end menu
8334
8335@node Understanding
8336@section Understanding Your Parser
8337
8338As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
8339Bison parsers are @dfn{shift/reduce automata}.  In some cases (much more
8340frequent than one would hope), looking at this automaton is required to
8341tune or simply fix a parser.
8342
8343The textual file is generated when the options @option{--report} or
8344@option{--verbose} are specified, see @ref{Invocation, , Invoking
8345Bison}.  Its name is made by removing @samp{.tab.c} or @samp{.c} from
8346the parser implementation file name, and adding @samp{.output}
8347instead.  Therefore, if the grammar file is @file{foo.y}, then the
8348parser implementation file is called @file{foo.tab.c} by default.  As
8349a consequence, the verbose output file is called @file{foo.output}.
8350
8351The following grammar file, @file{calc.y}, will be used in the sequel:
8352
8353@example
8354%token NUM STR
8355@group
8356%left '+' '-'
8357%left '*'
8358@end group
8359%%
8360@group
8361exp:
8362  exp '+' exp
8363| exp '-' exp
8364| exp '*' exp
8365| exp '/' exp
8366| NUM
8367;
8368@end group
8369useless: STR;
8370%%
8371@end example
8372
8373@command{bison} reports:
8374
8375@example
8376calc.y: warning: 1 nonterminal useless in grammar
8377calc.y: warning: 1 rule useless in grammar
8378calc.y:12.1-7: warning: nonterminal useless in grammar: useless
8379calc.y:12.10-12: warning: rule useless in grammar: useless: STR
8380calc.y: conflicts: 7 shift/reduce
8381@end example
8382
8383When given @option{--report=state}, in addition to @file{calc.tab.c}, it
8384creates a file @file{calc.output} with contents detailed below.  The
8385order of the output and the exact presentation might vary, but the
8386interpretation is the same.
8387
8388@noindent
8389@cindex token, useless
8390@cindex useless token
8391@cindex nonterminal, useless
8392@cindex useless nonterminal
8393@cindex rule, useless
8394@cindex useless rule
8395The first section reports useless tokens, nonterminals and rules.  Useless
8396nonterminals and rules are removed in order to produce a smaller parser, but
8397useless tokens are preserved, since they might be used by the scanner (note
8398the difference between ``useless'' and ``unused'' below):
8399
8400@example
8401Nonterminals useless in grammar
8402   useless
8403
8404Terminals unused in grammar
8405   STR
8406
8407Rules useless in grammar
8408    6 useless: STR
8409@end example
8410
8411@noindent
8412The next section lists states that still have conflicts.
8413
8414@example
8415State 8 conflicts: 1 shift/reduce
8416State 9 conflicts: 1 shift/reduce
8417State 10 conflicts: 1 shift/reduce
8418State 11 conflicts: 4 shift/reduce
8419@end example
8420
8421@noindent
8422Then Bison reproduces the exact grammar it used:
8423
8424@example
8425Grammar
8426
8427    0 $accept: exp $end
8428
8429    1 exp: exp '+' exp
8430    2    | exp '-' exp
8431    3    | exp '*' exp
8432    4    | exp '/' exp
8433    5    | NUM
8434@end example
8435
8436@noindent
8437and reports the uses of the symbols:
8438
8439@example
8440@group
8441Terminals, with rules where they appear
8442
8443$end (0) 0
8444'*' (42) 3
8445'+' (43) 1
8446'-' (45) 2
8447'/' (47) 4
8448error (256)
8449NUM (258) 5
8450STR (259)
8451@end group
8452
8453@group
8454Nonterminals, with rules where they appear
8455
8456$accept (9)
8457    on left: 0
8458exp (10)
8459    on left: 1 2 3 4 5, on right: 0 1 2 3 4
8460@end group
8461@end example
8462
8463@noindent
8464@cindex item
8465@cindex pointed rule
8466@cindex rule, pointed
8467Bison then proceeds onto the automaton itself, describing each state
8468with its set of @dfn{items}, also known as @dfn{pointed rules}.  Each
8469item is a production rule together with a point (@samp{.}) marking
8470the location of the input cursor.
8471
8472@example
8473State 0
8474
8475    0 $accept: . exp $end
8476
8477    NUM  shift, and go to state 1
8478
8479    exp  go to state 2
8480@end example
8481
8482This reads as follows: ``state 0 corresponds to being at the very
8483beginning of the parsing, in the initial rule, right before the start
8484symbol (here, @code{exp}).  When the parser returns to this state right
8485after having reduced a rule that produced an @code{exp}, the control
8486flow jumps to state 2.  If there is no such transition on a nonterminal
8487symbol, and the lookahead is a @code{NUM}, then this token is shifted onto
8488the parse stack, and the control flow jumps to state 1.  Any other
8489lookahead triggers a syntax error.''
8490
8491@cindex core, item set
8492@cindex item set core
8493@cindex kernel, item set
8494@cindex item set core
8495Even though the only active rule in state 0 seems to be rule 0, the
8496report lists @code{NUM} as a lookahead token because @code{NUM} can be
8497at the beginning of any rule deriving an @code{exp}.  By default Bison
8498reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
8499you want to see more detail you can invoke @command{bison} with
8500@option{--report=itemset} to list the derived items as well:
8501
8502@example
8503State 0
8504
8505    0 $accept: . exp $end
8506    1 exp: . exp '+' exp
8507    2    | . exp '-' exp
8508    3    | . exp '*' exp
8509    4    | . exp '/' exp
8510    5    | . NUM
8511
8512    NUM  shift, and go to state 1
8513
8514    exp  go to state 2
8515@end example
8516
8517@noindent
8518In the state 1@dots{}
8519
8520@example
8521State 1
8522
8523    5 exp: NUM .
8524
8525    $default  reduce using rule 5 (exp)
8526@end example
8527
8528@noindent
8529the rule 5, @samp{exp: NUM;}, is completed.  Whatever the lookahead token
8530(@samp{$default}), the parser will reduce it.  If it was coming from
8531State 0, then, after this reduction it will return to state 0, and will
8532jump to state 2 (@samp{exp: go to state 2}).
8533
8534@example
8535State 2
8536
8537    0 $accept: exp . $end
8538    1 exp: exp . '+' exp
8539    2    | exp . '-' exp
8540    3    | exp . '*' exp
8541    4    | exp . '/' exp
8542
8543    $end  shift, and go to state 3
8544    '+'   shift, and go to state 4
8545    '-'   shift, and go to state 5
8546    '*'   shift, and go to state 6
8547    '/'   shift, and go to state 7
8548@end example
8549
8550@noindent
8551In state 2, the automaton can only shift a symbol.  For instance,
8552because of the item @samp{exp: exp . '+' exp}, if the lookahead is
8553@samp{+} it is shifted onto the parse stack, and the automaton
8554jumps to state 4, corresponding to the item @samp{exp: exp '+' . exp}.
8555Since there is no default action, any lookahead not listed triggers a syntax
8556error.
8557
8558@cindex accepting state
8559The state 3 is named the @dfn{final state}, or the @dfn{accepting
8560state}:
8561
8562@example
8563State 3
8564
8565    0 $accept: exp $end .
8566
8567    $default  accept
8568@end example
8569
8570@noindent
8571the initial rule is completed (the start symbol and the end-of-input were
8572read), the parsing exits successfully.
8573
8574The interpretation of states 4 to 7 is straightforward, and is left to
8575the reader.
8576
8577@example
8578State 4
8579
8580    1 exp: exp '+' . exp
8581
8582    NUM  shift, and go to state 1
8583
8584    exp  go to state 8
8585
8586
8587State 5
8588
8589    2 exp: exp '-' . exp
8590
8591    NUM  shift, and go to state 1
8592
8593    exp  go to state 9
8594
8595
8596State 6
8597
8598    3 exp: exp '*' . exp
8599
8600    NUM  shift, and go to state 1
8601
8602    exp  go to state 10
8603
8604
8605State 7
8606
8607    4 exp: exp '/' . exp
8608
8609    NUM  shift, and go to state 1
8610
8611    exp  go to state 11
8612@end example
8613
8614As was announced in beginning of the report, @samp{State 8 conflicts:
86151 shift/reduce}:
8616
8617@example
8618State 8
8619
8620    1 exp: exp . '+' exp
8621    1    | exp '+' exp .
8622    2    | exp . '-' exp
8623    3    | exp . '*' exp
8624    4    | exp . '/' exp
8625
8626    '*'  shift, and go to state 6
8627    '/'  shift, and go to state 7
8628
8629    '/'       [reduce using rule 1 (exp)]
8630    $default  reduce using rule 1 (exp)
8631@end example
8632
8633Indeed, there are two actions associated to the lookahead @samp{/}:
8634either shifting (and going to state 7), or reducing rule 1.  The
8635conflict means that either the grammar is ambiguous, or the parser lacks
8636information to make the right decision.  Indeed the grammar is
8637ambiguous, as, since we did not specify the precedence of @samp{/}, the
8638sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
8639NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
8640NUM}, which corresponds to reducing rule 1.
8641
8642Because in deterministic parsing a single decision can be made, Bison
8643arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
8644Shift/Reduce Conflicts}.  Discarded actions are reported between
8645square brackets.
8646
8647Note that all the previous states had a single possible action: either
8648shifting the next token and going to the corresponding state, or
8649reducing a single rule.  In the other cases, i.e., when shifting
8650@emph{and} reducing is possible or when @emph{several} reductions are
8651possible, the lookahead is required to select the action.  State 8 is
8652one such state: if the lookahead is @samp{*} or @samp{/} then the action
8653is shifting, otherwise the action is reducing rule 1.  In other words,
8654the first two items, corresponding to rule 1, are not eligible when the
8655lookahead token is @samp{*}, since we specified that @samp{*} has higher
8656precedence than @samp{+}.  More generally, some items are eligible only
8657with some set of possible lookahead tokens.  When run with
8658@option{--report=lookahead}, Bison specifies these lookahead tokens:
8659
8660@example
8661State 8
8662
8663    1 exp: exp . '+' exp
8664    1    | exp '+' exp .  [$end, '+', '-', '/']
8665    2    | exp . '-' exp
8666    3    | exp . '*' exp
8667    4    | exp . '/' exp
8668
8669    '*'  shift, and go to state 6
8670    '/'  shift, and go to state 7
8671
8672    '/'       [reduce using rule 1 (exp)]
8673    $default  reduce using rule 1 (exp)
8674@end example
8675
8676Note however that while @samp{NUM + NUM / NUM} is ambiguous (which results in
8677the conflicts on @samp{/}), @samp{NUM + NUM * NUM} is not: the conflict was
8678solved thanks to associativity and precedence directives.  If invoked with
8679@option{--report=solved}, Bison includes information about the solved
8680conflicts in the report:
8681
8682@example
8683Conflict between rule 1 and token '+' resolved as reduce (%left '+').
8684Conflict between rule 1 and token '-' resolved as reduce (%left '-').
8685Conflict between rule 1 and token '*' resolved as shift ('+' < '*').
8686@end example
8687
8688
8689The remaining states are similar:
8690
8691@example
8692@group
8693State 9
8694
8695    1 exp: exp . '+' exp
8696    2    | exp . '-' exp
8697    2    | exp '-' exp .
8698    3    | exp . '*' exp
8699    4    | exp . '/' exp
8700
8701    '*'  shift, and go to state 6
8702    '/'  shift, and go to state 7
8703
8704    '/'       [reduce using rule 2 (exp)]
8705    $default  reduce using rule 2 (exp)
8706@end group
8707
8708@group
8709State 10
8710
8711    1 exp: exp . '+' exp
8712    2    | exp . '-' exp
8713    3    | exp . '*' exp
8714    3    | exp '*' exp .
8715    4    | exp . '/' exp
8716
8717    '/'  shift, and go to state 7
8718
8719    '/'       [reduce using rule 3 (exp)]
8720    $default  reduce using rule 3 (exp)
8721@end group
8722
8723@group
8724State 11
8725
8726    1 exp: exp . '+' exp
8727    2    | exp . '-' exp
8728    3    | exp . '*' exp
8729    4    | exp . '/' exp
8730    4    | exp '/' exp .
8731
8732    '+'  shift, and go to state 4
8733    '-'  shift, and go to state 5
8734    '*'  shift, and go to state 6
8735    '/'  shift, and go to state 7
8736
8737    '+'       [reduce using rule 4 (exp)]
8738    '-'       [reduce using rule 4 (exp)]
8739    '*'       [reduce using rule 4 (exp)]
8740    '/'       [reduce using rule 4 (exp)]
8741    $default  reduce using rule 4 (exp)
8742@end group
8743@end example
8744
8745@noindent
8746Observe that state 11 contains conflicts not only due to the lack of
8747precedence of @samp{/} with respect to @samp{+}, @samp{-}, and @samp{*}, but
8748also because the associativity of @samp{/} is not specified.
8749
8750Bison may also produce an HTML version of this output, via an XML file and
8751XSLT processing (@pxref{Xml,,Visualizing your parser in multiple formats}).
8752
8753@c ================================================= Graphical Representation
8754
8755@node Graphviz
8756@section Visualizing Your Parser
8757@cindex dot
8758
8759As another means to gain better understanding of the shift/reduce
8760automaton corresponding to the Bison parser, a DOT file can be generated. Note
8761that debugging a real grammar with this is tedious at best, and impractical
8762most of the times, because the generated files are huge (the generation of
8763a PDF or PNG file from it will take very long, and more often than not it will
8764fail due to memory exhaustion). This option was rather designed for beginners,
8765to help them understand LR parsers.
8766
8767This file is generated when the @option{--graph} option is specified
8768(@pxref{Invocation, , Invoking Bison}).  Its name is made by removing
8769@samp{.tab.c} or @samp{.c} from the parser implementation file name, and
8770adding @samp{.dot} instead.  If the grammar file is @file{foo.y}, the
8771Graphviz output file is called @file{foo.dot}.  A DOT file may also be
8772produced via an XML file and XSLT processing (@pxref{Xml,,Visualizing your
8773parser in multiple formats}).
8774
8775
8776The following grammar file, @file{rr.y}, will be used in the sequel:
8777
8778@example
8779%%
8780@group
8781exp: a ";" | b ".";
8782a: "0";
8783b: "0";
8784@end group
8785@end example
8786
8787The graphical output
8788@ifnotinfo
8789(see @ref{fig:graph})
8790@end ifnotinfo
8791is very similar to the textual one, and as such it is easier understood by
8792making direct comparisons between them.  @xref{Debugging, , Debugging Your
8793Parser}, for a detailled analysis of the textual report.
8794
8795@ifnotinfo
8796@float Figure,fig:graph
8797@image{figs/example, 430pt}
8798@caption{A graphical rendering of the parser.}
8799@end float
8800@end ifnotinfo
8801
8802@subheading Graphical Representation of States
8803
8804The items (pointed rules) for each state are grouped together in graph nodes.
8805Their numbering is the same as in the verbose file. See the following points,
8806about transitions, for examples
8807
8808When invoked with @option{--report=lookaheads}, the lookahead tokens, when
8809needed, are shown next to the relevant rule between square brackets as a
8810comma separated list. This is the case in the figure for the representation of
8811reductions, below.
8812
8813@sp 1
8814
8815The transitions are represented as directed edges between the current and
8816the target states.
8817
8818@subheading Graphical Representation of Shifts
8819
8820Shifts are shown as solid arrows, labelled with the lookahead token for that
8821shift. The following describes a reduction in the @file{rr.output} file:
8822
8823@example
8824@group
8825State 3
8826
8827    1 exp: a . ";"
8828
8829    ";"  shift, and go to state 6
8830@end group
8831@end example
8832
8833A Graphviz rendering of this portion of the graph could be:
8834
8835@center @image{figs/example-shift, 100pt}
8836
8837@subheading Graphical Representation of Reductions
8838
8839Reductions are shown as solid arrows, leading to a diamond-shaped node
8840bearing the number of the reduction rule. The arrow is labelled with the
8841appropriate comma separated lookahead tokens. If the reduction is the default
8842action for the given state, there is no such label.
8843
8844This is how reductions are represented in the verbose file @file{rr.output}:
8845@example
8846State 1
8847
8848    3 a: "0" .  [";"]
8849    4 b: "0" .  ["."]
8850
8851    "."       reduce using rule 4 (b)
8852    $default  reduce using rule 3 (a)
8853@end example
8854
8855A Graphviz rendering of this portion of the graph could be:
8856
8857@center @image{figs/example-reduce, 120pt}
8858
8859When unresolved conflicts are present, because in deterministic parsing
8860a single decision can be made, Bison can arbitrarily choose to disable a
8861reduction, see @ref{Shift/Reduce, , Shift/Reduce Conflicts}.  Discarded actions
8862are distinguished by a red filling color on these nodes, just like how they are
8863reported between square brackets in the verbose file.
8864
8865The reduction corresponding to the rule number 0 is the acceptation
8866state. It is shown as a blue diamond, labelled ``Acc''.
8867
8868@subheading Graphical representation of go tos
8869
8870The @samp{go to} jump transitions are represented as dotted lines bearing
8871the name of the rule being jumped to.
8872
8873@c ================================================= XML
8874
8875@node Xml
8876@section Visualizing your parser in multiple formats
8877@cindex xml
8878
8879Bison supports two major report formats: textual output
8880(@pxref{Understanding, ,Understanding Your Parser}) when invoked
8881with option @option{--verbose}, and DOT
8882(@pxref{Graphviz,, Visualizing Your Parser}) when invoked with
8883option @option{--graph}. However,
8884another alternative is to output an XML file that may then be, with
8885@command{xsltproc}, rendered as either a raw text format equivalent to the
8886verbose file, or as an HTML version of the same file, with clickable
8887transitions, or even as a DOT. The @file{.output} and DOT files obtained via
8888XSLT have no difference whatsoever with those obtained by invoking
8889@command{bison} with options @option{--verbose} or @option{--graph}.
8890
8891The XML file is generated when the options @option{-x} or
8892@option{--xml[=FILE]} are specified, see @ref{Invocation,,Invoking Bison}.
8893If not specified, its name is made by removing @samp{.tab.c} or @samp{.c}
8894from the parser implementation file name, and adding @samp{.xml} instead.
8895For instance, if the grammar file is @file{foo.y}, the default XML output
8896file is @file{foo.xml}.
8897
8898Bison ships with a @file{data/xslt} directory, containing XSL Transformation
8899files to apply to the XML file. Their names are non-ambiguous:
8900
8901@table @file
8902@item xml2dot.xsl
8903Used to output a copy of the DOT visualization of the automaton.
8904@item xml2text.xsl
8905Used to output a copy of the @samp{.output} file.
8906@item xml2xhtml.xsl
8907Used to output an xhtml enhancement of the @samp{.output} file.
8908@end table
8909
8910Sample usage (requires @command{xsltproc}):
8911@example
8912$ bison -x gr.y
8913@group
8914$ bison --print-datadir
8915/usr/local/share/bison
8916@end group
8917$ xsltproc /usr/local/share/bison/xslt/xml2xhtml.xsl gr.xml >gr.html
8918@end example
8919
8920@c ================================================= Tracing
8921
8922@node Tracing
8923@section Tracing Your Parser
8924@findex yydebug
8925@cindex debugging
8926@cindex tracing the parser
8927
8928When a Bison grammar compiles properly but parses ``incorrectly'', the
8929@code{yydebug} parser-trace feature helps figuring out why.
8930
8931@menu
8932* Enabling Traces::    Activating run-time trace support
8933* Mfcalc Traces::      Extending @code{mfcalc} to support traces
8934* The YYPRINT Macro::  Obsolete interface for semantic value reports
8935@end menu
8936
8937@node Enabling Traces
8938@subsection  Enabling Traces
8939There are several means to enable compilation of trace facilities:
8940
8941@table @asis
8942@item the macro @code{YYDEBUG}
8943@findex YYDEBUG
8944Define the macro @code{YYDEBUG} to a nonzero value when you compile the
8945parser.  This is compliant with POSIX Yacc.  You could use
8946@samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
8947YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
8948Prologue}).
8949
8950If the @code{%define} variable @code{api.prefix} is used (@pxref{Multiple
8951Parsers, ,Multiple Parsers in the Same Program}), for instance @samp{%define
8952api.prefix x}, then if @code{CDEBUG} is defined, its value controls the
8953tracing feature (enabled if and only if nonzero); otherwise tracing is
8954enabled if and only if @code{YYDEBUG} is nonzero.
8955
8956@item the option @option{-t} (POSIX Yacc compliant)
8957@itemx the option @option{--debug} (Bison extension)
8958Use the @samp{-t} option when you run Bison (@pxref{Invocation, ,Invoking
8959Bison}).  With @samp{%define api.prefix c}, it defines @code{CDEBUG} to 1,
8960otherwise it defines @code{YYDEBUG} to 1.
8961
8962@item the directive @samp{%debug}
8963@findex %debug
8964Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison Declaration
8965Summary}).  This is a Bison extension, especially useful for languages that
8966don't use a preprocessor.  Unless POSIX and Yacc portability matter to you,
8967this is the preferred solution.
8968@end table
8969
8970We suggest that you always enable the debug option so that debugging is
8971always possible.
8972
8973@findex YYFPRINTF
8974The trace facility outputs messages with macro calls of the form
8975@code{YYFPRINTF (stderr, @var{format}, @var{args})} where
8976@var{format} and @var{args} are the usual @code{printf} format and variadic
8977arguments.  If you define @code{YYDEBUG} to a nonzero value but do not
8978define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
8979and @code{YYFPRINTF} is defined to @code{fprintf}.
8980
8981Once you have compiled the program with trace facilities, the way to
8982request a trace is to store a nonzero value in the variable @code{yydebug}.
8983You can do this by making the C code do it (in @code{main}, perhaps), or
8984you can alter the value with a C debugger.
8985
8986Each step taken by the parser when @code{yydebug} is nonzero produces a
8987line or two of trace information, written on @code{stderr}.  The trace
8988messages tell you these things:
8989
8990@itemize @bullet
8991@item
8992Each time the parser calls @code{yylex}, what kind of token was read.
8993
8994@item
8995Each time a token is shifted, the depth and complete contents of the
8996state stack (@pxref{Parser States}).
8997
8998@item
8999Each time a rule is reduced, which rule it is, and the complete contents
9000of the state stack afterward.
9001@end itemize
9002
9003To make sense of this information, it helps to refer to the automaton
9004description file (@pxref{Understanding, ,Understanding Your Parser}).
9005This file shows the meaning of each state in terms of
9006positions in various rules, and also what each state will do with each
9007possible input token.  As you read the successive trace messages, you
9008can see that the parser is functioning according to its specification in
9009the listing file.  Eventually you will arrive at the place where
9010something undesirable happens, and you will see which parts of the
9011grammar are to blame.
9012
9013The parser implementation file is a C/C++/Java program and you can use
9014debuggers on it, but it's not easy to interpret what it is doing.  The
9015parser function is a finite-state machine interpreter, and aside from
9016the actions it executes the same code over and over.  Only the values
9017of variables show where in the grammar it is working.
9018
9019@node Mfcalc Traces
9020@subsection Enabling Debug Traces for @code{mfcalc}
9021
9022The debugging information normally gives the token type of each token read,
9023but not its semantic value.  The @code{%printer} directive allows specify
9024how semantic values are reported, see @ref{Printer Decl, , Printing
9025Semantic Values}.  For backward compatibility, Yacc like C parsers may also
9026use the @code{YYPRINT} (@pxref{The YYPRINT Macro, , The @code{YYPRINT}
9027Macro}), but its use is discouraged.
9028
9029As a demonstration of @code{%printer}, consider the multi-function
9030calculator, @code{mfcalc} (@pxref{Multi-function Calc}).  To enable run-time
9031traces, and semantic value reports, insert the following directives in its
9032prologue:
9033
9034@comment file: mfcalc.y: 2
9035@example
9036/* Generate the parser description file.  */
9037%verbose
9038/* Enable run-time traces (yydebug).  */
9039%define parse.trace
9040
9041/* Formatting semantic values.  */
9042%printer @{ fprintf (yyoutput, "%s", $$->name); @} VAR;
9043%printer @{ fprintf (yyoutput, "%s()", $$->name); @} FNCT;
9044%printer @{ fprintf (yyoutput, "%g", $$); @} <val>;
9045@end example
9046
9047The @code{%define} directive instructs Bison to generate run-time trace
9048support.  Then, activation of these traces is controlled at run-time by the
9049@code{yydebug} variable, which is disabled by default.  Because these traces
9050will refer to the ``states'' of the parser, it is helpful to ask for the
9051creation of a description of that parser; this is the purpose of (admittedly
9052ill-named) @code{%verbose} directive.
9053
9054The set of @code{%printer} directives demonstrates how to format the
9055semantic value in the traces.  Note that the specification can be done
9056either on the symbol type (e.g., @code{VAR} or @code{FNCT}), or on the type
9057tag: since @code{<val>} is the type for both @code{NUM} and @code{exp}, this
9058printer will be used for them.
9059
9060Here is a sample of the information provided by run-time traces.  The traces
9061are sent onto standard error.
9062
9063@example
9064$ @kbd{echo 'sin(1-1)' | ./mfcalc -p}
9065Starting parse
9066Entering state 0
9067Reducing stack by rule 1 (line 34):
9068-> $$ = nterm input ()
9069Stack now 0
9070Entering state 1
9071@end example
9072
9073@noindent
9074This first batch shows a specific feature of this grammar: the first rule
9075(which is in line 34 of @file{mfcalc.y} can be reduced without even having
9076to look for the first token.  The resulting left-hand symbol (@code{$$}) is
9077a valueless (@samp{()}) @code{input} non terminal (@code{nterm}).
9078
9079Then the parser calls the scanner.
9080@example
9081Reading a token: Next token is token FNCT (sin())
9082Shifting token FNCT (sin())
9083Entering state 6
9084@end example
9085
9086@noindent
9087That token (@code{token}) is a function (@code{FNCT}) whose value is
9088@samp{sin} as formatted per our @code{%printer} specification: @samp{sin()}.
9089The parser stores (@code{Shifting}) that token, and others, until it can do
9090something about it.
9091
9092@example
9093Reading a token: Next token is token '(' ()
9094Shifting token '(' ()
9095Entering state 14
9096Reading a token: Next token is token NUM (1.000000)
9097Shifting token NUM (1.000000)
9098Entering state 4
9099Reducing stack by rule 6 (line 44):
9100   $1 = token NUM (1.000000)
9101-> $$ = nterm exp (1.000000)
9102Stack now 0 1 6 14
9103Entering state 24
9104@end example
9105
9106@noindent
9107The previous reduction demonstrates the @code{%printer} directive for
9108@code{<val>}: both the token @code{NUM} and the resulting nonterminal
9109@code{exp} have @samp{1} as value.
9110
9111@example
9112Reading a token: Next token is token '-' ()
9113Shifting token '-' ()
9114Entering state 17
9115Reading a token: Next token is token NUM (1.000000)
9116Shifting token NUM (1.000000)
9117Entering state 4
9118Reducing stack by rule 6 (line 44):
9119   $1 = token NUM (1.000000)
9120-> $$ = nterm exp (1.000000)
9121Stack now 0 1 6 14 24 17
9122Entering state 26
9123Reading a token: Next token is token ')' ()
9124Reducing stack by rule 11 (line 49):
9125   $1 = nterm exp (1.000000)
9126   $2 = token '-' ()
9127   $3 = nterm exp (1.000000)
9128-> $$ = nterm exp (0.000000)
9129Stack now 0 1 6 14
9130Entering state 24
9131@end example
9132
9133@noindent
9134The rule for the subtraction was just reduced.  The parser is about to
9135discover the end of the call to @code{sin}.
9136
9137@example
9138Next token is token ')' ()
9139Shifting token ')' ()
9140Entering state 31
9141Reducing stack by rule 9 (line 47):
9142   $1 = token FNCT (sin())
9143   $2 = token '(' ()
9144   $3 = nterm exp (0.000000)
9145   $4 = token ')' ()
9146-> $$ = nterm exp (0.000000)
9147Stack now 0 1
9148Entering state 11
9149@end example
9150
9151@noindent
9152Finally, the end-of-line allow the parser to complete the computation, and
9153display its result.
9154
9155@example
9156Reading a token: Next token is token '\n' ()
9157Shifting token '\n' ()
9158Entering state 22
9159Reducing stack by rule 4 (line 40):
9160   $1 = nterm exp (0.000000)
9161   $2 = token '\n' ()
9162@result{} 0
9163-> $$ = nterm line ()
9164Stack now 0 1
9165Entering state 10
9166Reducing stack by rule 2 (line 35):
9167   $1 = nterm input ()
9168   $2 = nterm line ()
9169-> $$ = nterm input ()
9170Stack now 0
9171Entering state 1
9172@end example
9173
9174The parser has returned into state 1, in which it is waiting for the next
9175expression to evaluate, or for the end-of-file token, which causes the
9176completion of the parsing.
9177
9178@example
9179Reading a token: Now at end of input.
9180Shifting token $end ()
9181Entering state 2
9182Stack now 0 1 2
9183Cleanup: popping token $end ()
9184Cleanup: popping nterm input ()
9185@end example
9186
9187
9188@node The YYPRINT Macro
9189@subsection The @code{YYPRINT} Macro
9190
9191@findex YYPRINT
9192Before @code{%printer} support, semantic values could be displayed using the
9193@code{YYPRINT} macro, which works only for terminal symbols and only with
9194the @file{yacc.c} skeleton.
9195
9196@deffn {Macro} YYPRINT (@var{stream}, @var{token}, @var{value});
9197@findex YYPRINT
9198If you define @code{YYPRINT}, it should take three arguments.  The parser
9199will pass a standard I/O stream, the numeric code for the token type, and
9200the token value (from @code{yylval}).
9201
9202For @file{yacc.c} only.  Obsoleted by @code{%printer}.
9203@end deffn
9204
9205Here is an example of @code{YYPRINT} suitable for the multi-function
9206calculator (@pxref{Mfcalc Declarations, ,Declarations for @code{mfcalc}}):
9207
9208@example
9209%@{
9210  static void print_token_value (FILE *, int, YYSTYPE);
9211  #define YYPRINT(File, Type, Value)            \
9212    print_token_value (File, Type, Value)
9213%@}
9214
9215@dots{} %% @dots{} %% @dots{}
9216
9217static void
9218print_token_value (FILE *file, int type, YYSTYPE value)
9219@{
9220  if (type == VAR)
9221    fprintf (file, "%s", value.tptr->name);
9222  else if (type == NUM)
9223    fprintf (file, "%d", value.val);
9224@}
9225@end example
9226
9227@c ================================================= Invoking Bison
9228
9229@node Invocation
9230@chapter Invoking Bison
9231@cindex invoking Bison
9232@cindex Bison invocation
9233@cindex options for invoking Bison
9234
9235The usual way to invoke Bison is as follows:
9236
9237@example
9238bison @var{infile}
9239@end example
9240
9241Here @var{infile} is the grammar file name, which usually ends in
9242@samp{.y}.  The parser implementation file's name is made by replacing
9243the @samp{.y} with @samp{.tab.c} and removing any leading directory.
9244Thus, the @samp{bison foo.y} file name yields @file{foo.tab.c}, and
9245the @samp{bison hack/foo.y} file name yields @file{foo.tab.c}.  It's
9246also possible, in case you are writing C++ code instead of C in your
9247grammar file, to name it @file{foo.ypp} or @file{foo.y++}.  Then, the
9248output files will take an extension like the given one as input
9249(respectively @file{foo.tab.cpp} and @file{foo.tab.c++}).  This
9250feature takes effect with all options that manipulate file names like
9251@samp{-o} or @samp{-d}.
9252
9253For example :
9254
9255@example
9256bison -d @var{infile.yxx}
9257@end example
9258@noindent
9259will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
9260
9261@example
9262bison -d -o @var{output.c++} @var{infile.y}
9263@end example
9264@noindent
9265will produce @file{output.c++} and @file{outfile.h++}.
9266
9267For compatibility with POSIX, the standard Bison
9268distribution also contains a shell script called @command{yacc} that
9269invokes Bison with the @option{-y} option.
9270
9271@menu
9272* Bison Options::     All the options described in detail,
9273                        in alphabetical order by short options.
9274* Option Cross Key::  Alphabetical list of long options.
9275* Yacc Library::      Yacc-compatible @code{yylex} and @code{main}.
9276@end menu
9277
9278@node Bison Options
9279@section Bison Options
9280
9281Bison supports both traditional single-letter options and mnemonic long
9282option names.  Long option names are indicated with @samp{--} instead of
9283@samp{-}.  Abbreviations for option names are allowed as long as they
9284are unique.  When a long option takes an argument, like
9285@samp{--file-prefix}, connect the option name and the argument with
9286@samp{=}.
9287
9288Here is a list of options that can be used with Bison, alphabetized by
9289short option.  It is followed by a cross key alphabetized by long
9290option.
9291
9292@c Please, keep this ordered as in `bison --help'.
9293@noindent
9294Operations modes:
9295@table @option
9296@item -h
9297@itemx --help
9298Print a summary of the command-line options to Bison and exit.
9299
9300@item -V
9301@itemx --version
9302Print the version number of Bison and exit.
9303
9304@item --print-localedir
9305Print the name of the directory containing locale-dependent data.
9306
9307@item --print-datadir
9308Print the name of the directory containing skeletons and XSLT.
9309
9310@item -y
9311@itemx --yacc
9312Act more like the traditional Yacc command.  This can cause different
9313diagnostics to be generated, and may change behavior in other minor
9314ways.  Most importantly, imitate Yacc's output file name conventions,
9315so that the parser implementation file is called @file{y.tab.c}, and
9316the other outputs are called @file{y.output} and @file{y.tab.h}.
9317Also, if generating a deterministic parser in C, generate
9318@code{#define} statements in addition to an @code{enum} to associate
9319token numbers with token names.  Thus, the following shell script can
9320substitute for Yacc, and the Bison distribution contains such a script
9321for compatibility with POSIX:
9322
9323@example
9324#! /bin/sh
9325bison -y "$@@"
9326@end example
9327
9328The @option{-y}/@option{--yacc} option is intended for use with
9329traditional Yacc grammars.  If your grammar uses a Bison extension
9330like @samp{%glr-parser}, Bison might not be Yacc-compatible even if
9331this option is specified.
9332
9333@item -W [@var{category}]
9334@itemx --warnings[=@var{category}]
9335Output warnings falling in @var{category}.  @var{category} can be one
9336of:
9337@table @code
9338@item midrule-values
9339Warn about mid-rule values that are set but not used within any of the actions
9340of the parent rule.
9341For example, warn about unused @code{$2} in:
9342
9343@example
9344exp: '1' @{ $$ = 1; @} '+' exp @{ $$ = $1 + $4; @};
9345@end example
9346
9347Also warn about mid-rule values that are used but not set.
9348For example, warn about unset @code{$$} in the mid-rule action in:
9349
9350@example
9351exp: '1' @{ $1 = 1; @} '+' exp @{ $$ = $2 + $4; @};
9352@end example
9353
9354These warnings are not enabled by default since they sometimes prove to
9355be false alarms in existing grammars employing the Yacc constructs
9356@code{$0} or @code{$-@var{n}} (where @var{n} is some positive integer).
9357
9358@item yacc
9359Incompatibilities with POSIX Yacc.
9360
9361@item conflicts-sr
9362@itemx conflicts-rr
9363S/R and R/R conflicts.  These warnings are enabled by default.  However, if
9364the @code{%expect} or @code{%expect-rr} directive is specified, an
9365unexpected number of conflicts is an error, and an expected number of
9366conflicts is not reported, so @option{-W} and @option{--warning} then have
9367no effect on the conflict report.
9368
9369@item other
9370All warnings not categorized above.  These warnings are enabled by default.
9371
9372This category is provided merely for the sake of completeness.  Future
9373releases of Bison may move warnings from this category to new, more specific
9374categories.
9375
9376@item all
9377All the warnings.
9378@item none
9379Turn off all the warnings.
9380@item error
9381Treat warnings as errors.
9382@end table
9383
9384A category can be turned off by prefixing its name with @samp{no-}.  For
9385instance, @option{-Wno-yacc} will hide the warnings about
9386POSIX Yacc incompatibilities.
9387
9388@item -f [@var{feature}]
9389@itemx --feature[=@var{feature}]
9390Activate miscellaneous @var{feature}. @var{feature} can be one of:
9391@table @code
9392@item caret
9393@itemx diagnostics-show-caret
9394Show caret errors, in a manner similar to GCC's
9395@option{-fdiagnostics-show-caret}, or Clang's @option{-fcaret-diagnotics}. The
9396location provided with the message is used to quote the corresponding line of
9397the source file, underlining the important part of it with carets (^). Here is
9398an example, using the following file @file{in.y}:
9399
9400@example
9401%type <ival> exp
9402%%
9403exp: exp '+' exp @{ $exp = $1 + $2; @};
9404@end example
9405
9406When invoked with @option{-fcaret}, Bison will report:
9407
9408@example
9409@group
9410in.y:3.20-23: error: ambiguous reference: '$exp'
9411 exp: exp '+' exp @{ $exp = $1 + $2; @};
9412                    ^^^^
9413@end group
9414@group
9415in.y:3.1-3:       refers to: $exp at $$
9416 exp: exp '+' exp @{ $exp = $1 + $2; @};
9417 ^^^
9418@end group
9419@group
9420in.y:3.6-8:       refers to: $exp at $1
9421 exp: exp '+' exp @{ $exp = $1 + $2; @};
9422      ^^^
9423@end group
9424@group
9425in.y:3.14-16:     refers to: $exp at $3
9426 exp: exp '+' exp @{ $exp = $1 + $2; @};
9427              ^^^
9428@end group
9429@group
9430in.y:3.32-33: error: $2 of 'exp' has no declared type
9431 exp: exp '+' exp @{ $exp = $1 + $2; @};
9432                                ^^
9433@end group
9434@end example
9435
9436@end table
9437@end table
9438
9439@noindent
9440Tuning the parser:
9441
9442@table @option
9443@item -t
9444@itemx --debug
9445In the parser implementation file, define the macro @code{YYDEBUG} to
94461 if it is not already defined, so that the debugging facilities are
9447compiled.  @xref{Tracing, ,Tracing Your Parser}.
9448
9449@item -D @var{name}[=@var{value}]
9450@itemx --define=@var{name}[=@var{value}]
9451@itemx -F @var{name}[=@var{value}]
9452@itemx --force-define=@var{name}[=@var{value}]
9453Each of these is equivalent to @samp{%define @var{name} "@var{value}"}
9454(@pxref{%define Summary}) except that Bison processes multiple
9455definitions for the same @var{name} as follows:
9456
9457@itemize
9458@item
9459Bison quietly ignores all command-line definitions for @var{name} except
9460the last.
9461@item
9462If that command-line definition is specified by a @code{-D} or
9463@code{--define}, Bison reports an error for any @code{%define}
9464definition for @var{name}.
9465@item
9466If that command-line definition is specified by a @code{-F} or
9467@code{--force-define} instead, Bison quietly ignores all @code{%define}
9468definitions for @var{name}.
9469@item
9470Otherwise, Bison reports an error if there are multiple @code{%define}
9471definitions for @var{name}.
9472@end itemize
9473
9474You should avoid using @code{-F} and @code{--force-define} in your
9475make files unless you are confident that it is safe to quietly ignore
9476any conflicting @code{%define} that may be added to the grammar file.
9477
9478@item -L @var{language}
9479@itemx --language=@var{language}
9480Specify the programming language for the generated parser, as if
9481@code{%language} was specified (@pxref{Decl Summary, , Bison Declaration
9482Summary}).  Currently supported languages include C, C++, and Java.
9483@var{language} is case-insensitive.
9484
9485@item --locations
9486Pretend that @code{%locations} was specified.  @xref{Decl Summary}.
9487
9488@item -p @var{prefix}
9489@itemx --name-prefix=@var{prefix}
9490Pretend that @code{%name-prefix "@var{prefix}"} was specified (@pxref{Decl
9491Summary}).  Obsoleted by @code{-Dapi.prefix=@var{prefix}}.  @xref{Multiple
9492Parsers, ,Multiple Parsers in the Same Program}.
9493
9494@item -l
9495@itemx --no-lines
9496Don't put any @code{#line} preprocessor commands in the parser
9497implementation file.  Ordinarily Bison puts them in the parser
9498implementation file so that the C compiler and debuggers will
9499associate errors with your source file, the grammar file.  This option
9500causes them to associate errors with the parser implementation file,
9501treating it as an independent source file in its own right.
9502
9503@item -S @var{file}
9504@itemx --skeleton=@var{file}
9505Specify the skeleton to use, similar to @code{%skeleton}
9506(@pxref{Decl Summary, , Bison Declaration Summary}).
9507
9508@c You probably don't need this option unless you are developing Bison.
9509@c You should use @option{--language} if you want to specify the skeleton for a
9510@c different language, because it is clearer and because it will always
9511@c choose the correct skeleton for non-deterministic or push parsers.
9512
9513If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
9514file in the Bison installation directory.
9515If it does, @var{file} is an absolute file name or a file name relative to the
9516current working directory.
9517This is similar to how most shells resolve commands.
9518
9519@item -k
9520@itemx --token-table
9521Pretend that @code{%token-table} was specified.  @xref{Decl Summary}.
9522@end table
9523
9524@noindent
9525Adjust the output:
9526
9527@table @option
9528@item --defines[=@var{file}]
9529Pretend that @code{%defines} was specified, i.e., write an extra output
9530file containing macro definitions for the token type names defined in
9531the grammar, as well as a few other declarations.  @xref{Decl Summary}.
9532
9533@item -d
9534This is the same as @code{--defines} except @code{-d} does not accept a
9535@var{file} argument since POSIX Yacc requires that @code{-d} can be bundled
9536with other short options.
9537
9538@item -b @var{file-prefix}
9539@itemx --file-prefix=@var{prefix}
9540Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
9541for all Bison output file names.  @xref{Decl Summary}.
9542
9543@item -r @var{things}
9544@itemx --report=@var{things}
9545Write an extra output file containing verbose description of the comma
9546separated list of @var{things} among:
9547
9548@table @code
9549@item state
9550Description of the grammar, conflicts (resolved and unresolved), and
9551parser's automaton.
9552
9553@item itemset
9554Implies @code{state} and augments the description of the automaton with
9555the full set of items for each state, instead of its core only.
9556
9557@item lookahead
9558Implies @code{state} and augments the description of the automaton with
9559each rule's lookahead set.
9560
9561@item solved
9562Implies @code{state}.  Explain how conflicts were solved thanks to
9563precedence and associativity directives.
9564
9565@item all
9566Enable all the items.
9567
9568@item none
9569Do not generate the report.
9570@end table
9571
9572@item --report-file=@var{file}
9573Specify the @var{file} for the verbose description.
9574
9575@item -v
9576@itemx --verbose
9577Pretend that @code{%verbose} was specified, i.e., write an extra output
9578file containing verbose descriptions of the grammar and
9579parser.  @xref{Decl Summary}.
9580
9581@item -o @var{file}
9582@itemx --output=@var{file}
9583Specify the @var{file} for the parser implementation file.
9584
9585The other output files' names are constructed from @var{file} as
9586described under the @samp{-v} and @samp{-d} options.
9587
9588@item -g [@var{file}]
9589@itemx --graph[=@var{file}]
9590Output a graphical representation of the parser's
9591automaton computed by Bison, in @uref{http://www.graphviz.org/, Graphviz}
9592@uref{http://www.graphviz.org/doc/info/lang.html, DOT} format.
9593@code{@var{file}} is optional.
9594If omitted and the grammar file is @file{foo.y}, the output file will be
9595@file{foo.dot}.
9596
9597@item -x [@var{file}]
9598@itemx --xml[=@var{file}]
9599Output an XML report of the parser's automaton computed by Bison.
9600@code{@var{file}} is optional.
9601If omitted and the grammar file is @file{foo.y}, the output file will be
9602@file{foo.xml}.
9603(The current XML schema is experimental and may evolve.
9604More user feedback will help to stabilize it.)
9605@end table
9606
9607@node Option Cross Key
9608@section Option Cross Key
9609
9610Here is a list of options, alphabetized by long option, to help you find
9611the corresponding short option and directive.
9612
9613@multitable {@option{--force-define=@var{name}[=@var{value}]}} {@option{-F @var{name}[=@var{value}]}} {@code{%nondeterministic-parser}}
9614@headitem Long Option @tab Short Option @tab Bison Directive
9615@include cross-options.texi
9616@end multitable
9617
9618@node Yacc Library
9619@section Yacc Library
9620
9621The Yacc library contains default implementations of the
9622@code{yyerror} and @code{main} functions.  These default
9623implementations are normally not useful, but POSIX requires
9624them.  To use the Yacc library, link your program with the
9625@option{-ly} option.  Note that Bison's implementation of the Yacc
9626library is distributed under the terms of the GNU General
9627Public License (@pxref{Copying}).
9628
9629If you use the Yacc library's @code{yyerror} function, you should
9630declare @code{yyerror} as follows:
9631
9632@example
9633int yyerror (char const *);
9634@end example
9635
9636Bison ignores the @code{int} value returned by this @code{yyerror}.
9637If you use the Yacc library's @code{main} function, your
9638@code{yyparse} function should have the following type signature:
9639
9640@example
9641int yyparse (void);
9642@end example
9643
9644@c ================================================= C++ Bison
9645
9646@node Other Languages
9647@chapter Parsers Written In Other Languages
9648
9649@menu
9650* C++ Parsers::                 The interface to generate C++ parser classes
9651* Java Parsers::                The interface to generate Java parser classes
9652@end menu
9653
9654@node C++ Parsers
9655@section C++ Parsers
9656
9657@menu
9658* C++ Bison Interface::         Asking for C++ parser generation
9659* C++ Semantic Values::         %union vs. C++
9660* C++ Location Values::         The position and location classes
9661* C++ Parser Interface::        Instantiating and running the parser
9662* C++ Scanner Interface::       Exchanges between yylex and parse
9663* A Complete C++ Example::      Demonstrating their use
9664@end menu
9665
9666@node C++ Bison Interface
9667@subsection C++ Bison Interface
9668@c - %skeleton "lalr1.cc"
9669@c - Always pure
9670@c - initial action
9671
9672The C++ deterministic parser is selected using the skeleton directive,
9673@samp{%skeleton "lalr1.cc"}, or the synonymous command-line option
9674@option{--skeleton=lalr1.cc}.
9675@xref{Decl Summary}.
9676
9677When run, @command{bison} will create several entities in the @samp{yy}
9678namespace.
9679@findex %define namespace
9680Use the @samp{%define namespace} directive to change the namespace
9681name, see @ref{%define Summary,,namespace}.  The various classes are
9682generated in the following files:
9683
9684@table @file
9685@item position.hh
9686@itemx location.hh
9687The definition of the classes @code{position} and @code{location}, used for
9688location tracking.  These files are not generated if the @code{%define}
9689variable @code{api.location.type} is defined.  @xref{C++ Location Values}.
9690
9691@item stack.hh
9692An auxiliary class @code{stack} used by the parser.
9693
9694@item @var{file}.hh
9695@itemx @var{file}.cc
9696(Assuming the extension of the grammar file was @samp{.yy}.)  The
9697declaration and implementation of the C++ parser class.  The basename
9698and extension of these two files follow the same rules as with regular C
9699parsers (@pxref{Invocation}).
9700
9701The header is @emph{mandatory}; you must either pass
9702@option{-d}/@option{--defines} to @command{bison}, or use the
9703@samp{%defines} directive.
9704@end table
9705
9706All these files are documented using Doxygen; run @command{doxygen}
9707for a complete and accurate documentation.
9708
9709@node C++ Semantic Values
9710@subsection C++ Semantic Values
9711@c - No objects in unions
9712@c - YYSTYPE
9713@c - Printer and destructor
9714
9715The @code{%union} directive works as for C, see @ref{Union Decl, ,The
9716Collection of Value Types}.  In particular it produces a genuine
9717@code{union}@footnote{In the future techniques to allow complex types
9718within pseudo-unions (similar to Boost variants) might be implemented to
9719alleviate these issues.}, which have a few specific features in C++.
9720@itemize @minus
9721@item
9722The type @code{YYSTYPE} is defined but its use is discouraged: rather
9723you should refer to the parser's encapsulated type
9724@code{yy::parser::semantic_type}.
9725@item
9726Non POD (Plain Old Data) types cannot be used.  C++ forbids any
9727instance of classes with constructors in unions: only @emph{pointers}
9728to such objects are allowed.
9729@end itemize
9730
9731Because objects have to be stored via pointers, memory is not
9732reclaimed automatically: using the @code{%destructor} directive is the
9733only means to avoid leaks.  @xref{Destructor Decl, , Freeing Discarded
9734Symbols}.
9735
9736
9737@node C++ Location Values
9738@subsection C++ Location Values
9739@c - %locations
9740@c - class Position
9741@c - class Location
9742@c - %define filename_type "const symbol::Symbol"
9743
9744When the directive @code{%locations} is used, the C++ parser supports
9745location tracking, see @ref{Tracking Locations}.
9746
9747By default, two auxiliary classes define a @code{position}, a single point
9748in a file, and a @code{location}, a range composed of a pair of
9749@code{position}s (possibly spanning several files).  But if the
9750@code{%define} variable @code{api.location.type} is defined, then these
9751classes will not be generated, and the user defined type will be used.
9752
9753@tindex uint
9754In this section @code{uint} is an abbreviation for @code{unsigned int}: in
9755genuine code only the latter is used.
9756
9757@menu
9758* C++ position::                One point in the source file
9759* C++ location::                Two points in the source file
9760* User Defined Location Type::  Required interface for locations
9761@end menu
9762
9763@node C++ position
9764@subsubsection C++ @code{position}
9765
9766@deftypeop {Constructor} {position} {} position (std::string* @var{file} = 0, uint @var{line} = 1, uint @var{col} = 1)
9767Create a @code{position} denoting a given point.  Note that @code{file} is
9768not reclaimed when the @code{position} is destroyed: memory managed must be
9769handled elsewhere.
9770@end deftypeop
9771
9772@deftypemethod {position} {void} initialize (std::string* @var{file} = 0, uint @var{line} = 1, uint @var{col} = 1)
9773Reset the position to the given values.
9774@end deftypemethod
9775
9776@deftypeivar {position} {std::string*} file
9777The name of the file.  It will always be handled as a pointer, the
9778parser will never duplicate nor deallocate it.  As an experimental
9779feature you may change it to @samp{@var{type}*} using @samp{%define
9780filename_type "@var{type}"}.
9781@end deftypeivar
9782
9783@deftypeivar {position} {uint} line
9784The line, starting at 1.
9785@end deftypeivar
9786
9787@deftypemethod {position} {uint} lines (int @var{height} = 1)
9788Advance by @var{height} lines, resetting the column number.
9789@end deftypemethod
9790
9791@deftypeivar {position} {uint} column
9792The column, starting at 1.
9793@end deftypeivar
9794
9795@deftypemethod {position} {uint} columns (int @var{width} = 1)
9796Advance by @var{width} columns, without changing the line number.
9797@end deftypemethod
9798
9799@deftypemethod {position} {position&} operator+= (int @var{width})
9800@deftypemethodx {position} {position} operator+ (int @var{width})
9801@deftypemethodx {position} {position&} operator-= (int @var{width})
9802@deftypemethodx {position} {position} operator- (int @var{width})
9803Various forms of syntactic sugar for @code{columns}.
9804@end deftypemethod
9805
9806@deftypemethod {position} {bool} operator== (const position& @var{that})
9807@deftypemethodx {position} {bool} operator!= (const position& @var{that})
9808Whether @code{*this} and @code{that} denote equal/different positions.
9809@end deftypemethod
9810
9811@deftypefun {std::ostream&} operator<< (std::ostream& @var{o}, const position& @var{p})
9812Report @var{p} on @var{o} like this:
9813@samp{@var{file}:@var{line}.@var{column}}, or
9814@samp{@var{line}.@var{column}} if @var{file} is null.
9815@end deftypefun
9816
9817@node C++ location
9818@subsubsection C++ @code{location}
9819
9820@deftypeop {Constructor} {location} {} location (const position& @var{begin}, const position& @var{end})
9821Create a @code{Location} from the endpoints of the range.
9822@end deftypeop
9823
9824@deftypeop {Constructor} {location} {} location (const position& @var{pos} = position())
9825@deftypeopx {Constructor} {location} {} location (std::string* @var{file}, uint @var{line}, uint @var{col})
9826Create a @code{Location} denoting an empty range located at a given point.
9827@end deftypeop
9828
9829@deftypemethod {location} {void} initialize (std::string* @var{file} = 0, uint @var{line} = 1, uint @var{col} = 1)
9830Reset the location to an empty range at the given values.
9831@end deftypemethod
9832
9833@deftypeivar {location} {position} begin
9834@deftypeivarx {location} {position} end
9835The first, inclusive, position of the range, and the first beyond.
9836@end deftypeivar
9837
9838@deftypemethod {location} {uint} columns (int @var{width} = 1)
9839@deftypemethodx {location} {uint} lines (int @var{height} = 1)
9840Advance the @code{end} position.
9841@end deftypemethod
9842
9843@deftypemethod {location} {location} operator+ (const location& @var{end})
9844@deftypemethodx {location} {location} operator+ (int @var{width})
9845@deftypemethodx {location} {location} operator+= (int @var{width})
9846Various forms of syntactic sugar.
9847@end deftypemethod
9848
9849@deftypemethod {location} {void} step ()
9850Move @code{begin} onto @code{end}.
9851@end deftypemethod
9852
9853@deftypemethod {location} {bool} operator== (const location& @var{that})
9854@deftypemethodx {location} {bool} operator!= (const location& @var{that})
9855Whether @code{*this} and @code{that} denote equal/different ranges of
9856positions.
9857@end deftypemethod
9858
9859@deftypefun {std::ostream&} operator<< (std::ostream& @var{o}, const location& @var{p})
9860Report @var{p} on @var{o}, taking care of special cases such as: no
9861@code{filename} defined, or equal filename/line or column.
9862@end deftypefun
9863
9864@node User Defined Location Type
9865@subsubsection User Defined Location Type
9866@findex %define api.location.type
9867
9868Instead of using the built-in types you may use the @code{%define} variable
9869@code{api.location.type} to specify your own type:
9870
9871@example
9872%define api.location.type @var{LocationType}
9873@end example
9874
9875The requirements over your @var{LocationType} are:
9876@itemize
9877@item
9878it must be copyable;
9879
9880@item
9881in order to compute the (default) value of @code{@@$} in a reduction, the
9882parser basically runs
9883@example
9884@@$.begin = @@$1.begin;
9885@@$.end   = @@$@var{N}.end; // The location of last right-hand side symbol.
9886@end example
9887@noindent
9888so there must be copyable @code{begin} and @code{end} members;
9889
9890@item
9891alternatively you may redefine the computation of the default location, in
9892which case these members are not required (@pxref{Location Default Action});
9893
9894@item
9895if traces are enabled, then there must exist an @samp{std::ostream&
9896  operator<< (std::ostream& o, const @var{LocationType}& s)} function.
9897@end itemize
9898
9899@sp 1
9900
9901In programs with several C++ parsers, you may also use the @code{%define}
9902variable @code{api.location.type} to share a common set of built-in
9903definitions for @code{position} and @code{location}.  For instance, one
9904parser @file{master/parser.yy} might use:
9905
9906@example
9907%defines
9908%locations
9909%define namespace "master::"
9910@end example
9911
9912@noindent
9913to generate the @file{master/position.hh} and @file{master/location.hh}
9914files, reused by other parsers as follows:
9915
9916@example
9917%define api.location.type "master::location"
9918%code requires @{ #include <master/location.hh> @}
9919@end example
9920
9921@node C++ Parser Interface
9922@subsection C++ Parser Interface
9923@c - define parser_class_name
9924@c - Ctor
9925@c - parse, error, set_debug_level, debug_level, set_debug_stream,
9926@c   debug_stream.
9927@c - Reporting errors
9928
9929The output files @file{@var{output}.hh} and @file{@var{output}.cc}
9930declare and define the parser class in the namespace @code{yy}.  The
9931class name defaults to @code{parser}, but may be changed using
9932@samp{%define parser_class_name "@var{name}"}.  The interface of
9933this class is detailed below.  It can be extended using the
9934@code{%parse-param} feature: its semantics is slightly changed since
9935it describes an additional member of the parser class, and an
9936additional argument for its constructor.
9937
9938@defcv {Type} {parser} {semantic_type}
9939@defcvx {Type} {parser} {location_type}
9940The types for semantics value and locations.
9941@end defcv
9942
9943@defcv {Type} {parser} {token}
9944A structure that contains (only) the @code{yytokentype} enumeration, which
9945defines the tokens.  To refer to the token @code{FOO},
9946use @code{yy::parser::token::FOO}.  The scanner can use
9947@samp{typedef yy::parser::token token;} to ``import'' the token enumeration
9948(@pxref{Calc++ Scanner}).
9949@end defcv
9950
9951@deftypemethod {parser} {} parser (@var{type1} @var{arg1}, ...)
9952Build a new parser object.  There are no arguments by default, unless
9953@samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
9954@end deftypemethod
9955
9956@deftypemethod {parser} {int} parse ()
9957Run the syntactic analysis, and return 0 on success, 1 otherwise.
9958
9959@cindex exceptions
9960The whole function is wrapped in a @code{try}/@code{catch} block, so that
9961when an exception is thrown, the @code{%destructor}s are called to release
9962the lookahead symbol, and the symbols pushed on the stack.
9963@end deftypemethod
9964
9965@deftypemethod {parser} {std::ostream&} debug_stream ()
9966@deftypemethodx {parser} {void} set_debug_stream (std::ostream& @var{o})
9967Get or set the stream used for tracing the parsing.  It defaults to
9968@code{std::cerr}.
9969@end deftypemethod
9970
9971@deftypemethod {parser} {debug_level_type} debug_level ()
9972@deftypemethodx {parser} {void} set_debug_level (debug_level @var{l})
9973Get or set the tracing level.  Currently its value is either 0, no trace,
9974or nonzero, full tracing.
9975@end deftypemethod
9976
9977@deftypemethod {parser} {void} error (const location_type& @var{l}, const std::string& @var{m})
9978The definition for this member function must be supplied by the user:
9979the parser uses it to report a parser error occurring at @var{l},
9980described by @var{m}.
9981@end deftypemethod
9982
9983
9984@node C++ Scanner Interface
9985@subsection C++ Scanner Interface
9986@c - prefix for yylex.
9987@c - Pure interface to yylex
9988@c - %lex-param
9989
9990The parser invokes the scanner by calling @code{yylex}.  Contrary to C
9991parsers, C++ parsers are always pure: there is no point in using the
9992@code{%define api.pure full} directive.  Therefore the interface is as follows.
9993
9994@deftypemethod {parser} {int} yylex (semantic_type* @var{yylval}, location_type* @var{yylloc}, @var{type1} @var{arg1}, ...)
9995Return the next token.  Its type is the return value, its semantic
9996value and location being @var{yylval} and @var{yylloc}.  Invocations of
9997@samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
9998@end deftypemethod
9999
10000
10001@node A Complete C++ Example
10002@subsection A Complete C++ Example
10003
10004This section demonstrates the use of a C++ parser with a simple but
10005complete example.  This example should be available on your system,
10006ready to compile, in the directory @dfn{../bison/examples/calc++}.  It
10007focuses on the use of Bison, therefore the design of the various C++
10008classes is very naive: no accessors, no encapsulation of members etc.
10009We will use a Lex scanner, and more precisely, a Flex scanner, to
10010demonstrate the various interaction.  A hand written scanner is
10011actually easier to interface with.
10012
10013@menu
10014* Calc++ --- C++ Calculator::   The specifications
10015* Calc++ Parsing Driver::       An active parsing context
10016* Calc++ Parser::               A parser class
10017* Calc++ Scanner::              A pure C++ Flex scanner
10018* Calc++ Top Level::            Conducting the band
10019@end menu
10020
10021@node Calc++ --- C++ Calculator
10022@subsubsection Calc++ --- C++ Calculator
10023
10024Of course the grammar is dedicated to arithmetics, a single
10025expression, possibly preceded by variable assignments.  An
10026environment containing possibly predefined variables such as
10027@code{one} and @code{two}, is exchanged with the parser.  An example
10028of valid input follows.
10029
10030@example
10031three := 3
10032seven := one + two * three
10033seven * seven
10034@end example
10035
10036@node Calc++ Parsing Driver
10037@subsubsection Calc++ Parsing Driver
10038@c - An env
10039@c - A place to store error messages
10040@c - A place for the result
10041
10042To support a pure interface with the parser (and the scanner) the
10043technique of the ``parsing context'' is convenient: a structure
10044containing all the data to exchange.  Since, in addition to simply
10045launch the parsing, there are several auxiliary tasks to execute (open
10046the file for parsing, instantiate the parser etc.), we recommend
10047transforming the simple parsing context structure into a fully blown
10048@dfn{parsing driver} class.
10049
10050The declaration of this driver class, @file{calc++-driver.hh}, is as
10051follows.  The first part includes the CPP guard and imports the
10052required standard library components, and the declaration of the parser
10053class.
10054
10055@comment file: calc++-driver.hh
10056@example
10057#ifndef CALCXX_DRIVER_HH
10058# define CALCXX_DRIVER_HH
10059# include <string>
10060# include <map>
10061# include "calc++-parser.hh"
10062@end example
10063
10064
10065@noindent
10066Then comes the declaration of the scanning function.  Flex expects
10067the signature of @code{yylex} to be defined in the macro
10068@code{YY_DECL}, and the C++ parser expects it to be declared.  We can
10069factor both as follows.
10070
10071@comment file: calc++-driver.hh
10072@example
10073// Tell Flex the lexer's prototype ...
10074# define YY_DECL                                        \
10075  yy::calcxx_parser::token_type                         \
10076  yylex (yy::calcxx_parser::semantic_type* yylval,      \
10077         yy::calcxx_parser::location_type* yylloc,      \
10078         calcxx_driver& driver)
10079// ... and declare it for the parser's sake.
10080YY_DECL;
10081@end example
10082
10083@noindent
10084The @code{calcxx_driver} class is then declared with its most obvious
10085members.
10086
10087@comment file: calc++-driver.hh
10088@example
10089// Conducting the whole scanning and parsing of Calc++.
10090class calcxx_driver
10091@{
10092public:
10093  calcxx_driver ();
10094  virtual ~calcxx_driver ();
10095
10096  std::map<std::string, int> variables;
10097
10098  int result;
10099@end example
10100
10101@noindent
10102To encapsulate the coordination with the Flex scanner, it is useful to
10103have two members function to open and close the scanning phase.
10104
10105@comment file: calc++-driver.hh
10106@example
10107  // Handling the scanner.
10108  void scan_begin ();
10109  void scan_end ();
10110  bool trace_scanning;
10111@end example
10112
10113@noindent
10114Similarly for the parser itself.
10115
10116@comment file: calc++-driver.hh
10117@example
10118  // Run the parser.  Return 0 on success.
10119  int parse (const std::string& f);
10120  std::string file;
10121  bool trace_parsing;
10122@end example
10123
10124@noindent
10125To demonstrate pure handling of parse errors, instead of simply
10126dumping them on the standard error output, we will pass them to the
10127compiler driver using the following two member functions.  Finally, we
10128close the class declaration and CPP guard.
10129
10130@comment file: calc++-driver.hh
10131@example
10132  // Error handling.
10133  void error (const yy::location& l, const std::string& m);
10134  void error (const std::string& m);
10135@};
10136#endif // ! CALCXX_DRIVER_HH
10137@end example
10138
10139The implementation of the driver is straightforward.  The @code{parse}
10140member function deserves some attention.  The @code{error} functions
10141are simple stubs, they should actually register the located error
10142messages and set error state.
10143
10144@comment file: calc++-driver.cc
10145@example
10146#include "calc++-driver.hh"
10147#include "calc++-parser.hh"
10148
10149calcxx_driver::calcxx_driver ()
10150  : trace_scanning (false), trace_parsing (false)
10151@{
10152  variables["one"] = 1;
10153  variables["two"] = 2;
10154@}
10155
10156calcxx_driver::~calcxx_driver ()
10157@{
10158@}
10159
10160int
10161calcxx_driver::parse (const std::string &f)
10162@{
10163  file = f;
10164  scan_begin ();
10165  yy::calcxx_parser parser (*this);
10166  parser.set_debug_level (trace_parsing);
10167  int res = parser.parse ();
10168  scan_end ();
10169  return res;
10170@}
10171
10172void
10173calcxx_driver::error (const yy::location& l, const std::string& m)
10174@{
10175  std::cerr << l << ": " << m << std::endl;
10176@}
10177
10178void
10179calcxx_driver::error (const std::string& m)
10180@{
10181  std::cerr << m << std::endl;
10182@}
10183@end example
10184
10185@node Calc++ Parser
10186@subsubsection Calc++ Parser
10187
10188The grammar file @file{calc++-parser.yy} starts by asking for the C++
10189deterministic parser skeleton, the creation of the parser header file,
10190and specifies the name of the parser class.  Because the C++ skeleton
10191changed several times, it is safer to require the version you designed
10192the grammar for.
10193
10194@comment file: calc++-parser.yy
10195@example
10196%skeleton "lalr1.cc" /* -*- C++ -*- */
10197%require "@value{VERSION}"
10198%defines
10199%define parser_class_name "calcxx_parser"
10200@end example
10201
10202@noindent
10203@findex %code requires
10204Then come the declarations/inclusions needed to define the
10205@code{%union}.  Because the parser uses the parsing driver and
10206reciprocally, both cannot include the header of the other.  Because the
10207driver's header needs detailed knowledge about the parser class (in
10208particular its inner types), it is the parser's header which will simply
10209use a forward declaration of the driver.
10210@xref{%code Summary}.
10211
10212@comment file: calc++-parser.yy
10213@example
10214%code requires @{
10215# include <string>
10216class calcxx_driver;
10217@}
10218@end example
10219
10220@noindent
10221The driver is passed by reference to the parser and to the scanner.
10222This provides a simple but effective pure interface, not relying on
10223global variables.
10224
10225@comment file: calc++-parser.yy
10226@example
10227// The parsing context.
10228%parse-param @{ calcxx_driver& driver @}
10229%lex-param   @{ calcxx_driver& driver @}
10230@end example
10231
10232@noindent
10233Then we request the location tracking feature, and initialize the
10234first location's file name.  Afterward new locations are computed
10235relatively to the previous locations: the file name will be
10236automatically propagated.
10237
10238@comment file: calc++-parser.yy
10239@example
10240%locations
10241%initial-action
10242@{
10243  // Initialize the initial location.
10244  @@$.begin.filename = @@$.end.filename = &driver.file;
10245@};
10246@end example
10247
10248@noindent
10249Use the two following directives to enable parser tracing and verbose error
10250messages.  However, verbose error messages can contain incorrect information
10251(@pxref{LAC}).
10252
10253@comment file: calc++-parser.yy
10254@example
10255%debug
10256%error-verbose
10257@end example
10258
10259@noindent
10260Semantic values cannot use ``real'' objects, but only pointers to
10261them.
10262
10263@comment file: calc++-parser.yy
10264@example
10265// Symbols.
10266%union
10267@{
10268  int          ival;
10269  std::string *sval;
10270@};
10271@end example
10272
10273@noindent
10274@findex %code
10275The code between @samp{%code @{} and @samp{@}} is output in the
10276@file{*.cc} file; it needs detailed knowledge about the driver.
10277
10278@comment file: calc++-parser.yy
10279@example
10280%code @{
10281# include "calc++-driver.hh"
10282@}
10283@end example
10284
10285
10286@noindent
10287The token numbered as 0 corresponds to end of file; the following line
10288allows for nicer error messages referring to ``end of file'' instead
10289of ``$end''.  Similarly user friendly named are provided for each
10290symbol.  Note that the tokens names are prefixed by @code{TOKEN_} to
10291avoid name clashes.
10292
10293@comment file: calc++-parser.yy
10294@example
10295%token        END      0 "end of file"
10296%token        ASSIGN     ":="
10297%token <sval> IDENTIFIER "identifier"
10298%token <ival> NUMBER     "number"
10299%type  <ival> exp
10300@end example
10301
10302@noindent
10303To enable memory deallocation during error recovery, use
10304@code{%destructor}.
10305
10306@c FIXME: Document %printer, and mention that it takes a braced-code operand.
10307@comment file: calc++-parser.yy
10308@example
10309%printer    @{ yyoutput << *$$; @} "identifier"
10310%destructor @{ delete $$; @} "identifier"
10311
10312%printer    @{ yyoutput << $$; @} <ival>
10313@end example
10314
10315@noindent
10316The grammar itself is straightforward.
10317
10318@comment file: calc++-parser.yy
10319@example
10320%%
10321%start unit;
10322unit: assignments exp  @{ driver.result = $2; @};
10323
10324assignments:
10325  /* Nothing.  */        @{@}
10326| assignments assignment @{@};
10327
10328assignment:
10329     "identifier" ":=" exp
10330       @{ driver.variables[*$1] = $3; delete $1; @};
10331
10332%left '+' '-';
10333%left '*' '/';
10334exp: exp '+' exp   @{ $$ = $1 + $3; @}
10335   | exp '-' exp   @{ $$ = $1 - $3; @}
10336   | exp '*' exp   @{ $$ = $1 * $3; @}
10337   | exp '/' exp   @{ $$ = $1 / $3; @}
10338   | "identifier"  @{ $$ = driver.variables[*$1]; delete $1; @}
10339   | "number"      @{ $$ = $1; @};
10340%%
10341@end example
10342
10343@noindent
10344Finally the @code{error} member function registers the errors to the
10345driver.
10346
10347@comment file: calc++-parser.yy
10348@example
10349void
10350yy::calcxx_parser::error (const yy::calcxx_parser::location_type& l,
10351                          const std::string& m)
10352@{
10353  driver.error (l, m);
10354@}
10355@end example
10356
10357@node Calc++ Scanner
10358@subsubsection Calc++ Scanner
10359
10360The Flex scanner first includes the driver declaration, then the
10361parser's to get the set of defined tokens.
10362
10363@comment file: calc++-scanner.ll
10364@example
10365%@{ /* -*- C++ -*- */
10366# include <cstdlib>
10367# include <cerrno>
10368# include <climits>
10369# include <string>
10370# include "calc++-driver.hh"
10371# include "calc++-parser.hh"
10372
10373/* Work around an incompatibility in flex (at least versions
10374   2.5.31 through 2.5.33): it generates code that does
10375   not conform to C89.  See Debian bug 333231
10376   <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>.  */
10377# undef yywrap
10378# define yywrap() 1
10379
10380/* By default yylex returns int, we use token_type.
10381   Unfortunately yyterminate by default returns 0, which is
10382   not of token_type.  */
10383#define yyterminate() return token::END
10384%@}
10385@end example
10386
10387@noindent
10388Because there is no @code{#include}-like feature we don't need
10389@code{yywrap}, we don't need @code{unput} either, and we parse an
10390actual file, this is not an interactive session with the user.
10391Finally we enable the scanner tracing features.
10392
10393@comment file: calc++-scanner.ll
10394@example
10395%option noyywrap nounput batch debug
10396@end example
10397
10398@noindent
10399Abbreviations allow for more readable rules.
10400
10401@comment file: calc++-scanner.ll
10402@example
10403id    [a-zA-Z][a-zA-Z_0-9]*
10404int   [0-9]+
10405blank [ \t]
10406@end example
10407
10408@noindent
10409The following paragraph suffices to track locations accurately.  Each
10410time @code{yylex} is invoked, the begin position is moved onto the end
10411position.  Then when a pattern is matched, the end position is
10412advanced of its width.  In case it matched ends of lines, the end
10413cursor is adjusted, and each time blanks are matched, the begin cursor
10414is moved onto the end cursor to effectively ignore the blanks
10415preceding tokens.  Comments would be treated equally.
10416
10417@comment file: calc++-scanner.ll
10418@example
10419@group
10420%@{
10421# define YY_USER_ACTION  yylloc->columns (yyleng);
10422%@}
10423@end group
10424%%
10425%@{
10426  yylloc->step ();
10427%@}
10428@{blank@}+   yylloc->step ();
10429[\n]+      yylloc->lines (yyleng); yylloc->step ();
10430@end example
10431
10432@noindent
10433The rules are simple, just note the use of the driver to report errors.
10434It is convenient to use a typedef to shorten
10435@code{yy::calcxx_parser::token::identifier} into
10436@code{token::identifier} for instance.
10437
10438@comment file: calc++-scanner.ll
10439@example
10440%@{
10441  typedef yy::calcxx_parser::token token;
10442%@}
10443         /* Convert ints to the actual type of tokens.  */
10444[-+*/]   return yy::calcxx_parser::token_type (yytext[0]);
10445
10446":="     return token::ASSIGN;
10447
10448@group
10449@{int@}    @{
10450           errno = 0;
10451           long n = strtol (yytext, NULL, 10);
10452           if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
10453             driver.error (*yylloc, "integer is out of range");
10454           yylval->ival = n;
10455           return token::NUMBER;
10456         @}
10457@end group
10458
10459@group
10460@{id@}     @{
10461           yylval->sval = new std::string (yytext);
10462           return token::IDENTIFIER;
10463         @}
10464@end group
10465
10466.        driver.error (*yylloc, "invalid character");
10467%%
10468@end example
10469
10470@noindent
10471Finally, because the scanner related driver's member function depend
10472on the scanner's data, it is simpler to implement them in this file.
10473
10474@comment file: calc++-scanner.ll
10475@example
10476@group
10477void
10478calcxx_driver::scan_begin ()
10479@{
10480  yy_flex_debug = trace_scanning;
10481  if (file.empty () || file == "-")
10482    yyin = stdin;
10483  else if (!(yyin = fopen (file.c_str (), "r")))
10484    @{
10485      error ("cannot open " + file + ": " + strerror(errno));
10486      exit (EXIT_FAILURE);
10487    @}
10488@}
10489@end group
10490
10491@group
10492void
10493calcxx_driver::scan_end ()
10494@{
10495  fclose (yyin);
10496@}
10497@end group
10498@end example
10499
10500@node Calc++ Top Level
10501@subsubsection Calc++ Top Level
10502
10503The top level file, @file{calc++.cc}, poses no problem.
10504
10505@comment file: calc++.cc
10506@example
10507#include <iostream>
10508#include "calc++-driver.hh"
10509
10510@group
10511int
10512main (int argc, char *argv[])
10513@{
10514  calcxx_driver driver;
10515  for (int i = 1; i < argc; ++i)
10516    if (argv[i] == std::string ("-p"))
10517      driver.trace_parsing = true;
10518    else if (argv[i] == std::string ("-s"))
10519      driver.trace_scanning = true;
10520    else if (!driver.parse (argv[i]))
10521      std::cout << driver.result << std::endl;
10522@}
10523@end group
10524@end example
10525
10526@node Java Parsers
10527@section Java Parsers
10528
10529@menu
10530* Java Bison Interface::        Asking for Java parser generation
10531* Java Semantic Values::        %type and %token vs. Java
10532* Java Location Values::        The position and location classes
10533* Java Parser Interface::       Instantiating and running the parser
10534* Java Scanner Interface::      Specifying the scanner for the parser
10535* Java Action Features::        Special features for use in actions
10536* Java Differences::            Differences between C/C++ and Java Grammars
10537* Java Declarations Summary::   List of Bison declarations used with Java
10538@end menu
10539
10540@node Java Bison Interface
10541@subsection Java Bison Interface
10542@c - %language "Java"
10543
10544(The current Java interface is experimental and may evolve.
10545More user feedback will help to stabilize it.)
10546
10547The Java parser skeletons are selected using the @code{%language "Java"}
10548directive or the @option{-L java}/@option{--language=java} option.
10549
10550@c FIXME: Documented bug.
10551When generating a Java parser, @code{bison @var{basename}.y} will
10552create a single Java source file named @file{@var{basename}.java}
10553containing the parser implementation.  Using a grammar file without a
10554@file{.y} suffix is currently broken.  The basename of the parser
10555implementation file can be changed by the @code{%file-prefix}
10556directive or the @option{-p}/@option{--name-prefix} option.  The
10557entire parser implementation file name can be changed by the
10558@code{%output} directive or the @option{-o}/@option{--output} option.
10559The parser implementation file contains a single class for the parser.
10560
10561You can create documentation for generated parsers using Javadoc.
10562
10563Contrary to C parsers, Java parsers do not use global variables; the
10564state of the parser is always local to an instance of the parser class.
10565Therefore, all Java parsers are ``pure'', and the @code{%pure-parser}
10566and @code{%define api.pure full} directives does not do anything when used in
10567Java.
10568
10569Push parsers are currently unsupported in Java and @code{%define
10570api.push-pull} have no effect.
10571
10572GLR parsers are currently unsupported in Java.  Do not use the
10573@code{glr-parser} directive.
10574
10575No header file can be generated for Java parsers.  Do not use the
10576@code{%defines} directive or the @option{-d}/@option{--defines} options.
10577
10578@c FIXME: Possible code change.
10579Currently, support for debugging and verbose errors are always compiled
10580in.  Thus the @code{%debug} and @code{%token-table} directives and the
10581@option{-t}/@option{--debug} and @option{-k}/@option{--token-table}
10582options have no effect.  This may change in the future to eliminate
10583unused code in the generated parser, so use @code{%debug} and
10584@code{%verbose-error} explicitly if needed.  Also, in the future the
10585@code{%token-table} directive might enable a public interface to
10586access the token names and codes.
10587
10588@node Java Semantic Values
10589@subsection Java Semantic Values
10590@c - No %union, specify type in %type/%token.
10591@c - YYSTYPE
10592@c - Printer and destructor
10593
10594There is no @code{%union} directive in Java parsers.  Instead, the
10595semantic values' types (class names) should be specified in the
10596@code{%type} or @code{%token} directive:
10597
10598@example
10599%type <Expression> expr assignment_expr term factor
10600%type <Integer> number
10601@end example
10602
10603By default, the semantic stack is declared to have @code{Object} members,
10604which means that the class types you specify can be of any class.
10605To improve the type safety of the parser, you can declare the common
10606superclass of all the semantic values using the @code{%define stype}
10607directive.  For example, after the following declaration:
10608
10609@example
10610%define stype "ASTNode"
10611@end example
10612
10613@noindent
10614any @code{%type} or @code{%token} specifying a semantic type which
10615is not a subclass of ASTNode, will cause a compile-time error.
10616
10617@c FIXME: Documented bug.
10618Types used in the directives may be qualified with a package name.
10619Primitive data types are accepted for Java version 1.5 or later.  Note
10620that in this case the autoboxing feature of Java 1.5 will be used.
10621Generic types may not be used; this is due to a limitation in the
10622implementation of Bison, and may change in future releases.
10623
10624Java parsers do not support @code{%destructor}, since the language
10625adopts garbage collection.  The parser will try to hold references
10626to semantic values for as little time as needed.
10627
10628Java parsers do not support @code{%printer}, as @code{toString()}
10629can be used to print the semantic values.  This however may change
10630(in a backwards-compatible way) in future versions of Bison.
10631
10632
10633@node Java Location Values
10634@subsection Java Location Values
10635@c - %locations
10636@c - class Position
10637@c - class Location
10638
10639When the directive @code{%locations} is used, the Java parser supports
10640location tracking, see @ref{Tracking Locations}.  An auxiliary user-defined
10641class defines a @dfn{position}, a single point in a file; Bison itself
10642defines a class representing a @dfn{location}, a range composed of a pair of
10643positions (possibly spanning several files).  The location class is an inner
10644class of the parser; the name is @code{Location} by default, and may also be
10645renamed using @code{%define api.location.type "@var{class-name}"}.
10646
10647The location class treats the position as a completely opaque value.
10648By default, the class name is @code{Position}, but this can be changed
10649with @code{%define api.position.type "@var{class-name}"}.  This class must
10650be supplied by the user.
10651
10652
10653@deftypeivar {Location} {Position} begin
10654@deftypeivarx {Location} {Position} end
10655The first, inclusive, position of the range, and the first beyond.
10656@end deftypeivar
10657
10658@deftypeop {Constructor} {Location} {} Location (Position @var{loc})
10659Create a @code{Location} denoting an empty range located at a given point.
10660@end deftypeop
10661
10662@deftypeop {Constructor} {Location} {} Location (Position @var{begin}, Position @var{end})
10663Create a @code{Location} from the endpoints of the range.
10664@end deftypeop
10665
10666@deftypemethod {Location} {String} toString ()
10667Prints the range represented by the location.  For this to work
10668properly, the position class should override the @code{equals} and
10669@code{toString} methods appropriately.
10670@end deftypemethod
10671
10672
10673@node Java Parser Interface
10674@subsection Java Parser Interface
10675@c - define parser_class_name
10676@c - Ctor
10677@c - parse, error, set_debug_level, debug_level, set_debug_stream,
10678@c   debug_stream.
10679@c - Reporting errors
10680
10681The name of the generated parser class defaults to @code{YYParser}.  The
10682@code{YY} prefix may be changed using the @code{%name-prefix} directive
10683or the @option{-p}/@option{--name-prefix} option.  Alternatively, use
10684@code{%define parser_class_name "@var{name}"} to give a custom name to
10685the class.  The interface of this class is detailed below.
10686
10687By default, the parser class has package visibility.  A declaration
10688@code{%define public} will change to public visibility.  Remember that,
10689according to the Java language specification, the name of the @file{.java}
10690file should match the name of the class in this case.  Similarly, you can
10691use @code{abstract}, @code{final} and @code{strictfp} with the
10692@code{%define} declaration to add other modifiers to the parser class.
10693
10694The Java package name of the parser class can be specified using the
10695@code{%define package} directive.  The superclass and the implemented
10696interfaces of the parser class can be specified with the @code{%define
10697extends} and @code{%define implements} directives.
10698
10699The parser class defines an inner class, @code{Location}, that is used
10700for location tracking (see @ref{Java Location Values}), and a inner
10701interface, @code{Lexer} (see @ref{Java Scanner Interface}).  Other than
10702these inner class/interface, and the members described in the interface
10703below, all the other members and fields are preceded with a @code{yy} or
10704@code{YY} prefix to avoid clashes with user code.
10705
10706@c FIXME: The following constants and variables are still undocumented:
10707@c @code{bisonVersion}, @code{bisonSkeleton} and @code{errorVerbose}.
10708
10709The parser class can be extended using the @code{%parse-param}
10710directive. Each occurrence of the directive will add a @code{protected
10711final} field to the parser class, and an argument to its constructor,
10712which initialize them automatically.
10713
10714Token names defined by @code{%token} and the predefined @code{EOF} token
10715name are added as constant fields to the parser class.
10716
10717@deftypeop {Constructor} {YYParser} {} YYParser (@var{lex_param}, @dots{}, @var{parse_param}, @dots{})
10718Build a new parser object with embedded @code{%code lexer}.  There are
10719no parameters, unless @code{%parse-param}s and/or @code{%lex-param}s are
10720used.
10721@end deftypeop
10722
10723@deftypeop {Constructor} {YYParser} {} YYParser (Lexer @var{lexer}, @var{parse_param}, @dots{})
10724Build a new parser object using the specified scanner.  There are no
10725additional parameters unless @code{%parse-param}s are used.
10726
10727If the scanner is defined by @code{%code lexer}, this constructor is
10728declared @code{protected} and is called automatically with a scanner
10729created with the correct @code{%lex-param}s.
10730@end deftypeop
10731
10732@deftypemethod {YYParser} {boolean} parse ()
10733Run the syntactic analysis, and return @code{true} on success,
10734@code{false} otherwise.
10735@end deftypemethod
10736
10737@deftypemethod {YYParser} {boolean} recovering ()
10738During the syntactic analysis, return @code{true} if recovering
10739from a syntax error.
10740@xref{Error Recovery}.
10741@end deftypemethod
10742
10743@deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
10744@deftypemethodx {YYParser} {void} setDebugStream (java.io.printStream @var{o})
10745Get or set the stream used for tracing the parsing.  It defaults to
10746@code{System.err}.
10747@end deftypemethod
10748
10749@deftypemethod {YYParser} {int} getDebugLevel ()
10750@deftypemethodx {YYParser} {void} setDebugLevel (int @var{l})
10751Get or set the tracing level.  Currently its value is either 0, no trace,
10752or nonzero, full tracing.
10753@end deftypemethod
10754
10755
10756@node Java Scanner Interface
10757@subsection Java Scanner Interface
10758@c - %code lexer
10759@c - %lex-param
10760@c - Lexer interface
10761
10762There are two possible ways to interface a Bison-generated Java parser
10763with a scanner: the scanner may be defined by @code{%code lexer}, or
10764defined elsewhere.  In either case, the scanner has to implement the
10765@code{Lexer} inner interface of the parser class.
10766
10767In the first case, the body of the scanner class is placed in
10768@code{%code lexer} blocks.  If you want to pass parameters from the
10769parser constructor to the scanner constructor, specify them with
10770@code{%lex-param}; they are passed before @code{%parse-param}s to the
10771constructor.
10772
10773In the second case, the scanner has to implement the @code{Lexer} interface,
10774which is defined within the parser class (e.g., @code{YYParser.Lexer}).
10775The constructor of the parser object will then accept an object
10776implementing the interface; @code{%lex-param} is not used in this
10777case.
10778
10779In both cases, the scanner has to implement the following methods.
10780
10781@deftypemethod {Lexer} {void} yyerror (Location @var{loc}, String @var{msg})
10782This method is defined by the user to emit an error message.  The first
10783parameter is omitted if location tracking is not active.  Its type can be
10784changed using @code{%define api.location.type "@var{class-name}".}
10785@end deftypemethod
10786
10787@deftypemethod {Lexer} {int} yylex ()
10788Return the next token.  Its type is the return value, its semantic
10789value and location are saved and returned by the their methods in the
10790interface.
10791
10792Use @code{%define lex_throws} to specify any uncaught exceptions.
10793Default is @code{java.io.IOException}.
10794@end deftypemethod
10795
10796@deftypemethod {Lexer} {Position} getStartPos ()
10797@deftypemethodx {Lexer} {Position} getEndPos ()
10798Return respectively the first position of the last token that
10799@code{yylex} returned, and the first position beyond it.  These
10800methods are not needed unless location tracking is active.
10801
10802The return type can be changed using @code{%define api.position.type
10803"@var{class-name}".}
10804@end deftypemethod
10805
10806@deftypemethod {Lexer} {Object} getLVal ()
10807Return the semantic value of the last token that yylex returned.
10808
10809The return type can be changed using @code{%define stype
10810"@var{class-name}".}
10811@end deftypemethod
10812
10813
10814@node Java Action Features
10815@subsection Special Features for Use in Java Actions
10816
10817The following special constructs can be uses in Java actions.
10818Other analogous C action features are currently unavailable for Java.
10819
10820Use @code{%define throws} to specify any uncaught exceptions from parser
10821actions, and initial actions specified by @code{%initial-action}.
10822
10823@defvar $@var{n}
10824The semantic value for the @var{n}th component of the current rule.
10825This may not be assigned to.
10826@xref{Java Semantic Values}.
10827@end defvar
10828
10829@defvar $<@var{typealt}>@var{n}
10830Like @code{$@var{n}} but specifies a alternative type @var{typealt}.
10831@xref{Java Semantic Values}.
10832@end defvar
10833
10834@defvar $$
10835The semantic value for the grouping made by the current rule.  As a
10836value, this is in the base type (@code{Object} or as specified by
10837@code{%define stype}) as in not cast to the declared subtype because
10838casts are not allowed on the left-hand side of Java assignments.
10839Use an explicit Java cast if the correct subtype is needed.
10840@xref{Java Semantic Values}.
10841@end defvar
10842
10843@defvar $<@var{typealt}>$
10844Same as @code{$$} since Java always allow assigning to the base type.
10845Perhaps we should use this and @code{$<>$} for the value and @code{$$}
10846for setting the value but there is currently no easy way to distinguish
10847these constructs.
10848@xref{Java Semantic Values}.
10849@end defvar
10850
10851@defvar @@@var{n}
10852The location information of the @var{n}th component of the current rule.
10853This may not be assigned to.
10854@xref{Java Location Values}.
10855@end defvar
10856
10857@defvar @@$
10858The location information of the grouping made by the current rule.
10859@xref{Java Location Values}.
10860@end defvar
10861
10862@deftypefn {Statement} return YYABORT @code{;}
10863Return immediately from the parser, indicating failure.
10864@xref{Java Parser Interface}.
10865@end deftypefn
10866
10867@deftypefn {Statement} return YYACCEPT @code{;}
10868Return immediately from the parser, indicating success.
10869@xref{Java Parser Interface}.
10870@end deftypefn
10871
10872@deftypefn {Statement} {return} YYERROR @code{;}
10873Start error recovery (without printing an error message).
10874@xref{Error Recovery}.
10875@end deftypefn
10876
10877@deftypefn {Function} {boolean} recovering ()
10878Return whether error recovery is being done. In this state, the parser
10879reads token until it reaches a known state, and then restarts normal
10880operation.
10881@xref{Error Recovery}.
10882@end deftypefn
10883
10884@deftypefn  {Function} {protected void} yyerror (String msg)
10885@deftypefnx {Function} {protected void} yyerror (Position pos, String msg)
10886@deftypefnx {Function} {protected void} yyerror (Location loc, String msg)
10887Print an error message using the @code{yyerror} method of the scanner
10888instance in use.
10889@end deftypefn
10890
10891
10892@node Java Differences
10893@subsection Differences between C/C++ and Java Grammars
10894
10895The different structure of the Java language forces several differences
10896between C/C++ grammars, and grammars designed for Java parsers.  This
10897section summarizes these differences.
10898
10899@itemize
10900@item
10901Java lacks a preprocessor, so the @code{YYERROR}, @code{YYACCEPT},
10902@code{YYABORT} symbols (@pxref{Table of Symbols}) cannot obviously be
10903macros.  Instead, they should be preceded by @code{return} when they
10904appear in an action.  The actual definition of these symbols is
10905opaque to the Bison grammar, and it might change in the future.  The
10906only meaningful operation that you can do, is to return them.
10907@xref{Java Action Features}.
10908
10909Note that of these three symbols, only @code{YYACCEPT} and
10910@code{YYABORT} will cause a return from the @code{yyparse}
10911method@footnote{Java parsers include the actions in a separate
10912method than @code{yyparse} in order to have an intuitive syntax that
10913corresponds to these C macros.}.
10914
10915@item
10916Java lacks unions, so @code{%union} has no effect.  Instead, semantic
10917values have a common base type: @code{Object} or as specified by
10918@samp{%define stype}.  Angle brackets on @code{%token}, @code{type},
10919@code{$@var{n}} and @code{$$} specify subtypes rather than fields of
10920an union.  The type of @code{$$}, even with angle brackets, is the base
10921type since Java casts are not allow on the left-hand side of assignments.
10922Also, @code{$@var{n}} and @code{@@@var{n}} are not allowed on the
10923left-hand side of assignments. @xref{Java Semantic Values}, and
10924@ref{Java Action Features}.
10925
10926@item
10927The prologue declarations have a different meaning than in C/C++ code.
10928@table @asis
10929@item @code{%code imports}
10930blocks are placed at the beginning of the Java source code.  They may
10931include copyright notices.  For a @code{package} declarations, it is
10932suggested to use @code{%define package} instead.
10933
10934@item unqualified @code{%code}
10935blocks are placed inside the parser class.
10936
10937@item @code{%code lexer}
10938blocks, if specified, should include the implementation of the
10939scanner.  If there is no such block, the scanner can be any class
10940that implements the appropriate interface (@pxref{Java Scanner
10941Interface}).
10942@end table
10943
10944Other @code{%code} blocks are not supported in Java parsers.
10945In particular, @code{%@{ @dots{} %@}} blocks should not be used
10946and may give an error in future versions of Bison.
10947
10948The epilogue has the same meaning as in C/C++ code and it can
10949be used to define other classes used by the parser @emph{outside}
10950the parser class.
10951@end itemize
10952
10953
10954@node Java Declarations Summary
10955@subsection Java Declarations Summary
10956
10957This summary only include declarations specific to Java or have special
10958meaning when used in a Java parser.
10959
10960@deffn {Directive} {%language "Java"}
10961Generate a Java class for the parser.
10962@end deffn
10963
10964@deffn {Directive} %lex-param @{@var{type} @var{name}@}
10965A parameter for the lexer class defined by @code{%code lexer}
10966@emph{only}, added as parameters to the lexer constructor and the parser
10967constructor that @emph{creates} a lexer.  Default is none.
10968@xref{Java Scanner Interface}.
10969@end deffn
10970
10971@deffn {Directive} %name-prefix "@var{prefix}"
10972The prefix of the parser class name @code{@var{prefix}Parser} if
10973@code{%define parser_class_name} is not used.  Default is @code{YY}.
10974@xref{Java Bison Interface}.
10975@end deffn
10976
10977@deffn {Directive} %parse-param @{@var{type} @var{name}@}
10978A parameter for the parser class added as parameters to constructor(s)
10979and as fields initialized by the constructor(s).  Default is none.
10980@xref{Java Parser Interface}.
10981@end deffn
10982
10983@deffn {Directive} %token <@var{type}> @var{token} @dots{}
10984Declare tokens.  Note that the angle brackets enclose a Java @emph{type}.
10985@xref{Java Semantic Values}.
10986@end deffn
10987
10988@deffn {Directive} %type <@var{type}> @var{nonterminal} @dots{}
10989Declare the type of nonterminals.  Note that the angle brackets enclose
10990a Java @emph{type}.
10991@xref{Java Semantic Values}.
10992@end deffn
10993
10994@deffn {Directive} %code @{ @var{code} @dots{} @}
10995Code appended to the inside of the parser class.
10996@xref{Java Differences}.
10997@end deffn
10998
10999@deffn {Directive} {%code imports} @{ @var{code} @dots{} @}
11000Code inserted just after the @code{package} declaration.
11001@xref{Java Differences}.
11002@end deffn
11003
11004@deffn {Directive} {%code lexer} @{ @var{code} @dots{} @}
11005Code added to the body of a inner lexer class within the parser class.
11006@xref{Java Scanner Interface}.
11007@end deffn
11008
11009@deffn {Directive} %% @var{code} @dots{}
11010Code (after the second @code{%%}) appended to the end of the file,
11011@emph{outside} the parser class.
11012@xref{Java Differences}.
11013@end deffn
11014
11015@deffn {Directive} %@{ @var{code} @dots{} %@}
11016Not supported.  Use @code{%code import} instead.
11017@xref{Java Differences}.
11018@end deffn
11019
11020@deffn {Directive} {%define abstract}
11021Whether the parser class is declared @code{abstract}.  Default is false.
11022@xref{Java Bison Interface}.
11023@end deffn
11024
11025@deffn {Directive} {%define extends} "@var{superclass}"
11026The superclass of the parser class.  Default is none.
11027@xref{Java Bison Interface}.
11028@end deffn
11029
11030@deffn {Directive} {%define final}
11031Whether the parser class is declared @code{final}.  Default is false.
11032@xref{Java Bison Interface}.
11033@end deffn
11034
11035@deffn {Directive} {%define implements} "@var{interfaces}"
11036The implemented interfaces of the parser class, a comma-separated list.
11037Default is none.
11038@xref{Java Bison Interface}.
11039@end deffn
11040
11041@deffn {Directive} {%define lex_throws} "@var{exceptions}"
11042The exceptions thrown by the @code{yylex} method of the lexer, a
11043comma-separated list.  Default is @code{java.io.IOException}.
11044@xref{Java Scanner Interface}.
11045@end deffn
11046
11047@deffn {Directive} {%define api.location.type} "@var{class}"
11048The name of the class used for locations (a range between two
11049positions).  This class is generated as an inner class of the parser
11050class by @command{bison}.  Default is @code{Location}.
11051Formerly named @code{location_type}.
11052@xref{Java Location Values}.
11053@end deffn
11054
11055@deffn {Directive} {%define package} "@var{package}"
11056The package to put the parser class in.  Default is none.
11057@xref{Java Bison Interface}.
11058@end deffn
11059
11060@deffn {Directive} {%define parser_class_name} "@var{name}"
11061The name of the parser class.  Default is @code{YYParser} or
11062@code{@var{name-prefix}Parser}.
11063@xref{Java Bison Interface}.
11064@end deffn
11065
11066@deffn {Directive} {%define api.position.type} "@var{class}"
11067The name of the class used for positions. This class must be supplied by
11068the user.  Default is @code{Position}.
11069Formerly named @code{position_type}.
11070@xref{Java Location Values}.
11071@end deffn
11072
11073@deffn {Directive} {%define public}
11074Whether the parser class is declared @code{public}.  Default is false.
11075@xref{Java Bison Interface}.
11076@end deffn
11077
11078@deffn {Directive} {%define stype} "@var{class}"
11079The base type of semantic values.  Default is @code{Object}.
11080@xref{Java Semantic Values}.
11081@end deffn
11082
11083@deffn {Directive} {%define strictfp}
11084Whether the parser class is declared @code{strictfp}.  Default is false.
11085@xref{Java Bison Interface}.
11086@end deffn
11087
11088@deffn {Directive} {%define throws} "@var{exceptions}"
11089The exceptions thrown by user-supplied parser actions and
11090@code{%initial-action}, a comma-separated list.  Default is none.
11091@xref{Java Parser Interface}.
11092@end deffn
11093
11094
11095@c ================================================= FAQ
11096
11097@node FAQ
11098@chapter Frequently Asked Questions
11099@cindex frequently asked questions
11100@cindex questions
11101
11102Several questions about Bison come up occasionally.  Here some of them
11103are addressed.
11104
11105@menu
11106* Memory Exhausted::            Breaking the Stack Limits
11107* How Can I Reset the Parser::  @code{yyparse} Keeps some State
11108* Strings are Destroyed::       @code{yylval} Loses Track of Strings
11109* Implementing Gotos/Loops::    Control Flow in the Calculator
11110* Multiple start-symbols::      Factoring closely related grammars
11111* Secure?  Conform?::           Is Bison POSIX safe?
11112* I can't build Bison::         Troubleshooting
11113* Where can I find help?::      Troubleshouting
11114* Bug Reports::                 Troublereporting
11115* More Languages::              Parsers in C++, Java, and so on
11116* Beta Testing::                Experimenting development versions
11117* Mailing Lists::               Meeting other Bison users
11118@end menu
11119
11120@node Memory Exhausted
11121@section Memory Exhausted
11122
11123@quotation
11124My parser returns with error with a @samp{memory exhausted}
11125message.  What can I do?
11126@end quotation
11127
11128This question is already addressed elsewhere, see @ref{Recursion, ,Recursive
11129Rules}.
11130
11131@node How Can I Reset the Parser
11132@section How Can I Reset the Parser
11133
11134The following phenomenon has several symptoms, resulting in the
11135following typical questions:
11136
11137@quotation
11138I invoke @code{yyparse} several times, and on correct input it works
11139properly; but when a parse error is found, all the other calls fail
11140too.  How can I reset the error flag of @code{yyparse}?
11141@end quotation
11142
11143@noindent
11144or
11145
11146@quotation
11147My parser includes support for an @samp{#include}-like feature, in
11148which case I run @code{yyparse} from @code{yyparse}.  This fails
11149although I did specify @samp{%define api.pure full}.
11150@end quotation
11151
11152These problems typically come not from Bison itself, but from
11153Lex-generated scanners.  Because these scanners use large buffers for
11154speed, they might not notice a change of input file.  As a
11155demonstration, consider the following source file,
11156@file{first-line.l}:
11157
11158@example
11159@group
11160%@{
11161#include <stdio.h>
11162#include <stdlib.h>
11163%@}
11164@end group
11165%%
11166.*\n    ECHO; return 1;
11167%%
11168@group
11169int
11170yyparse (char const *file)
11171@{
11172  yyin = fopen (file, "r");
11173  if (!yyin)
11174    @{
11175      perror ("fopen");
11176      exit (EXIT_FAILURE);
11177    @}
11178@end group
11179@group
11180  /* One token only.  */
11181  yylex ();
11182  if (fclose (yyin) != 0)
11183    @{
11184      perror ("fclose");
11185      exit (EXIT_FAILURE);
11186    @}
11187  return 0;
11188@}
11189@end group
11190
11191@group
11192int
11193main (void)
11194@{
11195  yyparse ("input");
11196  yyparse ("input");
11197  return 0;
11198@}
11199@end group
11200@end example
11201
11202@noindent
11203If the file @file{input} contains
11204
11205@example
11206input:1: Hello,
11207input:2: World!
11208@end example
11209
11210@noindent
11211then instead of getting the first line twice, you get:
11212
11213@example
11214$ @kbd{flex -ofirst-line.c first-line.l}
11215$ @kbd{gcc  -ofirst-line   first-line.c -ll}
11216$ @kbd{./first-line}
11217input:1: Hello,
11218input:2: World!
11219@end example
11220
11221Therefore, whenever you change @code{yyin}, you must tell the
11222Lex-generated scanner to discard its current buffer and switch to the
11223new one.  This depends upon your implementation of Lex; see its
11224documentation for more.  For Flex, it suffices to call
11225@samp{YY_FLUSH_BUFFER} after each change to @code{yyin}.  If your
11226Flex-generated scanner needs to read from several input streams to
11227handle features like include files, you might consider using Flex
11228functions like @samp{yy_switch_to_buffer} that manipulate multiple
11229input buffers.
11230
11231If your Flex-generated scanner uses start conditions (@pxref{Start
11232conditions, , Start conditions, flex, The Flex Manual}), you might
11233also want to reset the scanner's state, i.e., go back to the initial
11234start condition, through a call to @samp{BEGIN (0)}.
11235
11236@node Strings are Destroyed
11237@section Strings are Destroyed
11238
11239@quotation
11240My parser seems to destroy old strings, or maybe it loses track of
11241them.  Instead of reporting @samp{"foo", "bar"}, it reports
11242@samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
11243@end quotation
11244
11245This error is probably the single most frequent ``bug report'' sent to
11246Bison lists, but is only concerned with a misunderstanding of the role
11247of the scanner.  Consider the following Lex code:
11248
11249@example
11250@group
11251%@{
11252#include <stdio.h>
11253char *yylval = NULL;
11254%@}
11255@end group
11256@group
11257%%
11258.*    yylval = yytext; return 1;
11259\n    /* IGNORE */
11260%%
11261@end group
11262@group
11263int
11264main ()
11265@{
11266  /* Similar to using $1, $2 in a Bison action.  */
11267  char *fst = (yylex (), yylval);
11268  char *snd = (yylex (), yylval);
11269  printf ("\"%s\", \"%s\"\n", fst, snd);
11270  return 0;
11271@}
11272@end group
11273@end example
11274
11275If you compile and run this code, you get:
11276
11277@example
11278$ @kbd{flex -osplit-lines.c split-lines.l}
11279$ @kbd{gcc  -osplit-lines   split-lines.c -ll}
11280$ @kbd{printf 'one\ntwo\n' | ./split-lines}
11281"one
11282two", "two"
11283@end example
11284
11285@noindent
11286this is because @code{yytext} is a buffer provided for @emph{reading}
11287in the action, but if you want to keep it, you have to duplicate it
11288(e.g., using @code{strdup}).  Note that the output may depend on how
11289your implementation of Lex handles @code{yytext}.  For instance, when
11290given the Lex compatibility option @option{-l} (which triggers the
11291option @samp{%array}) Flex generates a different behavior:
11292
11293@example
11294$ @kbd{flex -l -osplit-lines.c split-lines.l}
11295$ @kbd{gcc     -osplit-lines   split-lines.c -ll}
11296$ @kbd{printf 'one\ntwo\n' | ./split-lines}
11297"two", "two"
11298@end example
11299
11300
11301@node Implementing Gotos/Loops
11302@section Implementing Gotos/Loops
11303
11304@quotation
11305My simple calculator supports variables, assignments, and functions,
11306but how can I implement gotos, or loops?
11307@end quotation
11308
11309Although very pedagogical, the examples included in the document blur
11310the distinction to make between the parser---whose job is to recover
11311the structure of a text and to transmit it to subsequent modules of
11312the program---and the processing (such as the execution) of this
11313structure.  This works well with so called straight line programs,
11314i.e., precisely those that have a straightforward execution model:
11315execute simple instructions one after the others.
11316
11317@cindex abstract syntax tree
11318@cindex AST
11319If you want a richer model, you will probably need to use the parser
11320to construct a tree that does represent the structure it has
11321recovered; this tree is usually called the @dfn{abstract syntax tree},
11322or @dfn{AST} for short.  Then, walking through this tree,
11323traversing it in various ways, will enable treatments such as its
11324execution or its translation, which will result in an interpreter or a
11325compiler.
11326
11327This topic is way beyond the scope of this manual, and the reader is
11328invited to consult the dedicated literature.
11329
11330
11331@node Multiple start-symbols
11332@section Multiple start-symbols
11333
11334@quotation
11335I have several closely related grammars, and I would like to share their
11336implementations.  In fact, I could use a single grammar but with
11337multiple entry points.
11338@end quotation
11339
11340Bison does not support multiple start-symbols, but there is a very
11341simple means to simulate them.  If @code{foo} and @code{bar} are the two
11342pseudo start-symbols, then introduce two new tokens, say
11343@code{START_FOO} and @code{START_BAR}, and use them as switches from the
11344real start-symbol:
11345
11346@example
11347%token START_FOO START_BAR;
11348%start start;
11349start:
11350  START_FOO foo
11351| START_BAR bar;
11352@end example
11353
11354These tokens prevents the introduction of new conflicts.  As far as the
11355parser goes, that is all that is needed.
11356
11357Now the difficult part is ensuring that the scanner will send these
11358tokens first.  If your scanner is hand-written, that should be
11359straightforward.  If your scanner is generated by Lex, them there is
11360simple means to do it: recall that anything between @samp{%@{ ... %@}}
11361after the first @code{%%} is copied verbatim in the top of the generated
11362@code{yylex} function.  Make sure a variable @code{start_token} is
11363available in the scanner (e.g., a global variable or using
11364@code{%lex-param} etc.), and use the following:
11365
11366@example
11367  /* @r{Prologue.}  */
11368%%
11369%@{
11370  if (start_token)
11371    @{
11372      int t = start_token;
11373      start_token = 0;
11374      return t;
11375    @}
11376%@}
11377  /* @r{The rules.}  */
11378@end example
11379
11380
11381@node Secure?  Conform?
11382@section Secure?  Conform?
11383
11384@quotation
11385Is Bison secure?  Does it conform to POSIX?
11386@end quotation
11387
11388If you're looking for a guarantee or certification, we don't provide it.
11389However, Bison is intended to be a reliable program that conforms to the
11390POSIX specification for Yacc.  If you run into problems,
11391please send us a bug report.
11392
11393@node I can't build Bison
11394@section I can't build Bison
11395
11396@quotation
11397I can't build Bison because @command{make} complains that
11398@code{msgfmt} is not found.
11399What should I do?
11400@end quotation
11401
11402Like most GNU packages with internationalization support, that feature
11403is turned on by default.  If you have problems building in the @file{po}
11404subdirectory, it indicates that your system's internationalization
11405support is lacking.  You can re-configure Bison with
11406@option{--disable-nls} to turn off this support, or you can install GNU
11407gettext from @url{ftp://ftp.gnu.org/gnu/gettext/} and re-configure
11408Bison.  See the file @file{ABOUT-NLS} for more information.
11409
11410
11411@node Where can I find help?
11412@section Where can I find help?
11413
11414@quotation
11415I'm having trouble using Bison.  Where can I find help?
11416@end quotation
11417
11418First, read this fine manual.  Beyond that, you can send mail to
11419@email{help-bison@@gnu.org}.  This mailing list is intended to be
11420populated with people who are willing to answer questions about using
11421and installing Bison.  Please keep in mind that (most of) the people on
11422the list have aspects of their lives which are not related to Bison (!),
11423so you may not receive an answer to your question right away.  This can
11424be frustrating, but please try not to honk them off; remember that any
11425help they provide is purely voluntary and out of the kindness of their
11426hearts.
11427
11428@node Bug Reports
11429@section Bug Reports
11430
11431@quotation
11432I found a bug.  What should I include in the bug report?
11433@end quotation
11434
11435Before you send a bug report, make sure you are using the latest
11436version.  Check @url{ftp://ftp.gnu.org/pub/gnu/bison/} or one of its
11437mirrors.  Be sure to include the version number in your bug report.  If
11438the bug is present in the latest version but not in a previous version,
11439try to determine the most recent version which did not contain the bug.
11440
11441If the bug is parser-related, you should include the smallest grammar
11442you can which demonstrates the bug.  The grammar file should also be
11443complete (i.e., I should be able to run it through Bison without having
11444to edit or add anything).  The smaller and simpler the grammar, the
11445easier it will be to fix the bug.
11446
11447Include information about your compilation environment, including your
11448operating system's name and version and your compiler's name and
11449version.  If you have trouble compiling, you should also include a
11450transcript of the build session, starting with the invocation of
11451`configure'.  Depending on the nature of the bug, you may be asked to
11452send additional files as well (such as `config.h' or `config.cache').
11453
11454Patches are most welcome, but not required.  That is, do not hesitate to
11455send a bug report just because you cannot provide a fix.
11456
11457Send bug reports to @email{bug-bison@@gnu.org}.
11458
11459@node More Languages
11460@section More Languages
11461
11462@quotation
11463Will Bison ever have C++ and Java support?  How about @var{insert your
11464favorite language here}?
11465@end quotation
11466
11467C++ and Java support is there now, and is documented.  We'd love to add other
11468languages; contributions are welcome.
11469
11470@node Beta Testing
11471@section Beta Testing
11472
11473@quotation
11474What is involved in being a beta tester?
11475@end quotation
11476
11477It's not terribly involved.  Basically, you would download a test
11478release, compile it, and use it to build and run a parser or two.  After
11479that, you would submit either a bug report or a message saying that
11480everything is okay.  It is important to report successes as well as
11481failures because test releases eventually become mainstream releases,
11482but only if they are adequately tested.  If no one tests, development is
11483essentially halted.
11484
11485Beta testers are particularly needed for operating systems to which the
11486developers do not have easy access.  They currently have easy access to
11487recent GNU/Linux and Solaris versions.  Reports about other operating
11488systems are especially welcome.
11489
11490@node Mailing Lists
11491@section Mailing Lists
11492
11493@quotation
11494How do I join the help-bison and bug-bison mailing lists?
11495@end quotation
11496
11497See @url{http://lists.gnu.org/}.
11498
11499@c ================================================= Table of Symbols
11500
11501@node Table of Symbols
11502@appendix Bison Symbols
11503@cindex Bison symbols, table of
11504@cindex symbols in Bison, table of
11505
11506@deffn {Variable} @@$
11507In an action, the location of the left-hand side of the rule.
11508@xref{Tracking Locations}.
11509@end deffn
11510
11511@deffn {Variable} @@@var{n}
11512@deffnx {Symbol} @@@var{n}
11513In an action, the location of the @var{n}-th symbol of the right-hand side
11514of the rule.  @xref{Tracking Locations}.
11515
11516In a grammar, the Bison-generated nonterminal symbol for a mid-rule action
11517with a semantical value.  @xref{Mid-Rule Action Translation}.
11518@end deffn
11519
11520@deffn {Variable} @@@var{name}
11521@deffnx {Variable} @@[@var{name}]
11522In an action, the location of a symbol addressed by @var{name}.
11523@xref{Tracking Locations}.
11524@end deffn
11525
11526@deffn {Symbol} $@@@var{n}
11527In a grammar, the Bison-generated nonterminal symbol for a mid-rule action
11528with no semantical value.  @xref{Mid-Rule Action Translation}.
11529@end deffn
11530
11531@deffn {Variable} $$
11532In an action, the semantic value of the left-hand side of the rule.
11533@xref{Actions}.
11534@end deffn
11535
11536@deffn {Variable} $@var{n}
11537In an action, the semantic value of the @var{n}-th symbol of the
11538right-hand side of the rule.  @xref{Actions}.
11539@end deffn
11540
11541@deffn {Variable} $@var{name}
11542@deffnx {Variable} $[@var{name}]
11543In an action, the semantic value of a symbol addressed by @var{name}.
11544@xref{Actions}.
11545@end deffn
11546
11547@deffn {Delimiter} %%
11548Delimiter used to separate the grammar rule section from the
11549Bison declarations section or the epilogue.
11550@xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
11551@end deffn
11552
11553@c Don't insert spaces, or check the DVI output.
11554@deffn {Delimiter} %@{@var{code}%@}
11555All code listed between @samp{%@{} and @samp{%@}} is copied verbatim
11556to the parser implementation file.  Such code forms the prologue of
11557the grammar file.  @xref{Grammar Outline, ,Outline of a Bison
11558Grammar}.
11559@end deffn
11560
11561@deffn {Construct} /* @dots{} */
11562@deffnx {Construct} // @dots{}
11563Comments, as in C/C++.
11564@end deffn
11565
11566@deffn {Delimiter} :
11567Separates a rule's result from its components.  @xref{Rules, ,Syntax of
11568Grammar Rules}.
11569@end deffn
11570
11571@deffn {Delimiter} ;
11572Terminates a rule.  @xref{Rules, ,Syntax of Grammar Rules}.
11573@end deffn
11574
11575@deffn {Delimiter} |
11576Separates alternate rules for the same result nonterminal.
11577@xref{Rules, ,Syntax of Grammar Rules}.
11578@end deffn
11579
11580@deffn {Directive} <*>
11581Used to define a default tagged @code{%destructor} or default tagged
11582@code{%printer}.
11583
11584This feature is experimental.
11585More user feedback will help to determine whether it should become a permanent
11586feature.
11587
11588@xref{Destructor Decl, , Freeing Discarded Symbols}.
11589@end deffn
11590
11591@deffn {Directive} <>
11592Used to define a default tagless @code{%destructor} or default tagless
11593@code{%printer}.
11594
11595This feature is experimental.
11596More user feedback will help to determine whether it should become a permanent
11597feature.
11598
11599@xref{Destructor Decl, , Freeing Discarded Symbols}.
11600@end deffn
11601
11602@deffn {Symbol} $accept
11603The predefined nonterminal whose only rule is @samp{$accept: @var{start}
11604$end}, where @var{start} is the start symbol.  @xref{Start Decl, , The
11605Start-Symbol}.  It cannot be used in the grammar.
11606@end deffn
11607
11608@deffn {Directive} %code @{@var{code}@}
11609@deffnx {Directive} %code @var{qualifier} @{@var{code}@}
11610Insert @var{code} verbatim into the output parser source at the
11611default location or at the location specified by @var{qualifier}.
11612@xref{%code Summary}.
11613@end deffn
11614
11615@deffn {Directive} %debug
11616Equip the parser for debugging.  @xref{Decl Summary}.
11617@end deffn
11618
11619@ifset defaultprec
11620@deffn {Directive} %default-prec
11621Assign a precedence to rules that lack an explicit @samp{%prec}
11622modifier.  @xref{Contextual Precedence, ,Context-Dependent
11623Precedence}.
11624@end deffn
11625@end ifset
11626
11627@deffn {Directive} %define @var{variable}
11628@deffnx {Directive} %define @var{variable} @var{value}
11629@deffnx {Directive} %define @var{variable} "@var{value}"
11630Define a variable to adjust Bison's behavior.  @xref{%define Summary}.
11631@end deffn
11632
11633@deffn {Directive} %defines
11634Bison declaration to create a parser header file, which is usually
11635meant for the scanner.  @xref{Decl Summary}.
11636@end deffn
11637
11638@deffn {Directive} %defines @var{defines-file}
11639Same as above, but save in the file @var{defines-file}.
11640@xref{Decl Summary}.
11641@end deffn
11642
11643@deffn {Directive} %destructor
11644Specify how the parser should reclaim the memory associated to
11645discarded symbols.  @xref{Destructor Decl, , Freeing Discarded Symbols}.
11646@end deffn
11647
11648@deffn {Directive} %dprec
11649Bison declaration to assign a precedence to a rule that is used at parse
11650time to resolve reduce/reduce conflicts.  @xref{GLR Parsers, ,Writing
11651GLR Parsers}.
11652@end deffn
11653
11654@deffn {Symbol} $end
11655The predefined token marking the end of the token stream.  It cannot be
11656used in the grammar.
11657@end deffn
11658
11659@deffn {Symbol} error
11660A token name reserved for error recovery.  This token may be used in
11661grammar rules so as to allow the Bison parser to recognize an error in
11662the grammar without halting the process.  In effect, a sentence
11663containing an error may be recognized as valid.  On a syntax error, the
11664token @code{error} becomes the current lookahead token.  Actions
11665corresponding to @code{error} are then executed, and the lookahead
11666token is reset to the token that originally caused the violation.
11667@xref{Error Recovery}.
11668@end deffn
11669
11670@deffn {Directive} %error-verbose
11671Bison declaration to request verbose, specific error message strings
11672when @code{yyerror} is called.  @xref{Error Reporting}.
11673@end deffn
11674
11675@deffn {Directive} %file-prefix "@var{prefix}"
11676Bison declaration to set the prefix of the output files.  @xref{Decl
11677Summary}.
11678@end deffn
11679
11680@deffn {Directive} %glr-parser
11681Bison declaration to produce a GLR parser.  @xref{GLR
11682Parsers, ,Writing GLR Parsers}.
11683@end deffn
11684
11685@deffn {Directive} %initial-action
11686Run user code before parsing.  @xref{Initial Action Decl, , Performing Actions before Parsing}.
11687@end deffn
11688
11689@deffn {Directive} %language
11690Specify the programming language for the generated parser.
11691@xref{Decl Summary}.
11692@end deffn
11693
11694@deffn {Directive} %left
11695Bison declaration to assign left associativity to token(s).
11696@xref{Precedence Decl, ,Operator Precedence}.
11697@end deffn
11698
11699@deffn {Directive} %lex-param @{@var{argument-declaration}@}
11700Bison declaration to specifying an additional parameter that
11701@code{yylex} should accept.  @xref{Pure Calling,, Calling Conventions
11702for Pure Parsers}.
11703@end deffn
11704
11705@deffn {Directive} %merge
11706Bison declaration to assign a merging function to a rule.  If there is a
11707reduce/reduce conflict with a rule having the same merging function, the
11708function is applied to the two semantic values to get a single result.
11709@xref{GLR Parsers, ,Writing GLR Parsers}.
11710@end deffn
11711
11712@deffn {Directive} %name-prefix "@var{prefix}"
11713Obsoleted by the @code{%define} variable @code{api.prefix} (@pxref{Multiple
11714Parsers, ,Multiple Parsers in the Same Program}).
11715
11716Rename the external symbols (variables and functions) used in the parser so
11717that they start with @var{prefix} instead of @samp{yy}.  Contrary to
11718@code{api.prefix}, do no rename types and macros.
11719
11720The precise list of symbols renamed in C parsers is @code{yyparse},
11721@code{yylex}, @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yychar},
11722@code{yydebug}, and (if locations are used) @code{yylloc}.  If you use a
11723push parser, @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
11724@code{yypstate_new} and @code{yypstate_delete} will also be renamed.  For
11725example, if you use @samp{%name-prefix "c_"}, the names become
11726@code{c_parse}, @code{c_lex}, and so on.  For C++ parsers, see the
11727@code{%define namespace} documentation in this section.
11728@end deffn
11729
11730
11731@ifset defaultprec
11732@deffn {Directive} %no-default-prec
11733Do not assign a precedence to rules that lack an explicit @samp{%prec}
11734modifier.  @xref{Contextual Precedence, ,Context-Dependent
11735Precedence}.
11736@end deffn
11737@end ifset
11738
11739@deffn {Directive} %no-lines
11740Bison declaration to avoid generating @code{#line} directives in the
11741parser implementation file.  @xref{Decl Summary}.
11742@end deffn
11743
11744@deffn {Directive} %nonassoc
11745Bison declaration to assign nonassociativity to token(s).
11746@xref{Precedence Decl, ,Operator Precedence}.
11747@end deffn
11748
11749@deffn {Directive} %output "@var{file}"
11750Bison declaration to set the name of the parser implementation file.
11751@xref{Decl Summary}.
11752@end deffn
11753
11754@deffn {Directive} %parse-param @{@var{argument-declaration}@}
11755Bison declaration to specifying an additional parameter that
11756@code{yyparse} should accept.  @xref{Parser Function,, The Parser
11757Function @code{yyparse}}.
11758@end deffn
11759
11760@deffn {Directive} %prec
11761Bison declaration to assign a precedence to a specific rule.
11762@xref{Contextual Precedence, ,Context-Dependent Precedence}.
11763@end deffn
11764
11765@deffn {Directive} %pure-parser
11766Deprecated version of @code{%define api.pure} (@pxref{%define
11767Summary,,api.pure}), for which Bison is more careful to warn about
11768unreasonable usage.
11769@end deffn
11770
11771@deffn {Directive} %require "@var{version}"
11772Require version @var{version} or higher of Bison.  @xref{Require Decl, ,
11773Require a Version of Bison}.
11774@end deffn
11775
11776@deffn {Directive} %right
11777Bison declaration to assign right associativity to token(s).
11778@xref{Precedence Decl, ,Operator Precedence}.
11779@end deffn
11780
11781@deffn {Directive} %skeleton
11782Specify the skeleton to use; usually for development.
11783@xref{Decl Summary}.
11784@end deffn
11785
11786@deffn {Directive} %start
11787Bison declaration to specify the start symbol.  @xref{Start Decl, ,The
11788Start-Symbol}.
11789@end deffn
11790
11791@deffn {Directive} %token
11792Bison declaration to declare token(s) without specifying precedence.
11793@xref{Token Decl, ,Token Type Names}.
11794@end deffn
11795
11796@deffn {Directive} %token-table
11797Bison declaration to include a token name table in the parser
11798implementation file.  @xref{Decl Summary}.
11799@end deffn
11800
11801@deffn {Directive} %type
11802Bison declaration to declare nonterminals.  @xref{Type Decl,
11803,Nonterminal Symbols}.
11804@end deffn
11805
11806@deffn {Symbol} $undefined
11807The predefined token onto which all undefined values returned by
11808@code{yylex} are mapped.  It cannot be used in the grammar, rather, use
11809@code{error}.
11810@end deffn
11811
11812@deffn {Directive} %union
11813Bison declaration to specify several possible data types for semantic
11814values.  @xref{Union Decl, ,The Collection of Value Types}.
11815@end deffn
11816
11817@deffn {Macro} YYABORT
11818Macro to pretend that an unrecoverable syntax error has occurred, by
11819making @code{yyparse} return 1 immediately.  The error reporting
11820function @code{yyerror} is not called.  @xref{Parser Function, ,The
11821Parser Function @code{yyparse}}.
11822
11823For Java parsers, this functionality is invoked using @code{return YYABORT;}
11824instead.
11825@end deffn
11826
11827@deffn {Macro} YYACCEPT
11828Macro to pretend that a complete utterance of the language has been
11829read, by making @code{yyparse} return 0 immediately.
11830@xref{Parser Function, ,The Parser Function @code{yyparse}}.
11831
11832For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
11833instead.
11834@end deffn
11835
11836@deffn {Macro} YYBACKUP
11837Macro to discard a value from the parser stack and fake a lookahead
11838token.  @xref{Action Features, ,Special Features for Use in Actions}.
11839@end deffn
11840
11841@deffn {Variable} yychar
11842External integer variable that contains the integer value of the
11843lookahead token.  (In a pure parser, it is a local variable within
11844@code{yyparse}.)  Error-recovery rule actions may examine this variable.
11845@xref{Action Features, ,Special Features for Use in Actions}.
11846@end deffn
11847
11848@deffn {Variable} yyclearin
11849Macro used in error-recovery rule actions.  It clears the previous
11850lookahead token.  @xref{Error Recovery}.
11851@end deffn
11852
11853@deffn {Macro} YYDEBUG
11854Macro to define to equip the parser with tracing code.  @xref{Tracing,
11855,Tracing Your Parser}.
11856@end deffn
11857
11858@deffn {Variable} yydebug
11859External integer variable set to zero by default.  If @code{yydebug}
11860is given a nonzero value, the parser will output information on input
11861symbols and parser action.  @xref{Tracing, ,Tracing Your Parser}.
11862@end deffn
11863
11864@deffn {Macro} yyerrok
11865Macro to cause parser to recover immediately to its normal mode
11866after a syntax error.  @xref{Error Recovery}.
11867@end deffn
11868
11869@deffn {Macro} YYERROR
11870Cause an immediate syntax error.  This statement initiates error
11871recovery just as if the parser itself had detected an error; however, it
11872does not call @code{yyerror}, and does not print any message.  If you
11873want to print an error message, call @code{yyerror} explicitly before
11874the @samp{YYERROR;} statement.  @xref{Error Recovery}.
11875
11876For Java parsers, this functionality is invoked using @code{return YYERROR;}
11877instead.
11878@end deffn
11879
11880@deffn {Function} yyerror
11881User-supplied function to be called by @code{yyparse} on error.
11882@xref{Error Reporting, ,The Error
11883Reporting Function @code{yyerror}}.
11884@end deffn
11885
11886@deffn {Macro} YYERROR_VERBOSE
11887An obsolete macro that you define with @code{#define} in the prologue
11888to request verbose, specific error message strings
11889when @code{yyerror} is called.  It doesn't matter what definition you
11890use for @code{YYERROR_VERBOSE}, just whether you define it.
11891Supported by the C skeletons only; using
11892@code{%error-verbose} is preferred.  @xref{Error Reporting}.
11893@end deffn
11894
11895@deffn {Macro} YYFPRINTF
11896Macro used to output run-time traces.
11897@xref{Enabling Traces}.
11898@end deffn
11899
11900@deffn {Macro} YYINITDEPTH
11901Macro for specifying the initial size of the parser stack.
11902@xref{Memory Management}.
11903@end deffn
11904
11905@deffn {Function} yylex
11906User-supplied lexical analyzer function, called with no arguments to get
11907the next token.  @xref{Lexical, ,The Lexical Analyzer Function
11908@code{yylex}}.
11909@end deffn
11910
11911@deffn {Macro} YYLEX_PARAM
11912An obsolete macro for specifying an extra argument (or list of extra
11913arguments) for @code{yyparse} to pass to @code{yylex}.  The use of this
11914macro is deprecated, and is supported only for Yacc like parsers.
11915@xref{Pure Calling,, Calling Conventions for Pure Parsers}.
11916@end deffn
11917
11918@deffn {Variable} yylloc
11919External variable in which @code{yylex} should place the line and column
11920numbers associated with a token.  (In a pure parser, it is a local
11921variable within @code{yyparse}, and its address is passed to
11922@code{yylex}.)
11923You can ignore this variable if you don't use the @samp{@@} feature in the
11924grammar actions.
11925@xref{Token Locations, ,Textual Locations of Tokens}.
11926In semantic actions, it stores the location of the lookahead token.
11927@xref{Actions and Locations, ,Actions and Locations}.
11928@end deffn
11929
11930@deffn {Type} YYLTYPE
11931Data type of @code{yylloc}; by default, a structure with four
11932members.  @xref{Location Type, , Data Types of Locations}.
11933@end deffn
11934
11935@deffn {Variable} yylval
11936External variable in which @code{yylex} should place the semantic
11937value associated with a token.  (In a pure parser, it is a local
11938variable within @code{yyparse}, and its address is passed to
11939@code{yylex}.)
11940@xref{Token Values, ,Semantic Values of Tokens}.
11941In semantic actions, it stores the semantic value of the lookahead token.
11942@xref{Actions, ,Actions}.
11943@end deffn
11944
11945@deffn {Macro} YYMAXDEPTH
11946Macro for specifying the maximum size of the parser stack.  @xref{Memory
11947Management}.
11948@end deffn
11949
11950@deffn {Variable} yynerrs
11951Global variable which Bison increments each time it reports a syntax error.
11952(In a pure parser, it is a local variable within @code{yyparse}. In a
11953pure push parser, it is a member of yypstate.)
11954@xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
11955@end deffn
11956
11957@deffn {Function} yyparse
11958The parser function produced by Bison; call this function to start
11959parsing.  @xref{Parser Function, ,The Parser Function @code{yyparse}}.
11960@end deffn
11961
11962@deffn {Macro} YYPRINT
11963Macro used to output token semantic values.  For @file{yacc.c} only.
11964Obsoleted by @code{%printer}.
11965@xref{The YYPRINT Macro, , The @code{YYPRINT} Macro}.
11966@end deffn
11967
11968@deffn {Function} yypstate_delete
11969The function to delete a parser instance, produced by Bison in push mode;
11970call this function to delete the memory associated with a parser.
11971@xref{Parser Delete Function, ,The Parser Delete Function
11972@code{yypstate_delete}}.
11973(The current push parsing interface is experimental and may evolve.
11974More user feedback will help to stabilize it.)
11975@end deffn
11976
11977@deffn {Function} yypstate_new
11978The function to create a parser instance, produced by Bison in push mode;
11979call this function to create a new parser.
11980@xref{Parser Create Function, ,The Parser Create Function
11981@code{yypstate_new}}.
11982(The current push parsing interface is experimental and may evolve.
11983More user feedback will help to stabilize it.)
11984@end deffn
11985
11986@deffn {Function} yypull_parse
11987The parser function produced by Bison in push mode; call this function to
11988parse the rest of the input stream.
11989@xref{Pull Parser Function, ,The Pull Parser Function
11990@code{yypull_parse}}.
11991(The current push parsing interface is experimental and may evolve.
11992More user feedback will help to stabilize it.)
11993@end deffn
11994
11995@deffn {Function} yypush_parse
11996The parser function produced by Bison in push mode; call this function to
11997parse a single token.  @xref{Push Parser Function, ,The Push Parser Function
11998@code{yypush_parse}}.
11999(The current push parsing interface is experimental and may evolve.
12000More user feedback will help to stabilize it.)
12001@end deffn
12002
12003@deffn {Macro} YYPARSE_PARAM
12004An obsolete macro for specifying the name of a parameter that
12005@code{yyparse} should accept.  The use of this macro is deprecated, and
12006is supported only for Yacc like parsers.  @xref{Pure Calling,, Calling
12007Conventions for Pure Parsers}.
12008@end deffn
12009
12010@deffn {Macro} YYRECOVERING
12011The expression @code{YYRECOVERING ()} yields 1 when the parser
12012is recovering from a syntax error, and 0 otherwise.
12013@xref{Action Features, ,Special Features for Use in Actions}.
12014@end deffn
12015
12016@deffn {Macro} YYSTACK_USE_ALLOCA
12017Macro used to control the use of @code{alloca} when the
12018deterministic parser in C needs to extend its stacks.  If defined to 0,
12019the parser will use @code{malloc} to extend its stacks.  If defined to
120201, the parser will use @code{alloca}.  Values other than 0 and 1 are
12021reserved for future Bison extensions.  If not defined,
12022@code{YYSTACK_USE_ALLOCA} defaults to 0.
12023
12024In the all-too-common case where your code may run on a host with a
12025limited stack and with unreliable stack-overflow checking, you should
12026set @code{YYMAXDEPTH} to a value that cannot possibly result in
12027unchecked stack overflow on any of your target hosts when
12028@code{alloca} is called.  You can inspect the code that Bison
12029generates in order to determine the proper numeric values.  This will
12030require some expertise in low-level implementation details.
12031@end deffn
12032
12033@deffn {Type} YYSTYPE
12034Data type of semantic values; @code{int} by default.
12035@xref{Value Type, ,Data Types of Semantic Values}.
12036@end deffn
12037
12038@node Glossary
12039@appendix Glossary
12040@cindex glossary
12041
12042@table @asis
12043@item Accepting state
12044A state whose only action is the accept action.
12045The accepting state is thus a consistent state.
12046@xref{Understanding, ,Understanding Your Parser}.
12047
12048@item Backus-Naur Form (BNF; also called ``Backus Normal Form'')
12049Formal method of specifying context-free grammars originally proposed
12050by John Backus, and slightly improved by Peter Naur in his 1960-01-02
12051committee document contributing to what became the Algol 60 report.
12052@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
12053
12054@item Consistent state
12055A state containing only one possible action.  @xref{Default Reductions}.
12056
12057@item Context-free grammars
12058Grammars specified as rules that can be applied regardless of context.
12059Thus, if there is a rule which says that an integer can be used as an
12060expression, integers are allowed @emph{anywhere} an expression is
12061permitted.  @xref{Language and Grammar, ,Languages and Context-Free
12062Grammars}.
12063
12064@item Default reduction
12065The reduction that a parser should perform if the current parser state
12066contains no other action for the lookahead token.  In permitted parser
12067states, Bison declares the reduction with the largest lookahead set to be
12068the default reduction and removes that lookahead set.  @xref{Default
12069Reductions}.
12070
12071@item Defaulted state
12072A consistent state with a default reduction.  @xref{Default Reductions}.
12073
12074@item Dynamic allocation
12075Allocation of memory that occurs during execution, rather than at
12076compile time or on entry to a function.
12077
12078@item Empty string
12079Analogous to the empty set in set theory, the empty string is a
12080character string of length zero.
12081
12082@item Finite-state stack machine
12083A ``machine'' that has discrete states in which it is said to exist at
12084each instant in time.  As input to the machine is processed, the
12085machine moves from state to state as specified by the logic of the
12086machine.  In the case of the parser, the input is the language being
12087parsed, and the states correspond to various stages in the grammar
12088rules.  @xref{Algorithm, ,The Bison Parser Algorithm}.
12089
12090@item Generalized LR (GLR)
12091A parsing algorithm that can handle all context-free grammars, including those
12092that are not LR(1).  It resolves situations that Bison's
12093deterministic parsing
12094algorithm cannot by effectively splitting off multiple parsers, trying all
12095possible parsers, and discarding those that fail in the light of additional
12096right context.  @xref{Generalized LR Parsing, ,Generalized
12097LR Parsing}.
12098
12099@item Grouping
12100A language construct that is (in general) grammatically divisible;
12101for example, `expression' or `declaration' in C@.
12102@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
12103
12104@item IELR(1) (Inadequacy Elimination LR(1))
12105A minimal LR(1) parser table construction algorithm.  That is, given any
12106context-free grammar, IELR(1) generates parser tables with the full
12107language-recognition power of canonical LR(1) but with nearly the same
12108number of parser states as LALR(1).  This reduction in parser states is
12109often an order of magnitude.  More importantly, because canonical LR(1)'s
12110extra parser states may contain duplicate conflicts in the case of non-LR(1)
12111grammars, the number of conflicts for IELR(1) is often an order of magnitude
12112less as well.  This can significantly reduce the complexity of developing a
12113grammar.  @xref{LR Table Construction}.
12114
12115@item Infix operator
12116An arithmetic operator that is placed between the operands on which it
12117performs some operation.
12118
12119@item Input stream
12120A continuous flow of data between devices or programs.
12121
12122@item LAC (Lookahead Correction)
12123A parsing mechanism that fixes the problem of delayed syntax error
12124detection, which is caused by LR state merging, default reductions, and the
12125use of @code{%nonassoc}.  Delayed syntax error detection results in
12126unexpected semantic actions, initiation of error recovery in the wrong
12127syntactic context, and an incorrect list of expected tokens in a verbose
12128syntax error message.  @xref{LAC}.
12129
12130@item Language construct
12131One of the typical usage schemas of the language.  For example, one of
12132the constructs of the C language is the @code{if} statement.
12133@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
12134
12135@item Left associativity
12136Operators having left associativity are analyzed from left to right:
12137@samp{a+b+c} first computes @samp{a+b} and then combines with
12138@samp{c}.  @xref{Precedence, ,Operator Precedence}.
12139
12140@item Left recursion
12141A rule whose result symbol is also its first component symbol; for
12142example, @samp{expseq1 : expseq1 ',' exp;}.  @xref{Recursion, ,Recursive
12143Rules}.
12144
12145@item Left-to-right parsing
12146Parsing a sentence of a language by analyzing it token by token from
12147left to right.  @xref{Algorithm, ,The Bison Parser Algorithm}.
12148
12149@item Lexical analyzer (scanner)
12150A function that reads an input stream and returns tokens one by one.
12151@xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
12152
12153@item Lexical tie-in
12154A flag, set by actions in the grammar rules, which alters the way
12155tokens are parsed.  @xref{Lexical Tie-ins}.
12156
12157@item Literal string token
12158A token which consists of two or more fixed characters.  @xref{Symbols}.
12159
12160@item Lookahead token
12161A token already read but not yet shifted.  @xref{Lookahead, ,Lookahead
12162Tokens}.
12163
12164@item LALR(1)
12165The class of context-free grammars that Bison (like most other parser
12166generators) can handle by default; a subset of LR(1).
12167@xref{Mysterious Conflicts}.
12168
12169@item LR(1)
12170The class of context-free grammars in which at most one token of
12171lookahead is needed to disambiguate the parsing of any piece of input.
12172
12173@item Nonterminal symbol
12174A grammar symbol standing for a grammatical construct that can
12175be expressed through rules in terms of smaller constructs; in other
12176words, a construct that is not a token.  @xref{Symbols}.
12177
12178@item Parser
12179A function that recognizes valid sentences of a language by analyzing
12180the syntax structure of a set of tokens passed to it from a lexical
12181analyzer.
12182
12183@item Postfix operator
12184An arithmetic operator that is placed after the operands upon which it
12185performs some operation.
12186
12187@item Reduction
12188Replacing a string of nonterminals and/or terminals with a single
12189nonterminal, according to a grammar rule.  @xref{Algorithm, ,The Bison
12190Parser Algorithm}.
12191
12192@item Reentrant
12193A reentrant subprogram is a subprogram which can be in invoked any
12194number of times in parallel, without interference between the various
12195invocations.  @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
12196
12197@item Reverse polish notation
12198A language in which all operators are postfix operators.
12199
12200@item Right recursion
12201A rule whose result symbol is also its last component symbol; for
12202example, @samp{expseq1: exp ',' expseq1;}.  @xref{Recursion, ,Recursive
12203Rules}.
12204
12205@item Semantics
12206In computer languages, the semantics are specified by the actions
12207taken for each instance of the language, i.e., the meaning of
12208each statement.  @xref{Semantics, ,Defining Language Semantics}.
12209
12210@item Shift
12211A parser is said to shift when it makes the choice of analyzing
12212further input from the stream rather than reducing immediately some
12213already-recognized rule.  @xref{Algorithm, ,The Bison Parser Algorithm}.
12214
12215@item Single-character literal
12216A single character that is recognized and interpreted as is.
12217@xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
12218
12219@item Start symbol
12220The nonterminal symbol that stands for a complete valid utterance in
12221the language being parsed.  The start symbol is usually listed as the
12222first nonterminal symbol in a language specification.
12223@xref{Start Decl, ,The Start-Symbol}.
12224
12225@item Symbol table
12226A data structure where symbol names and associated data are stored
12227during parsing to allow for recognition and use of existing
12228information in repeated uses of a symbol.  @xref{Multi-function Calc}.
12229
12230@item Syntax error
12231An error encountered during parsing of an input stream due to invalid
12232syntax.  @xref{Error Recovery}.
12233
12234@item Token
12235A basic, grammatically indivisible unit of a language.  The symbol
12236that describes a token in the grammar is a terminal symbol.
12237The input of the Bison parser is a stream of tokens which comes from
12238the lexical analyzer.  @xref{Symbols}.
12239
12240@item Terminal symbol
12241A grammar symbol that has no rules in the grammar and therefore is
12242grammatically indivisible.  The piece of text it represents is a token.
12243@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
12244
12245@item Unreachable state
12246A parser state to which there does not exist a sequence of transitions from
12247the parser's start state.  A state can become unreachable during conflict
12248resolution.  @xref{Unreachable States}.
12249@end table
12250
12251@node Copying This Manual
12252@appendix Copying This Manual
12253@include fdl.texi
12254
12255@node Bibliography
12256@unnumbered Bibliography
12257
12258@table @asis
12259@item [Denny 2008]
12260Joel E. Denny and Brian A. Malloy, IELR(1): Practical LR(1) Parser Tables
12261for Non-LR(1) Grammars with Conflict Resolution, in @cite{Proceedings of the
122622008 ACM Symposium on Applied Computing} (SAC'08), ACM, New York, NY, USA,
12263pp.@: 240--245.  @uref{http://dx.doi.org/10.1145/1363686.1363747}
12264
12265@item [Denny 2010 May]
12266Joel E. Denny, PSLR(1): Pseudo-Scannerless Minimal LR(1) for the
12267Deterministic Parsing of Composite Languages, Ph.D. Dissertation, Clemson
12268University, Clemson, SC, USA (May 2010).
12269@uref{http://proquest.umi.com/pqdlink?did=2041473591&Fmt=7&clientId=79356&RQT=309&VName=PQD}
12270
12271@item [Denny 2010 November]
12272Joel E. Denny and Brian A. Malloy, The IELR(1) Algorithm for Generating
12273Minimal LR(1) Parser Tables for Non-LR(1) Grammars with Conflict Resolution,
12274in @cite{Science of Computer Programming}, Vol.@: 75, Issue 11 (November
122752010), pp.@: 943--979.  @uref{http://dx.doi.org/10.1016/j.scico.2009.08.001}
12276
12277@item [DeRemer 1982]
12278Frank DeRemer and Thomas Pennello, Efficient Computation of LALR(1)
12279Look-Ahead Sets, in @cite{ACM Transactions on Programming Languages and
12280Systems}, Vol.@: 4, No.@: 4 (October 1982), pp.@:
12281615--649. @uref{http://dx.doi.org/10.1145/69622.357187}
12282
12283@item [Knuth 1965]
12284Donald E. Knuth, On the Translation of Languages from Left to Right, in
12285@cite{Information and Control}, Vol.@: 8, Issue 6 (December 1965), pp.@:
12286607--639. @uref{http://dx.doi.org/10.1016/S0019-9958(65)90426-2}
12287
12288@item [Scott 2000]
12289Elizabeth Scott, Adrian Johnstone, and Shamsa Sadaf Hussain,
12290@cite{Tomita-Style Generalised LR Parsers}, Royal Holloway, University of
12291London, Department of Computer Science, TR-00-12 (December 2000).
12292@uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps}
12293@end table
12294
12295@node Index of Terms
12296@unnumbered Index of Terms
12297
12298@printindex cp
12299
12300@bye
12301
12302@c LocalWords: texinfo setfilename settitle setchapternewpage finalout texi FSF
12303@c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex FSF's
12304@c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry Naur
12305@c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa Multi
12306@c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc multi
12307@c LocalWords: rpcalc Lexer Expr ltcalc mfcalc yylex defaultprec Donnelly Gotos
12308@c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref yypush
12309@c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex lr
12310@c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init stmtMerge POSIX
12311@c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG yypull
12312@c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit nonfree
12313@c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok rr
12314@c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln Stallman Destructor
12315@c LocalWords: symrec val tptr FNCT fnctptr func struct sym enum IEC syntaxes
12316@c LocalWords: fnct putsym getsym fname arith fncts atan ptr malloc sizeof Lex
12317@c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum DOTDOT
12318@c LocalWords: ptypes itype YYPRINT trigraphs yytname expseq vindex dtype Unary
12319@c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs nonterminal
12320@c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES reentrant
12321@c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param yypstate
12322@c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP subrange
12323@c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword loc
12324@c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH inline
12325@c LocalWords: YYINITDEPTH stmts ref initdcl maybeasm notype Lookahead yyoutput
12326@c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args Autoconf
12327@c LocalWords: infile ypp yxx outfile itemx tex leaderfill Troubleshouting sqrt
12328@c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll lookahead
12329@c LocalWords: nbar yytext fst snd osplit ntwo strdup AST Troublereporting th
12330@c LocalWords: YYSTACK DVI fdl printindex IELR nondeterministic nonterminals ps
12331@c LocalWords: subexpressions declarator nondeferred config libintl postfix LAC
12332@c LocalWords: preprocessor nonpositive unary nonnumeric typedef extern rhs sr
12333@c LocalWords: yytokentype destructor multicharacter nonnull EBCDIC nterm LR's
12334@c LocalWords: lvalue nonnegative XNUM CHR chr TAGLESS tagless stdout api TOK
12335@c LocalWords: destructors Reentrancy nonreentrant subgrammar nonassociative Ph
12336@c LocalWords: deffnx namespace xml goto lalr ielr runtime lex yacc yyps env
12337@c LocalWords: yystate variadic Unshift NLS gettext po UTF Automake LOCALEDIR
12338@c LocalWords: YYENABLE bindtextdomain Makefile DEFS CPPFLAGS DBISON DeRemer
12339@c LocalWords: autoreconf Pennello multisets nondeterminism Generalised baz ACM
12340@c LocalWords: redeclare automata Dparse localedir datadir XSLT midrule Wno
12341@c LocalWords: Graphviz multitable headitem hh basename Doxygen fno filename
12342@c LocalWords: doxygen ival sval deftypemethod deallocate pos deftypemethodx
12343@c LocalWords: Ctor defcv defcvx arg accessors arithmetics CPP ifndef CALCXX
12344@c LocalWords: lexer's calcxx bool LPAREN RPAREN deallocation cerrno climits
12345@c LocalWords: cstdlib Debian undef yywrap unput noyywrap nounput zA yyleng
12346@c LocalWords: errno strtol ERANGE str strerror iostream argc argv Javadoc PSLR
12347@c LocalWords: bytecode initializers superclass stype ASTNode autoboxing nls
12348@c LocalWords: toString deftypeivar deftypeivarx deftypeop YYParser strictfp
12349@c LocalWords: superclasses boolean getErrorVerbose setErrorVerbose deftypecv
12350@c LocalWords: getDebugStream setDebugStream getDebugLevel setDebugLevel url
12351@c LocalWords: bisonVersion deftypecvx bisonSkeleton getStartPos getEndPos uint
12352@c LocalWords: getLVal defvar deftypefn deftypefnx gotos msgfmt Corbett LALR's
12353@c LocalWords: subdirectory Solaris nonassociativity perror schemas Malloy ints
12354@c LocalWords: Scannerless ispell american ChangeLog smallexample CSTYPE CLTYPE
12355@c LocalWords: clval CDEBUG cdebug deftypeopx yyterminate LocationType
12356@c LocalWords: parsers parser's
12357@c LocalWords: associativity subclasses precedences unresolvable runnable
12358@c LocalWords: allocators subunit initializations unreferenced untyped
12359@c LocalWords: errorVerbose subtype subtypes
12360
12361@c Local Variables:
12362@c ispell-dictionary: "american"
12363@c fill-column: 76
12364@c End:
12365