1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename bison.info
5 @settitle Bison @value{VERSION}
11 @c This edition has been formatted so that you can format and print it in
12 @c the smallbook format.
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.
29 @comment %**end of header
33 This manual is for @acronym{GNU} Bison (version @value{VERSION},
34 @value{UPDATED}), the @acronym{GNU} parser generator.
36 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
37 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software
41 Permission is granted to copy, distribute and/or modify this document
42 under the terms of the @acronym{GNU} Free Documentation License,
43 Version 1.2 or any later version published by the Free Software
44 Foundation; with no Invariant Sections, with the Front-Cover texts
45 being ``A @acronym{GNU} Manual,'' and with the Back-Cover Texts as in
46 (a) below. A copy of the license is included in the section entitled
47 ``@acronym{GNU} Free Documentation License.''
49 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
50 modify this @acronym{GNU} manual. Buying copies from the @acronym{FSF}
51 supports it in developing @acronym{GNU} and promoting software
56 @dircategory Software development
58 * bison: (bison). @acronym{GNU} parser generator (Yacc replacement).
63 @subtitle The Yacc-compatible Parser Generator
64 @subtitle @value{UPDATED}, Bison Version @value{VERSION}
66 @author by Charles Donnelly and Richard Stallman
69 @vskip 0pt plus 1filll
72 Published by the Free Software Foundation @*
73 51 Franklin Street, Fifth Floor @*
74 Boston, MA 02110-1301 USA @*
75 Printed copies are available from the Free Software Foundation.@*
76 @acronym{ISBN} 1-882114-44-2
78 Cover art by Etienne Suvasa.
92 * Copying:: The @acronym{GNU} General Public License says
93 how you can copy and share Bison
96 * Concepts:: Basic concepts for understanding Bison.
97 * Examples:: Three simple explained examples of using Bison.
100 * Grammar File:: Writing Bison declarations and rules.
101 * Interface:: C-language interface to the parser function @code{yyparse}.
102 * Algorithm:: How the Bison parser works at run-time.
103 * Error Recovery:: Writing rules for error recovery.
104 * Context Dependency:: What to do if your language syntax is too
105 messy for Bison to handle straightforwardly.
106 * Debugging:: Understanding or debugging Bison parsers.
107 * Invocation:: How to run Bison (to produce the parser source file).
108 * Other Languages:: Creating C++ and Java parsers.
109 * FAQ:: Frequently Asked Questions
110 * Table of Symbols:: All the keywords of the Bison language are explained.
111 * Glossary:: Basic concepts are explained.
112 * Copying This Manual:: License for copying this manual.
113 * Index:: Cross-references to the text.
116 --- The Detailed Node Listing ---
118 The Concepts of Bison
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:: Tracking Locations.
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.
134 Writing @acronym{GLR} Parsers
136 * Simple GLR Parsers:: Using @acronym{GLR} parsers on unambiguous grammars.
137 * Merging GLR Parses:: Using @acronym{GLR} parsers to resolve ambiguities.
138 * GLR Semantic Actions:: Deferred semantic actions have special concerns.
139 * Compiler Requirements:: @acronym{GLR} parsers require a modern C compiler.
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.
153 Reverse Polish Notation Calculator
155 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
156 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
157 * Lexer: Rpcalc Lexer. The lexical analyzer.
158 * Main: Rpcalc Main. The controlling function.
159 * Error: Rpcalc Error. The error reporting function.
160 * Gen: Rpcalc Gen. Running Bison on the grammar file.
161 * Comp: Rpcalc Compile. Run the C compiler on the output code.
163 Grammar Rules for @code{rpcalc}
169 Location Tracking Calculator: @code{ltcalc}
171 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
172 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
173 * Lexer: Ltcalc Lexer. The lexical analyzer.
175 Multi-Function Calculator: @code{mfcalc}
177 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
178 * Rules: Mfcalc Rules. Grammar rules for the calculator.
179 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
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 * Locations:: Locations and actions.
189 * Declarations:: All kinds of Bison declarations are described here.
190 * Multiple Parsers:: Putting more than one Bison parser in one program.
192 Outline of a Bison Grammar
194 * Prologue:: Syntax and usage of the prologue.
195 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
196 * Bison Declarations:: Syntax and usage of the Bison declarations section.
197 * Grammar Rules:: Syntax and usage of the grammar rules section.
198 * Epilogue:: Syntax and usage of the epilogue.
200 Defining Language Semantics
202 * Value Type:: Specifying one data type for all semantic values.
203 * Multiple Types:: Specifying several alternative data types.
204 * Actions:: An action is the semantic definition of a grammar rule.
205 * Action Types:: Specifying data types for actions to operate on.
206 * Mid-Rule Actions:: Most actions go at the end of a rule.
207 This says when, why and how to use the exceptional
208 action in the middle of a rule.
212 * Location Type:: Specifying a data type for locations.
213 * Actions and Locations:: Using locations in actions.
214 * Location Default Action:: Defining a general way to compute locations.
218 * Require Decl:: Requiring a Bison version.
219 * Token Decl:: Declaring terminal symbols.
220 * Precedence Decl:: Declaring terminals with precedence and associativity.
221 * Union Decl:: Declaring the set of all semantic value types.
222 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
223 * Initial Action Decl:: Code run before parsing starts.
224 * Destructor Decl:: Declaring how symbols are freed.
225 * Expect Decl:: Suppressing warnings about parsing conflicts.
226 * Start Decl:: Specifying the start symbol.
227 * Pure Decl:: Requesting a reentrant parser.
228 * Push Decl:: Requesting a push parser.
229 * Decl Summary:: Table of all Bison declarations.
231 Parser C-Language Interface
233 * Parser Function:: How to call @code{yyparse} and what it returns.
234 * Lexical:: You must supply a function @code{yylex}
236 * Error Reporting:: You must supply a function @code{yyerror}.
237 * Action Features:: Special features for use in actions.
238 * Internationalization:: How to let the parser speak in the user's
241 The Lexical Analyzer Function @code{yylex}
243 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
244 * Token Values:: How @code{yylex} must return the semantic value
245 of the token it has read.
246 * Token Locations:: How @code{yylex} must return the text location
247 (line number, etc.) of the token, if the
249 * Pure Calling:: How the calling convention differs
250 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
252 The Bison Parser Algorithm
254 * Lookahead:: Parser looks one token ahead when deciding what to do.
255 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
256 * Precedence:: Operator precedence works by resolving conflicts.
257 * Contextual Precedence:: When an operator's precedence depends on context.
258 * Parser States:: The parser is a finite-state-machine with stack.
259 * Reduce/Reduce:: When two rules are applicable in the same situation.
260 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
261 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
262 * Memory Management:: What happens when memory is exhausted. How to avoid it.
266 * Why Precedence:: An example showing why precedence is needed.
267 * Using Precedence:: How to specify precedence in Bison grammars.
268 * Precedence Examples:: How these features are used in the previous example.
269 * How Precedence:: How they work.
271 Handling Context Dependencies
273 * Semantic Tokens:: Token parsing can depend on the semantic context.
274 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
275 * Tie-in Recovery:: Lexical tie-ins have implications for how
276 error recovery rules must be written.
278 Debugging Your Parser
280 * Understanding:: Understanding the structure of your parser.
281 * Tracing:: Tracing the execution of your parser.
285 * Bison Options:: All the options described in detail,
286 in alphabetical order by short options.
287 * Option Cross Key:: Alphabetical list of long options.
288 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
290 Parsers Written In Other Languages
292 * C++ Parsers:: The interface to generate C++ parser classes
293 * Java Parsers:: The interface to generate Java parser classes
297 * C++ Bison Interface:: Asking for C++ parser generation
298 * C++ Semantic Values:: %union vs. C++
299 * C++ Location Values:: The position and location classes
300 * C++ Parser Interface:: Instantiating and running the parser
301 * C++ Scanner Interface:: Exchanges between yylex and parse
302 * A Complete C++ Example:: Demonstrating their use
304 A Complete C++ Example
306 * Calc++ --- C++ Calculator:: The specifications
307 * Calc++ Parsing Driver:: An active parsing context
308 * Calc++ Parser:: A parser class
309 * Calc++ Scanner:: A pure C++ Flex scanner
310 * Calc++ Top Level:: Conducting the band
314 * Java Bison Interface:: Asking for Java parser generation
315 * Java Semantic Values:: %type and %token vs. Java
316 * Java Location Values:: The position and location classes
317 * Java Parser Interface:: Instantiating and running the parser
318 * Java Scanner Interface:: Java scanners, and pure parsers
319 * Java Differences:: Differences between C/C++ and Java Grammars
321 Frequently Asked Questions
323 * Memory Exhausted:: Breaking the Stack Limits
324 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
325 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
326 * Implementing Gotos/Loops:: Control Flow in the Calculator
327 * Multiple start-symbols:: Factoring closely related grammars
328 * Secure? Conform?:: Is Bison @acronym{POSIX} safe?
329 * I can't build Bison:: Troubleshooting
330 * Where can I find help?:: Troubleshouting
331 * Bug Reports:: Troublereporting
332 * Other Languages:: Parsers in Java and others
333 * Beta Testing:: Experimenting development versions
334 * Mailing Lists:: Meeting other Bison users
338 * Copying This Manual:: License for copying this manual.
344 @unnumbered Introduction
347 @dfn{Bison} is a general-purpose parser generator that converts an
348 annotated context-free grammar into an @acronym{LALR}(1) or
349 @acronym{GLR} parser for that grammar. Once you are proficient with
350 Bison, you can use it to develop a wide range of language parsers, from those
351 used in simple desk calculators to complex programming languages.
353 Bison is upward compatible with Yacc: all properly-written Yacc grammars
354 ought to work with Bison with no change. Anyone familiar with Yacc
355 should be able to use Bison with little trouble. You need to be fluent in
356 C or C++ programming in order to use Bison or to understand this manual.
358 We begin with tutorial chapters that explain the basic concepts of using
359 Bison and show three explained examples, each building on the last. If you
360 don't know Bison or Yacc, start by reading these chapters. Reference
361 chapters follow which describe specific aspects of Bison in detail.
363 Bison was written primarily by Robert Corbett; Richard Stallman made it
364 Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
365 multi-character string literals and other features.
367 This edition corresponds to version @value{VERSION} of Bison.
370 @unnumbered Conditions for Using Bison
372 The distribution terms for Bison-generated parsers permit using the
373 parsers in nonfree programs. Before Bison version 2.2, these extra
374 permissions applied only when Bison was generating @acronym{LALR}(1)
375 parsers in C@. And before Bison version 1.24, Bison-generated
376 parsers could be used only in programs that were free software.
378 The other @acronym{GNU} programming tools, such as the @acronym{GNU} C
380 had such a requirement. They could always be used for nonfree
381 software. The reason Bison was different was not due to a special
382 policy decision; it resulted from applying the usual General Public
383 License to all of the Bison source code.
385 The output of the Bison utility---the Bison parser file---contains a
386 verbatim copy of a sizable piece of Bison, which is the code for the
387 parser's implementation. (The actions from your grammar are inserted
388 into this implementation at one point, but most of the rest of the
389 implementation is not changed.) When we applied the @acronym{GPL}
390 terms to the skeleton code for the parser's implementation,
391 the effect was to restrict the use of Bison output to free software.
393 We didn't change the terms because of sympathy for people who want to
394 make software proprietary. @strong{Software should be free.} But we
395 concluded that limiting Bison's use to free software was doing little to
396 encourage people to make other software free. So we decided to make the
397 practical conditions for using Bison match the practical conditions for
398 using the other @acronym{GNU} tools.
400 This exception applies when Bison is generating code for a parser.
401 You can tell whether the exception applies to a Bison output file by
402 inspecting the file for text beginning with ``As a special
403 exception@dots{}''. The text spells out the exact terms of the
407 @unnumbered GNU GENERAL PUBLIC LICENSE
408 @include gpl-3.0.texi
411 @chapter The Concepts of Bison
413 This chapter introduces many of the basic concepts without which the
414 details of Bison will not make sense. If you do not already know how to
415 use Bison or Yacc, we suggest you start by reading this chapter carefully.
418 * Language and Grammar:: Languages and context-free grammars,
419 as mathematical ideas.
420 * Grammar in Bison:: How we represent grammars for Bison's sake.
421 * Semantic Values:: Each token or syntactic grouping can have
422 a semantic value (the value of an integer,
423 the name of an identifier, etc.).
424 * Semantic Actions:: Each rule can have an action containing C code.
425 * GLR Parsers:: Writing parsers for general context-free languages.
426 * Locations Overview:: Tracking Locations.
427 * Bison Parser:: What are Bison's input and output,
428 how is the output used?
429 * Stages:: Stages in writing and running Bison grammars.
430 * Grammar Layout:: Overall structure of a Bison grammar file.
433 @node Language and Grammar
434 @section Languages and Context-Free Grammars
436 @cindex context-free grammar
437 @cindex grammar, context-free
438 In order for Bison to parse a language, it must be described by a
439 @dfn{context-free grammar}. This means that you specify one or more
440 @dfn{syntactic groupings} and give rules for constructing them from their
441 parts. For example, in the C language, one kind of grouping is called an
442 `expression'. One rule for making an expression might be, ``An expression
443 can be made of a minus sign and another expression''. Another would be,
444 ``An expression can be an integer''. As you can see, rules are often
445 recursive, but there must be at least one rule which leads out of the
448 @cindex @acronym{BNF}
449 @cindex Backus-Naur form
450 The most common formal system for presenting such rules for humans to read
451 is @dfn{Backus-Naur Form} or ``@acronym{BNF}'', which was developed in
452 order to specify the language Algol 60. Any grammar expressed in
453 @acronym{BNF} is a context-free grammar. The input to Bison is
454 essentially machine-readable @acronym{BNF}.
456 @cindex @acronym{LALR}(1) grammars
457 @cindex @acronym{LR}(1) grammars
458 There are various important subclasses of context-free grammar. Although it
459 can handle almost all context-free grammars, Bison is optimized for what
460 are called @acronym{LALR}(1) grammars.
461 In brief, in these grammars, it must be possible to
462 tell how to parse any portion of an input string with just a single
463 token of lookahead. Strictly speaking, that is a description of an
464 @acronym{LR}(1) grammar, and @acronym{LALR}(1) involves additional
465 restrictions that are
466 hard to explain simply; but it is rare in actual practice to find an
467 @acronym{LR}(1) grammar that fails to be @acronym{LALR}(1).
468 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}, for
469 more information on this.
471 @cindex @acronym{GLR} parsing
472 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
473 @cindex ambiguous grammars
474 @cindex nondeterministic parsing
476 Parsers for @acronym{LALR}(1) grammars are @dfn{deterministic}, meaning
477 roughly that the next grammar rule to apply at any point in the input is
478 uniquely determined by the preceding input and a fixed, finite portion
479 (called a @dfn{lookahead}) of the remaining input. A context-free
480 grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
481 apply the grammar rules to get the same inputs. Even unambiguous
482 grammars can be @dfn{nondeterministic}, meaning that no fixed
483 lookahead always suffices to determine the next grammar rule to apply.
484 With the proper declarations, Bison is also able to parse these more
485 general context-free grammars, using a technique known as @acronym{GLR}
486 parsing (for Generalized @acronym{LR}). Bison's @acronym{GLR} parsers
487 are able to handle any context-free grammar for which the number of
488 possible parses of any given string is finite.
490 @cindex symbols (abstract)
492 @cindex syntactic grouping
493 @cindex grouping, syntactic
494 In the formal grammatical rules for a language, each kind of syntactic
495 unit or grouping is named by a @dfn{symbol}. Those which are built by
496 grouping smaller constructs according to grammatical rules are called
497 @dfn{nonterminal symbols}; those which can't be subdivided are called
498 @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
499 corresponding to a single terminal symbol a @dfn{token}, and a piece
500 corresponding to a single nonterminal symbol a @dfn{grouping}.
502 We can use the C language as an example of what symbols, terminal and
503 nonterminal, mean. The tokens of C are identifiers, constants (numeric
504 and string), and the various keywords, arithmetic operators and
505 punctuation marks. So the terminal symbols of a grammar for C include
506 `identifier', `number', `string', plus one symbol for each keyword,
507 operator or punctuation mark: `if', `return', `const', `static', `int',
508 `char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
509 (These tokens can be subdivided into characters, but that is a matter of
510 lexicography, not grammar.)
512 Here is a simple C function subdivided into tokens:
516 int /* @r{keyword `int'} */
517 square (int x) /* @r{identifier, open-paren, keyword `int',}
518 @r{identifier, close-paren} */
519 @{ /* @r{open-brace} */
520 return x * x; /* @r{keyword `return', identifier, asterisk,}
521 @r{identifier, semicolon} */
522 @} /* @r{close-brace} */
527 int /* @r{keyword `int'} */
528 square (int x) /* @r{identifier, open-paren, keyword `int', identifier, close-paren} */
529 @{ /* @r{open-brace} */
530 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
531 @} /* @r{close-brace} */
535 The syntactic groupings of C include the expression, the statement, the
536 declaration, and the function definition. These are represented in the
537 grammar of C by nonterminal symbols `expression', `statement',
538 `declaration' and `function definition'. The full grammar uses dozens of
539 additional language constructs, each with its own nonterminal symbol, in
540 order to express the meanings of these four. The example above is a
541 function definition; it contains one declaration, and one statement. In
542 the statement, each @samp{x} is an expression and so is @samp{x * x}.
544 Each nonterminal symbol must have grammatical rules showing how it is made
545 out of simpler constructs. For example, one kind of C statement is the
546 @code{return} statement; this would be described with a grammar rule which
547 reads informally as follows:
550 A `statement' can be made of a `return' keyword, an `expression' and a
555 There would be many other rules for `statement', one for each kind of
559 One nonterminal symbol must be distinguished as the special one which
560 defines a complete utterance in the language. It is called the @dfn{start
561 symbol}. In a compiler, this means a complete input program. In the C
562 language, the nonterminal symbol `sequence of definitions and declarations'
565 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
566 program---but it is not valid as an @emph{entire} C program. In the
567 context-free grammar of C, this follows from the fact that `expression' is
568 not the start symbol.
570 The Bison parser reads a sequence of tokens as its input, and groups the
571 tokens using the grammar rules. If the input is valid, the end result is
572 that the entire token sequence reduces to a single grouping whose symbol is
573 the grammar's start symbol. If we use a grammar for C, the entire input
574 must be a `sequence of definitions and declarations'. If not, the parser
575 reports a syntax error.
577 @node Grammar in Bison
578 @section From Formal Rules to Bison Input
579 @cindex Bison grammar
580 @cindex grammar, Bison
581 @cindex formal grammar
583 A formal grammar is a mathematical construct. To define the language
584 for Bison, you must write a file expressing the grammar in Bison syntax:
585 a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
587 A nonterminal symbol in the formal grammar is represented in Bison input
588 as an identifier, like an identifier in C@. By convention, it should be
589 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
591 The Bison representation for a terminal symbol is also called a @dfn{token
592 type}. Token types as well can be represented as C-like identifiers. By
593 convention, these identifiers should be upper case to distinguish them from
594 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
595 @code{RETURN}. A terminal symbol that stands for a particular keyword in
596 the language should be named after that keyword converted to upper case.
597 The terminal symbol @code{error} is reserved for error recovery.
600 A terminal symbol can also be represented as a character literal, just like
601 a C character constant. You should do this whenever a token is just a
602 single character (parenthesis, plus-sign, etc.): use that same character in
603 a literal as the terminal symbol for that token.
605 A third way to represent a terminal symbol is with a C string constant
606 containing several characters. @xref{Symbols}, for more information.
608 The grammar rules also have an expression in Bison syntax. For example,
609 here is the Bison rule for a C @code{return} statement. The semicolon in
610 quotes is a literal character token, representing part of the C syntax for
611 the statement; the naked semicolon, and the colon, are Bison punctuation
615 stmt: RETURN expr ';'
620 @xref{Rules, ,Syntax of Grammar Rules}.
622 @node Semantic Values
623 @section Semantic Values
624 @cindex semantic value
625 @cindex value, semantic
627 A formal grammar selects tokens only by their classifications: for example,
628 if a rule mentions the terminal symbol `integer constant', it means that
629 @emph{any} integer constant is grammatically valid in that position. The
630 precise value of the constant is irrelevant to how to parse the input: if
631 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
634 But the precise value is very important for what the input means once it is
635 parsed. A compiler is useless if it fails to distinguish between 4, 1 and
636 3989 as constants in the program! Therefore, each token in a Bison grammar
637 has both a token type and a @dfn{semantic value}. @xref{Semantics,
638 ,Defining Language Semantics},
641 The token type is a terminal symbol defined in the grammar, such as
642 @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
643 you need to know to decide where the token may validly appear and how to
644 group it with other tokens. The grammar rules know nothing about tokens
647 The semantic value has all the rest of the information about the
648 meaning of the token, such as the value of an integer, or the name of an
649 identifier. (A token such as @code{','} which is just punctuation doesn't
650 need to have any semantic value.)
652 For example, an input token might be classified as token type
653 @code{INTEGER} and have the semantic value 4. Another input token might
654 have the same token type @code{INTEGER} but value 3989. When a grammar
655 rule says that @code{INTEGER} is allowed, either of these tokens is
656 acceptable because each is an @code{INTEGER}. When the parser accepts the
657 token, it keeps track of the token's semantic value.
659 Each grouping can also have a semantic value as well as its nonterminal
660 symbol. For example, in a calculator, an expression typically has a
661 semantic value that is a number. In a compiler for a programming
662 language, an expression typically has a semantic value that is a tree
663 structure describing the meaning of the expression.
665 @node Semantic Actions
666 @section Semantic Actions
667 @cindex semantic actions
668 @cindex actions, semantic
670 In order to be useful, a program must do more than parse input; it must
671 also produce some output based on the input. In a Bison grammar, a grammar
672 rule can have an @dfn{action} made up of C statements. Each time the
673 parser recognizes a match for that rule, the action is executed.
676 Most of the time, the purpose of an action is to compute the semantic value
677 of the whole construct from the semantic values of its parts. For example,
678 suppose we have a rule which says an expression can be the sum of two
679 expressions. When the parser recognizes such a sum, each of the
680 subexpressions has a semantic value which describes how it was built up.
681 The action for this rule should create a similar sort of value for the
682 newly recognized larger expression.
684 For example, here is a rule that says an expression can be the sum of
688 expr: expr '+' expr @{ $$ = $1 + $3; @}
693 The action says how to produce the semantic value of the sum expression
694 from the values of the two subexpressions.
697 @section Writing @acronym{GLR} Parsers
698 @cindex @acronym{GLR} parsing
699 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
702 @cindex shift/reduce conflicts
703 @cindex reduce/reduce conflicts
705 In some grammars, Bison's standard
706 @acronym{LALR}(1) parsing algorithm cannot decide whether to apply a
707 certain grammar rule at a given point. That is, it may not be able to
708 decide (on the basis of the input read so far) which of two possible
709 reductions (applications of a grammar rule) applies, or whether to apply
710 a reduction or read more of the input and apply a reduction later in the
711 input. These are known respectively as @dfn{reduce/reduce} conflicts
712 (@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
713 (@pxref{Shift/Reduce}).
715 To use a grammar that is not easily modified to be @acronym{LALR}(1), a
716 more general parsing algorithm is sometimes necessary. If you include
717 @code{%glr-parser} among the Bison declarations in your file
718 (@pxref{Grammar Outline}), the result is a Generalized @acronym{LR}
719 (@acronym{GLR}) parser. These parsers handle Bison grammars that
720 contain no unresolved conflicts (i.e., after applying precedence
721 declarations) identically to @acronym{LALR}(1) parsers. However, when
722 faced with unresolved shift/reduce and reduce/reduce conflicts,
723 @acronym{GLR} parsers use the simple expedient of doing both,
724 effectively cloning the parser to follow both possibilities. Each of
725 the resulting parsers can again split, so that at any given time, there
726 can be any number of possible parses being explored. The parsers
727 proceed in lockstep; that is, all of them consume (shift) a given input
728 symbol before any of them proceed to the next. Each of the cloned
729 parsers eventually meets one of two possible fates: either it runs into
730 a parsing error, in which case it simply vanishes, or it merges with
731 another parser, because the two of them have reduced the input to an
732 identical set of symbols.
734 During the time that there are multiple parsers, semantic actions are
735 recorded, but not performed. When a parser disappears, its recorded
736 semantic actions disappear as well, and are never performed. When a
737 reduction makes two parsers identical, causing them to merge, Bison
738 records both sets of semantic actions. Whenever the last two parsers
739 merge, reverting to the single-parser case, Bison resolves all the
740 outstanding actions either by precedences given to the grammar rules
741 involved, or by performing both actions, and then calling a designated
742 user-defined function on the resulting values to produce an arbitrary
746 * Simple GLR Parsers:: Using @acronym{GLR} parsers on unambiguous grammars.
747 * Merging GLR Parses:: Using @acronym{GLR} parsers to resolve ambiguities.
748 * GLR Semantic Actions:: Deferred semantic actions have special concerns.
749 * Compiler Requirements:: @acronym{GLR} parsers require a modern C compiler.
752 @node Simple GLR Parsers
753 @subsection Using @acronym{GLR} on Unambiguous Grammars
754 @cindex @acronym{GLR} parsing, unambiguous grammars
755 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing, unambiguous grammars
759 @cindex reduce/reduce conflicts
760 @cindex shift/reduce conflicts
762 In the simplest cases, you can use the @acronym{GLR} algorithm
763 to parse grammars that are unambiguous, but fail to be @acronym{LALR}(1).
764 Such grammars typically require more than one symbol of lookahead,
765 or (in rare cases) fall into the category of grammars in which the
766 @acronym{LALR}(1) algorithm throws away too much information (they are in
767 @acronym{LR}(1), but not @acronym{LALR}(1), @ref{Mystery Conflicts}).
769 Consider a problem that
770 arises in the declaration of enumerated and subrange types in the
771 programming language Pascal. Here are some examples:
774 type subrange = lo .. hi;
775 type enum = (a, b, c);
779 The original language standard allows only numeric
780 literals and constant identifiers for the subrange bounds (@samp{lo}
781 and @samp{hi}), but Extended Pascal (@acronym{ISO}/@acronym{IEC}
782 10206) and many other
783 Pascal implementations allow arbitrary expressions there. This gives
784 rise to the following situation, containing a superfluous pair of
788 type subrange = (a) .. b;
792 Compare this to the following declaration of an enumerated
793 type with only one value:
800 (These declarations are contrived, but they are syntactically
801 valid, and more-complicated cases can come up in practical programs.)
803 These two declarations look identical until the @samp{..} token.
804 With normal @acronym{LALR}(1) one-token lookahead it is not
805 possible to decide between the two forms when the identifier
806 @samp{a} is parsed. It is, however, desirable
807 for a parser to decide this, since in the latter case
808 @samp{a} must become a new identifier to represent the enumeration
809 value, while in the former case @samp{a} must be evaluated with its
810 current meaning, which may be a constant or even a function call.
812 You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
813 to be resolved later, but this typically requires substantial
814 contortions in both semantic actions and large parts of the
815 grammar, where the parentheses are nested in the recursive rules for
818 You might think of using the lexer to distinguish between the two
819 forms by returning different tokens for currently defined and
820 undefined identifiers. But if these declarations occur in a local
821 scope, and @samp{a} is defined in an outer scope, then both forms
822 are possible---either locally redefining @samp{a}, or using the
823 value of @samp{a} from the outer scope. So this approach cannot
826 A simple solution to this problem is to declare the parser to
827 use the @acronym{GLR} algorithm.
828 When the @acronym{GLR} parser reaches the critical state, it
829 merely splits into two branches and pursues both syntax rules
830 simultaneously. Sooner or later, one of them runs into a parsing
831 error. If there is a @samp{..} token before the next
832 @samp{;}, the rule for enumerated types fails since it cannot
833 accept @samp{..} anywhere; otherwise, the subrange type rule
834 fails since it requires a @samp{..} token. So one of the branches
835 fails silently, and the other one continues normally, performing
836 all the intermediate actions that were postponed during the split.
838 If the input is syntactically incorrect, both branches fail and the parser
839 reports a syntax error as usual.
841 The effect of all this is that the parser seems to ``guess'' the
842 correct branch to take, or in other words, it seems to use more
843 lookahead than the underlying @acronym{LALR}(1) algorithm actually allows
844 for. In this example, @acronym{LALR}(2) would suffice, but also some cases
845 that are not @acronym{LALR}(@math{k}) for any @math{k} can be handled this way.
847 In general, a @acronym{GLR} parser can take quadratic or cubic worst-case time,
848 and the current Bison parser even takes exponential time and space
849 for some grammars. In practice, this rarely happens, and for many
850 grammars it is possible to prove that it cannot happen.
851 The present example contains only one conflict between two
852 rules, and the type-declaration context containing the conflict
853 cannot be nested. So the number of
854 branches that can exist at any time is limited by the constant 2,
855 and the parsing time is still linear.
857 Here is a Bison grammar corresponding to the example above. It
858 parses a vastly simplified form of Pascal type declarations.
861 %token TYPE DOTDOT ID
871 type_decl : TYPE ID '=' type ';'
876 type : '(' id_list ')'
898 When used as a normal @acronym{LALR}(1) grammar, Bison correctly complains
899 about one reduce/reduce conflict. In the conflicting situation the
900 parser chooses one of the alternatives, arbitrarily the one
901 declared first. Therefore the following correct input is not
908 The parser can be turned into a @acronym{GLR} parser, while also telling Bison
909 to be silent about the one known reduce/reduce conflict, by
910 adding these two declarations to the Bison input file (before the first
919 No change in the grammar itself is required. Now the
920 parser recognizes all valid declarations, according to the
921 limited syntax above, transparently. In fact, the user does not even
922 notice when the parser splits.
924 So here we have a case where we can use the benefits of @acronym{GLR},
925 almost without disadvantages. Even in simple cases like this, however,
926 there are at least two potential problems to beware. First, always
927 analyze the conflicts reported by Bison to make sure that @acronym{GLR}
928 splitting is only done where it is intended. A @acronym{GLR} parser
929 splitting inadvertently may cause problems less obvious than an
930 @acronym{LALR} parser statically choosing the wrong alternative in a
931 conflict. Second, consider interactions with the lexer (@pxref{Semantic
932 Tokens}) with great care. Since a split parser consumes tokens without
933 performing any actions during the split, the lexer cannot obtain
934 information via parser actions. Some cases of lexer interactions can be
935 eliminated by using @acronym{GLR} to shift the complications from the
936 lexer to the parser. You must check the remaining cases for
939 In our example, it would be safe for the lexer to return tokens based on
940 their current meanings in some symbol table, because no new symbols are
941 defined in the middle of a type declaration. Though it is possible for
942 a parser to define the enumeration constants as they are parsed, before
943 the type declaration is completed, it actually makes no difference since
944 they cannot be used within the same enumerated type declaration.
946 @node Merging GLR Parses
947 @subsection Using @acronym{GLR} to Resolve Ambiguities
948 @cindex @acronym{GLR} parsing, ambiguous grammars
949 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing, ambiguous grammars
953 @cindex reduce/reduce conflicts
955 Let's consider an example, vastly simplified from a C++ grammar.
960 #define YYSTYPE char const *
962 void yyerror (char const *);
975 | prog stmt @{ printf ("\n"); @}
978 stmt : expr ';' %dprec 1
982 expr : ID @{ printf ("%s ", $$); @}
983 | TYPENAME '(' expr ')'
984 @{ printf ("%s <cast> ", $1); @}
985 | expr '+' expr @{ printf ("+ "); @}
986 | expr '=' expr @{ printf ("= "); @}
989 decl : TYPENAME declarator ';'
990 @{ printf ("%s <declare> ", $1); @}
991 | TYPENAME declarator '=' expr ';'
992 @{ printf ("%s <init-declare> ", $1); @}
995 declarator : ID @{ printf ("\"%s\" ", $1); @}
1001 This models a problematic part of the C++ grammar---the ambiguity between
1002 certain declarations and statements. For example,
1009 parses as either an @code{expr} or a @code{stmt}
1010 (assuming that @samp{T} is recognized as a @code{TYPENAME} and
1011 @samp{x} as an @code{ID}).
1012 Bison detects this as a reduce/reduce conflict between the rules
1013 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
1014 time it encounters @code{x} in the example above. Since this is a
1015 @acronym{GLR} parser, it therefore splits the problem into two parses, one for
1016 each choice of resolving the reduce/reduce conflict.
1017 Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1018 however, neither of these parses ``dies,'' because the grammar as it stands is
1019 ambiguous. One of the parsers eventually reduces @code{stmt : expr ';'} and
1020 the other reduces @code{stmt : decl}, after which both parsers are in an
1021 identical state: they've seen @samp{prog stmt} and have the same unprocessed
1022 input remaining. We say that these parses have @dfn{merged.}
1024 At this point, the @acronym{GLR} parser requires a specification in the
1025 grammar of how to choose between the competing parses.
1026 In the example above, the two @code{%dprec}
1027 declarations specify that Bison is to give precedence
1028 to the parse that interprets the example as a
1029 @code{decl}, which implies that @code{x} is a declarator.
1030 The parser therefore prints
1033 "x" y z + T <init-declare>
1036 The @code{%dprec} declarations only come into play when more than one
1037 parse survives. Consider a different input string for this parser:
1044 This is another example of using @acronym{GLR} to parse an unambiguous
1045 construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
1046 Here, there is no ambiguity (this cannot be parsed as a declaration).
1047 However, at the time the Bison parser encounters @code{x}, it does not
1048 have enough information to resolve the reduce/reduce conflict (again,
1049 between @code{x} as an @code{expr} or a @code{declarator}). In this
1050 case, no precedence declaration is used. Again, the parser splits
1051 into two, one assuming that @code{x} is an @code{expr}, and the other
1052 assuming @code{x} is a @code{declarator}. The second of these parsers
1053 then vanishes when it sees @code{+}, and the parser prints
1059 Suppose that instead of resolving the ambiguity, you wanted to see all
1060 the possibilities. For this purpose, you must merge the semantic
1061 actions of the two possible parsers, rather than choosing one over the
1062 other. To do so, you could change the declaration of @code{stmt} as
1066 stmt : expr ';' %merge <stmtMerge>
1067 | decl %merge <stmtMerge>
1072 and define the @code{stmtMerge} function as:
1076 stmtMerge (YYSTYPE x0, YYSTYPE x1)
1084 with an accompanying forward declaration
1085 in the C declarations at the beginning of the file:
1089 #define YYSTYPE char const *
1090 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
1095 With these declarations, the resulting parser parses the first example
1096 as both an @code{expr} and a @code{decl}, and prints
1099 "x" y z + T <init-declare> x T <cast> y z + = <OR>
1102 Bison requires that all of the
1103 productions that participate in any particular merge have identical
1104 @samp{%merge} clauses. Otherwise, the ambiguity would be unresolvable,
1105 and the parser will report an error during any parse that results in
1106 the offending merge.
1108 @node GLR Semantic Actions
1109 @subsection GLR Semantic Actions
1111 @cindex deferred semantic actions
1112 By definition, a deferred semantic action is not performed at the same time as
1113 the associated reduction.
1114 This raises caveats for several Bison features you might use in a semantic
1115 action in a @acronym{GLR} parser.
1118 @cindex @acronym{GLR} parsers and @code{yychar}
1120 @cindex @acronym{GLR} parsers and @code{yylval}
1122 @cindex @acronym{GLR} parsers and @code{yylloc}
1123 In any semantic action, you can examine @code{yychar} to determine the type of
1124 the lookahead token present at the time of the associated reduction.
1125 After checking that @code{yychar} is not set to @code{YYEMPTY} or @code{YYEOF},
1126 you can then examine @code{yylval} and @code{yylloc} to determine the
1127 lookahead token's semantic value and location, if any.
1128 In a nondeferred semantic action, you can also modify any of these variables to
1129 influence syntax analysis.
1130 @xref{Lookahead, ,Lookahead Tokens}.
1133 @cindex @acronym{GLR} parsers and @code{yyclearin}
1134 In a deferred semantic action, it's too late to influence syntax analysis.
1135 In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1136 shallow copies of the values they had at the time of the associated reduction.
1137 For this reason alone, modifying them is dangerous.
1138 Moreover, the result of modifying them is undefined and subject to change with
1139 future versions of Bison.
1140 For example, if a semantic action might be deferred, you should never write it
1141 to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1142 memory referenced by @code{yylval}.
1145 @cindex @acronym{GLR} parsers and @code{YYERROR}
1146 Another Bison feature requiring special consideration is @code{YYERROR}
1147 (@pxref{Action Features}), which you can invoke in a semantic action to
1148 initiate error recovery.
1149 During deterministic @acronym{GLR} operation, the effect of @code{YYERROR} is
1150 the same as its effect in an @acronym{LALR}(1) parser.
1151 In a deferred semantic action, its effect is undefined.
1152 @c The effect is probably a syntax error at the split point.
1154 Also, see @ref{Location Default Action, ,Default Action for Locations}, which
1155 describes a special usage of @code{YYLLOC_DEFAULT} in @acronym{GLR} parsers.
1157 @node Compiler Requirements
1158 @subsection Considerations when Compiling @acronym{GLR} Parsers
1159 @cindex @code{inline}
1160 @cindex @acronym{GLR} parsers and @code{inline}
1162 The @acronym{GLR} parsers require a compiler for @acronym{ISO} C89 or
1163 later. In addition, they use the @code{inline} keyword, which is not
1164 C89, but is C99 and is a common extension in pre-C99 compilers. It is
1165 up to the user of these parsers to handle
1166 portability issues. For instance, if using Autoconf and the Autoconf
1167 macro @code{AC_C_INLINE}, a mere
1176 will suffice. Otherwise, we suggest
1180 #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
1186 @node Locations Overview
1189 @cindex textual location
1190 @cindex location, textual
1192 Many applications, like interpreters or compilers, have to produce verbose
1193 and useful error messages. To achieve this, one must be able to keep track of
1194 the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
1195 Bison provides a mechanism for handling these locations.
1197 Each token has a semantic value. In a similar fashion, each token has an
1198 associated location, but the type of locations is the same for all tokens and
1199 groupings. Moreover, the output parser is equipped with a default data
1200 structure for storing locations (@pxref{Locations}, for more details).
1202 Like semantic values, locations can be reached in actions using a dedicated
1203 set of constructs. In the example above, the location of the whole grouping
1204 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1207 When a rule is matched, a default action is used to compute the semantic value
1208 of its left hand side (@pxref{Actions}). In the same way, another default
1209 action is used for locations. However, the action for locations is general
1210 enough for most cases, meaning there is usually no need to describe for each
1211 rule how @code{@@$} should be formed. When building a new location for a given
1212 grouping, the default behavior of the output parser is to take the beginning
1213 of the first symbol, and the end of the last symbol.
1216 @section Bison Output: the Parser File
1217 @cindex Bison parser
1218 @cindex Bison utility
1219 @cindex lexical analyzer, purpose
1222 When you run Bison, you give it a Bison grammar file as input. The output
1223 is a C source file that parses the language described by the grammar.
1224 This file is called a @dfn{Bison parser}. Keep in mind that the Bison
1225 utility and the Bison parser are two distinct programs: the Bison utility
1226 is a program whose output is the Bison parser that becomes part of your
1229 The job of the Bison parser is to group tokens into groupings according to
1230 the grammar rules---for example, to build identifiers and operators into
1231 expressions. As it does this, it runs the actions for the grammar rules it
1234 The tokens come from a function called the @dfn{lexical analyzer} that
1235 you must supply in some fashion (such as by writing it in C). The Bison
1236 parser calls the lexical analyzer each time it wants a new token. It
1237 doesn't know what is ``inside'' the tokens (though their semantic values
1238 may reflect this). Typically the lexical analyzer makes the tokens by
1239 parsing characters of text, but Bison does not depend on this.
1240 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
1242 The Bison parser file is C code which defines a function named
1243 @code{yyparse} which implements that grammar. This function does not make
1244 a complete C program: you must supply some additional functions. One is
1245 the lexical analyzer. Another is an error-reporting function which the
1246 parser calls to report an error. In addition, a complete C program must
1247 start with a function called @code{main}; you have to provide this, and
1248 arrange for it to call @code{yyparse} or the parser will never run.
1249 @xref{Interface, ,Parser C-Language Interface}.
1251 Aside from the token type names and the symbols in the actions you
1252 write, all symbols defined in the Bison parser file itself
1253 begin with @samp{yy} or @samp{YY}. This includes interface functions
1254 such as the lexical analyzer function @code{yylex}, the error reporting
1255 function @code{yyerror} and the parser function @code{yyparse} itself.
1256 This also includes numerous identifiers used for internal purposes.
1257 Therefore, you should avoid using C identifiers starting with @samp{yy}
1258 or @samp{YY} in the Bison grammar file except for the ones defined in
1259 this manual. Also, you should avoid using the C identifiers
1260 @samp{malloc} and @samp{free} for anything other than their usual
1263 In some cases the Bison parser file includes system headers, and in
1264 those cases your code should respect the identifiers reserved by those
1265 headers. On some non-@acronym{GNU} hosts, @code{<alloca.h>}, @code{<malloc.h>},
1266 @code{<stddef.h>}, and @code{<stdlib.h>} are included as needed to
1267 declare memory allocators and related types. @code{<libintl.h>} is
1268 included if message translation is in use
1269 (@pxref{Internationalization}). Other system headers may
1270 be included if you define @code{YYDEBUG} to a nonzero value
1271 (@pxref{Tracing, ,Tracing Your Parser}).
1274 @section Stages in Using Bison
1275 @cindex stages in using Bison
1278 The actual language-design process using Bison, from grammar specification
1279 to a working compiler or interpreter, has these parts:
1283 Formally specify the grammar in a form recognized by Bison
1284 (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
1285 in the language, describe the action that is to be taken when an
1286 instance of that rule is recognized. The action is described by a
1287 sequence of C statements.
1290 Write a lexical analyzer to process input and pass tokens to the parser.
1291 The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
1292 Lexical Analyzer Function @code{yylex}}). It could also be produced
1293 using Lex, but the use of Lex is not discussed in this manual.
1296 Write a controlling function that calls the Bison-produced parser.
1299 Write error-reporting routines.
1302 To turn this source code as written into a runnable program, you
1303 must follow these steps:
1307 Run Bison on the grammar to produce the parser.
1310 Compile the code output by Bison, as well as any other source files.
1313 Link the object files to produce the finished product.
1316 @node Grammar Layout
1317 @section The Overall Layout of a Bison Grammar
1318 @cindex grammar file
1320 @cindex format of grammar file
1321 @cindex layout of Bison grammar
1323 The input file for the Bison utility is a @dfn{Bison grammar file}. The
1324 general form of a Bison grammar file is as follows:
1331 @var{Bison declarations}
1340 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1341 in every Bison grammar file to separate the sections.
1343 The prologue may define types and variables used in the actions. You can
1344 also use preprocessor commands to define macros used there, and use
1345 @code{#include} to include header files that do any of these things.
1346 You need to declare the lexical analyzer @code{yylex} and the error
1347 printer @code{yyerror} here, along with any other global identifiers
1348 used by the actions in the grammar rules.
1350 The Bison declarations declare the names of the terminal and nonterminal
1351 symbols, and may also describe operator precedence and the data types of
1352 semantic values of various symbols.
1354 The grammar rules define how to construct each nonterminal symbol from its
1357 The epilogue can contain any code you want to use. Often the
1358 definitions of functions declared in the prologue go here. In a
1359 simple program, all the rest of the program can go here.
1363 @cindex simple examples
1364 @cindex examples, simple
1366 Now we show and explain three sample programs written using Bison: a
1367 reverse polish notation calculator, an algebraic (infix) notation
1368 calculator, and a multi-function calculator. All three have been tested
1369 under BSD Unix 4.3; each produces a usable, though limited, interactive
1370 desk-top calculator.
1372 These examples are simple, but Bison grammars for real programming
1373 languages are written the same way. You can copy these examples into a
1374 source file to try them.
1377 * RPN Calc:: Reverse polish notation calculator;
1378 a first example with no operator precedence.
1379 * Infix Calc:: Infix (algebraic) notation calculator.
1380 Operator precedence is introduced.
1381 * Simple Error Recovery:: Continuing after syntax errors.
1382 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1383 * Multi-function Calc:: Calculator with memory and trig functions.
1384 It uses multiple data-types for semantic values.
1385 * Exercises:: Ideas for improving the multi-function calculator.
1389 @section Reverse Polish Notation Calculator
1390 @cindex reverse polish notation
1391 @cindex polish notation calculator
1392 @cindex @code{rpcalc}
1393 @cindex calculator, simple
1395 The first example is that of a simple double-precision @dfn{reverse polish
1396 notation} calculator (a calculator using postfix operators). This example
1397 provides a good starting point, since operator precedence is not an issue.
1398 The second example will illustrate how operator precedence is handled.
1400 The source code for this calculator is named @file{rpcalc.y}. The
1401 @samp{.y} extension is a convention used for Bison input files.
1404 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
1405 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1406 * Lexer: Rpcalc Lexer. The lexical analyzer.
1407 * Main: Rpcalc Main. The controlling function.
1408 * Error: Rpcalc Error. The error reporting function.
1409 * Gen: Rpcalc Gen. Running Bison on the grammar file.
1410 * Comp: Rpcalc Compile. Run the C compiler on the output code.
1414 @subsection Declarations for @code{rpcalc}
1416 Here are the C and Bison declarations for the reverse polish notation
1417 calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1420 /* Reverse polish notation calculator. */
1423 #define YYSTYPE double
1426 void yyerror (char const *);
1431 %% /* Grammar rules and actions follow. */
1434 The declarations section (@pxref{Prologue, , The prologue}) contains two
1435 preprocessor directives and two forward declarations.
1437 The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1438 specifying the C data type for semantic values of both tokens and
1439 groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1440 Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1441 don't define it, @code{int} is the default. Because we specify
1442 @code{double}, each token and each expression has an associated value,
1443 which is a floating point number.
1445 The @code{#include} directive is used to declare the exponentiation
1446 function @code{pow}.
1448 The forward declarations for @code{yylex} and @code{yyerror} are
1449 needed because the C language requires that functions be declared
1450 before they are used. These functions will be defined in the
1451 epilogue, but the parser calls them so they must be declared in the
1454 The second section, Bison declarations, provides information to Bison
1455 about the token types (@pxref{Bison Declarations, ,The Bison
1456 Declarations Section}). Each terminal symbol that is not a
1457 single-character literal must be declared here. (Single-character
1458 literals normally don't need to be declared.) In this example, all the
1459 arithmetic operators are designated by single-character literals, so the
1460 only terminal symbol that needs to be declared is @code{NUM}, the token
1461 type for numeric constants.
1464 @subsection Grammar Rules for @code{rpcalc}
1466 Here are the grammar rules for the reverse polish notation calculator.
1474 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1477 exp: NUM @{ $$ = $1; @}
1478 | exp exp '+' @{ $$ = $1 + $2; @}
1479 | exp exp '-' @{ $$ = $1 - $2; @}
1480 | exp exp '*' @{ $$ = $1 * $2; @}
1481 | exp exp '/' @{ $$ = $1 / $2; @}
1482 /* Exponentiation */
1483 | exp exp '^' @{ $$ = pow ($1, $2); @}
1485 | exp 'n' @{ $$ = -$1; @}
1490 The groupings of the rpcalc ``language'' defined here are the expression
1491 (given the name @code{exp}), the line of input (@code{line}), and the
1492 complete input transcript (@code{input}). Each of these nonterminal
1493 symbols has several alternate rules, joined by the vertical bar @samp{|}
1494 which is read as ``or''. The following sections explain what these rules
1497 The semantics of the language is determined by the actions taken when a
1498 grouping is recognized. The actions are the C code that appears inside
1499 braces. @xref{Actions}.
1501 You must specify these actions in C, but Bison provides the means for
1502 passing semantic values between the rules. In each action, the
1503 pseudo-variable @code{$$} stands for the semantic value for the grouping
1504 that the rule is going to construct. Assigning a value to @code{$$} is the
1505 main job of most actions. The semantic values of the components of the
1506 rule are referred to as @code{$1}, @code{$2}, and so on.
1515 @subsubsection Explanation of @code{input}
1517 Consider the definition of @code{input}:
1525 This definition reads as follows: ``A complete input is either an empty
1526 string, or a complete input followed by an input line''. Notice that
1527 ``complete input'' is defined in terms of itself. This definition is said
1528 to be @dfn{left recursive} since @code{input} appears always as the
1529 leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1531 The first alternative is empty because there are no symbols between the
1532 colon and the first @samp{|}; this means that @code{input} can match an
1533 empty string of input (no tokens). We write the rules this way because it
1534 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1535 It's conventional to put an empty alternative first and write the comment
1536 @samp{/* empty */} in it.
1538 The second alternate rule (@code{input line}) handles all nontrivial input.
1539 It means, ``After reading any number of lines, read one more line if
1540 possible.'' The left recursion makes this rule into a loop. Since the
1541 first alternative matches empty input, the loop can be executed zero or
1544 The parser function @code{yyparse} continues to process input until a
1545 grammatical error is seen or the lexical analyzer says there are no more
1546 input tokens; we will arrange for the latter to happen at end-of-input.
1549 @subsubsection Explanation of @code{line}
1551 Now consider the definition of @code{line}:
1555 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1559 The first alternative is a token which is a newline character; this means
1560 that rpcalc accepts a blank line (and ignores it, since there is no
1561 action). The second alternative is an expression followed by a newline.
1562 This is the alternative that makes rpcalc useful. The semantic value of
1563 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1564 question is the first symbol in the alternative. The action prints this
1565 value, which is the result of the computation the user asked for.
1567 This action is unusual because it does not assign a value to @code{$$}. As
1568 a consequence, the semantic value associated with the @code{line} is
1569 uninitialized (its value will be unpredictable). This would be a bug if
1570 that value were ever used, but we don't use it: once rpcalc has printed the
1571 value of the user's input line, that value is no longer needed.
1574 @subsubsection Explanation of @code{expr}
1576 The @code{exp} grouping has several rules, one for each kind of expression.
1577 The first rule handles the simplest expressions: those that are just numbers.
1578 The second handles an addition-expression, which looks like two expressions
1579 followed by a plus-sign. The third handles subtraction, and so on.
1583 | exp exp '+' @{ $$ = $1 + $2; @}
1584 | exp exp '-' @{ $$ = $1 - $2; @}
1589 We have used @samp{|} to join all the rules for @code{exp}, but we could
1590 equally well have written them separately:
1594 exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1595 exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1599 Most of the rules have actions that compute the value of the expression in
1600 terms of the value of its parts. For example, in the rule for addition,
1601 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1602 the second one. The third component, @code{'+'}, has no meaningful
1603 associated semantic value, but if it had one you could refer to it as
1604 @code{$3}. When @code{yyparse} recognizes a sum expression using this
1605 rule, the sum of the two subexpressions' values is produced as the value of
1606 the entire expression. @xref{Actions}.
1608 You don't have to give an action for every rule. When a rule has no
1609 action, Bison by default copies the value of @code{$1} into @code{$$}.
1610 This is what happens in the first rule (the one that uses @code{NUM}).
1612 The formatting shown here is the recommended convention, but Bison does
1613 not require it. You can add or change white space as much as you wish.
1617 exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
1621 means the same thing as this:
1625 | exp exp '+' @{ $$ = $1 + $2; @}
1631 The latter, however, is much more readable.
1634 @subsection The @code{rpcalc} Lexical Analyzer
1635 @cindex writing a lexical analyzer
1636 @cindex lexical analyzer, writing
1638 The lexical analyzer's job is low-level parsing: converting characters
1639 or sequences of characters into tokens. The Bison parser gets its
1640 tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1641 Analyzer Function @code{yylex}}.
1643 Only a simple lexical analyzer is needed for the @acronym{RPN}
1645 lexical analyzer skips blanks and tabs, then reads in numbers as
1646 @code{double} and returns them as @code{NUM} tokens. Any other character
1647 that isn't part of a number is a separate token. Note that the token-code
1648 for such a single-character token is the character itself.
1650 The return value of the lexical analyzer function is a numeric code which
1651 represents a token type. The same text used in Bison rules to stand for
1652 this token type is also a C expression for the numeric code for the type.
1653 This works in two ways. If the token type is a character literal, then its
1654 numeric code is that of the character; you can use the same
1655 character literal in the lexical analyzer to express the number. If the
1656 token type is an identifier, that identifier is defined by Bison as a C
1657 macro whose definition is the appropriate number. In this example,
1658 therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1660 The semantic value of the token (if it has one) is stored into the
1661 global variable @code{yylval}, which is where the Bison parser will look
1662 for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1663 defined at the beginning of the grammar; @pxref{Rpcalc Decls,
1664 ,Declarations for @code{rpcalc}}.)
1666 A token type code of zero is returned if the end-of-input is encountered.
1667 (Bison recognizes any nonpositive value as indicating end-of-input.)
1669 Here is the code for the lexical analyzer:
1673 /* The lexical analyzer returns a double floating point
1674 number on the stack and the token NUM, or the numeric code
1675 of the character read if not a number. It skips all blanks
1676 and tabs, and returns 0 for end-of-input. */
1687 /* Skip white space. */
1688 while ((c = getchar ()) == ' ' || c == '\t')
1692 /* Process numbers. */
1693 if (c == '.' || isdigit (c))
1696 scanf ("%lf", &yylval);
1701 /* Return end-of-input. */
1704 /* Return a single char. */
1711 @subsection The Controlling Function
1712 @cindex controlling function
1713 @cindex main function in simple example
1715 In keeping with the spirit of this example, the controlling function is
1716 kept to the bare minimum. The only requirement is that it call
1717 @code{yyparse} to start the process of parsing.
1730 @subsection The Error Reporting Routine
1731 @cindex error reporting routine
1733 When @code{yyparse} detects a syntax error, it calls the error reporting
1734 function @code{yyerror} to print an error message (usually but not
1735 always @code{"syntax error"}). It is up to the programmer to supply
1736 @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1737 here is the definition we will use:
1743 /* Called by yyparse on error. */
1745 yyerror (char const *s)
1747 fprintf (stderr, "%s\n", s);
1752 After @code{yyerror} returns, the Bison parser may recover from the error
1753 and continue parsing if the grammar contains a suitable error rule
1754 (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1755 have not written any error rules in this example, so any invalid input will
1756 cause the calculator program to exit. This is not clean behavior for a
1757 real calculator, but it is adequate for the first example.
1760 @subsection Running Bison to Make the Parser
1761 @cindex running Bison (introduction)
1763 Before running Bison to produce a parser, we need to decide how to
1764 arrange all the source code in one or more source files. For such a
1765 simple example, the easiest thing is to put everything in one file. The
1766 definitions of @code{yylex}, @code{yyerror} and @code{main} go at the
1767 end, in the epilogue of the file
1768 (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1770 For a large project, you would probably have several source files, and use
1771 @code{make} to arrange to recompile them.
1773 With all the source in a single file, you use the following command to
1774 convert it into a parser file:
1781 In this example the file was called @file{rpcalc.y} (for ``Reverse Polish
1782 @sc{calc}ulator''). Bison produces a file named @file{@var{file}.tab.c},
1783 removing the @samp{.y} from the original file name. The file output by
1784 Bison contains the source code for @code{yyparse}. The additional
1785 functions in the input file (@code{yylex}, @code{yyerror} and @code{main})
1786 are copied verbatim to the output.
1788 @node Rpcalc Compile
1789 @subsection Compiling the Parser File
1790 @cindex compiling the parser
1792 Here is how to compile and run the parser file:
1796 # @r{List files in current directory.}
1798 rpcalc.tab.c rpcalc.y
1802 # @r{Compile the Bison parser.}
1803 # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1804 $ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
1808 # @r{List files again.}
1810 rpcalc rpcalc.tab.c rpcalc.y
1814 The file @file{rpcalc} now contains the executable code. Here is an
1815 example session using @code{rpcalc}.
1821 @kbd{3 7 + 3 4 5 *+-}
1823 @kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
1827 @kbd{3 4 ^} @r{Exponentiation}
1829 @kbd{^D} @r{End-of-file indicator}
1834 @section Infix Notation Calculator: @code{calc}
1835 @cindex infix notation calculator
1837 @cindex calculator, infix notation
1839 We now modify rpcalc to handle infix operators instead of postfix. Infix
1840 notation involves the concept of operator precedence and the need for
1841 parentheses nested to arbitrary depth. Here is the Bison code for
1842 @file{calc.y}, an infix desk-top calculator.
1845 /* Infix notation calculator. */
1848 #define YYSTYPE double
1852 void yyerror (char const *);
1855 /* Bison declarations. */
1859 %left NEG /* negation--unary minus */
1860 %right '^' /* exponentiation */
1862 %% /* The grammar follows. */
1868 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1871 exp: NUM @{ $$ = $1; @}
1872 | exp '+' exp @{ $$ = $1 + $3; @}
1873 | exp '-' exp @{ $$ = $1 - $3; @}
1874 | exp '*' exp @{ $$ = $1 * $3; @}
1875 | exp '/' exp @{ $$ = $1 / $3; @}
1876 | '-' exp %prec NEG @{ $$ = -$2; @}
1877 | exp '^' exp @{ $$ = pow ($1, $3); @}
1878 | '(' exp ')' @{ $$ = $2; @}
1884 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1887 There are two important new features shown in this code.
1889 In the second section (Bison declarations), @code{%left} declares token
1890 types and says they are left-associative operators. The declarations
1891 @code{%left} and @code{%right} (right associativity) take the place of
1892 @code{%token} which is used to declare a token type name without
1893 associativity. (These tokens are single-character literals, which
1894 ordinarily don't need to be declared. We declare them here to specify
1897 Operator precedence is determined by the line ordering of the
1898 declarations; the higher the line number of the declaration (lower on
1899 the page or screen), the higher the precedence. Hence, exponentiation
1900 has the highest precedence, unary minus (@code{NEG}) is next, followed
1901 by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator
1904 The other important new feature is the @code{%prec} in the grammar
1905 section for the unary minus operator. The @code{%prec} simply instructs
1906 Bison that the rule @samp{| '-' exp} has the same precedence as
1907 @code{NEG}---in this case the next-to-highest. @xref{Contextual
1908 Precedence, ,Context-Dependent Precedence}.
1910 Here is a sample run of @file{calc.y}:
1915 @kbd{4 + 4.5 - (34/(8*3+-3))}
1923 @node Simple Error Recovery
1924 @section Simple Error Recovery
1925 @cindex error recovery, simple
1927 Up to this point, this manual has not addressed the issue of @dfn{error
1928 recovery}---how to continue parsing after the parser detects a syntax
1929 error. All we have handled is error reporting with @code{yyerror}.
1930 Recall that by default @code{yyparse} returns after calling
1931 @code{yyerror}. This means that an erroneous input line causes the
1932 calculator program to exit. Now we show how to rectify this deficiency.
1934 The Bison language itself includes the reserved word @code{error}, which
1935 may be included in the grammar rules. In the example below it has
1936 been added to one of the alternatives for @code{line}:
1941 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1942 | error '\n' @{ yyerrok; @}
1947 This addition to the grammar allows for simple error recovery in the
1948 event of a syntax error. If an expression that cannot be evaluated is
1949 read, the error will be recognized by the third rule for @code{line},
1950 and parsing will continue. (The @code{yyerror} function is still called
1951 upon to print its message as well.) The action executes the statement
1952 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
1953 that error recovery is complete (@pxref{Error Recovery}). Note the
1954 difference between @code{yyerrok} and @code{yyerror}; neither one is a
1957 This form of error recovery deals with syntax errors. There are other
1958 kinds of errors; for example, division by zero, which raises an exception
1959 signal that is normally fatal. A real calculator program must handle this
1960 signal and use @code{longjmp} to return to @code{main} and resume parsing
1961 input lines; it would also have to discard the rest of the current line of
1962 input. We won't discuss this issue further because it is not specific to
1965 @node Location Tracking Calc
1966 @section Location Tracking Calculator: @code{ltcalc}
1967 @cindex location tracking calculator
1968 @cindex @code{ltcalc}
1969 @cindex calculator, location tracking
1971 This example extends the infix notation calculator with location
1972 tracking. This feature will be used to improve the error messages. For
1973 the sake of clarity, this example is a simple integer calculator, since
1974 most of the work needed to use locations will be done in the lexical
1978 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
1979 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
1980 * Lexer: Ltcalc Lexer. The lexical analyzer.
1984 @subsection Declarations for @code{ltcalc}
1986 The C and Bison declarations for the location tracking calculator are
1987 the same as the declarations for the infix notation calculator.
1990 /* Location tracking calculator. */
1996 void yyerror (char const *);
1999 /* Bison declarations. */
2007 %% /* The grammar follows. */
2011 Note there are no declarations specific to locations. Defining a data
2012 type for storing locations is not needed: we will use the type provided
2013 by default (@pxref{Location Type, ,Data Types of Locations}), which is a
2014 four member structure with the following integer fields:
2015 @code{first_line}, @code{first_column}, @code{last_line} and
2016 @code{last_column}. By conventions, and in accordance with the GNU
2017 Coding Standards and common practice, the line and column count both
2021 @subsection Grammar Rules for @code{ltcalc}
2023 Whether handling locations or not has no effect on the syntax of your
2024 language. Therefore, grammar rules for this example will be very close
2025 to those of the previous example: we will only modify them to benefit
2026 from the new information.
2028 Here, we will use locations to report divisions by zero, and locate the
2029 wrong expressions or subexpressions.
2040 | exp '\n' @{ printf ("%d\n", $1); @}
2045 exp : NUM @{ $$ = $1; @}
2046 | exp '+' exp @{ $$ = $1 + $3; @}
2047 | exp '-' exp @{ $$ = $1 - $3; @}
2048 | exp '*' exp @{ $$ = $1 * $3; @}
2058 fprintf (stderr, "%d.%d-%d.%d: division by zero",
2059 @@3.first_line, @@3.first_column,
2060 @@3.last_line, @@3.last_column);
2065 | '-' exp %prec NEG @{ $$ = -$2; @}
2066 | exp '^' exp @{ $$ = pow ($1, $3); @}
2067 | '(' exp ')' @{ $$ = $2; @}
2071 This code shows how to reach locations inside of semantic actions, by
2072 using the pseudo-variables @code{@@@var{n}} for rule components, and the
2073 pseudo-variable @code{@@$} for groupings.
2075 We don't need to assign a value to @code{@@$}: the output parser does it
2076 automatically. By default, before executing the C code of each action,
2077 @code{@@$} is set to range from the beginning of @code{@@1} to the end
2078 of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
2079 can be redefined (@pxref{Location Default Action, , Default Action for
2080 Locations}), and for very specific rules, @code{@@$} can be computed by
2084 @subsection The @code{ltcalc} Lexical Analyzer.
2086 Until now, we relied on Bison's defaults to enable location
2087 tracking. The next step is to rewrite the lexical analyzer, and make it
2088 able to feed the parser with the token locations, as it already does for
2091 To this end, we must take into account every single character of the
2092 input text, to avoid the computed locations of being fuzzy or wrong:
2103 /* Skip white space. */
2104 while ((c = getchar ()) == ' ' || c == '\t')
2105 ++yylloc.last_column;
2110 yylloc.first_line = yylloc.last_line;
2111 yylloc.first_column = yylloc.last_column;
2115 /* Process numbers. */
2119 ++yylloc.last_column;
2120 while (isdigit (c = getchar ()))
2122 ++yylloc.last_column;
2123 yylval = yylval * 10 + c - '0';
2130 /* Return end-of-input. */
2134 /* Return a single char, and update location. */
2138 yylloc.last_column = 0;
2141 ++yylloc.last_column;
2146 Basically, the lexical analyzer performs the same processing as before:
2147 it skips blanks and tabs, and reads numbers or single-character tokens.
2148 In addition, it updates @code{yylloc}, the global variable (of type
2149 @code{YYLTYPE}) containing the token's location.
2151 Now, each time this function returns a token, the parser has its number
2152 as well as its semantic value, and its location in the text. The last
2153 needed change is to initialize @code{yylloc}, for example in the
2154 controlling function:
2161 yylloc.first_line = yylloc.last_line = 1;
2162 yylloc.first_column = yylloc.last_column = 0;
2168 Remember that computing locations is not a matter of syntax. Every
2169 character must be associated to a location update, whether it is in
2170 valid input, in comments, in literal strings, and so on.
2172 @node Multi-function Calc
2173 @section Multi-Function Calculator: @code{mfcalc}
2174 @cindex multi-function calculator
2175 @cindex @code{mfcalc}
2176 @cindex calculator, multi-function
2178 Now that the basics of Bison have been discussed, it is time to move on to
2179 a more advanced problem. The above calculators provided only five
2180 functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
2181 be nice to have a calculator that provides other mathematical functions such
2182 as @code{sin}, @code{cos}, etc.
2184 It is easy to add new operators to the infix calculator as long as they are
2185 only single-character literals. The lexical analyzer @code{yylex} passes
2186 back all nonnumeric characters as tokens, so new grammar rules suffice for
2187 adding a new operator. But we want something more flexible: built-in
2188 functions whose syntax has this form:
2191 @var{function_name} (@var{argument})
2195 At the same time, we will add memory to the calculator, by allowing you
2196 to create named variables, store values in them, and use them later.
2197 Here is a sample session with the multi-function calculator:
2201 @kbd{pi = 3.141592653589}
2205 @kbd{alpha = beta1 = 2.3}
2211 @kbd{exp(ln(beta1))}
2216 Note that multiple assignment and nested function calls are permitted.
2219 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
2220 * Rules: Mfcalc Rules. Grammar rules for the calculator.
2221 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
2225 @subsection Declarations for @code{mfcalc}
2227 Here are the C and Bison declarations for the multi-function calculator.
2232 #include <math.h> /* For math functions, cos(), sin(), etc. */
2233 #include "calc.h" /* Contains definition of `symrec'. */
2235 void yyerror (char const *);
2240 double val; /* For returning numbers. */
2241 symrec *tptr; /* For returning symbol-table pointers. */
2244 %token <val> NUM /* Simple double precision number. */
2245 %token <tptr> VAR FNCT /* Variable and Function. */
2252 %left NEG /* negation--unary minus */
2253 %right '^' /* exponentiation */
2255 %% /* The grammar follows. */
2258 The above grammar introduces only two new features of the Bison language.
2259 These features allow semantic values to have various data types
2260 (@pxref{Multiple Types, ,More Than One Value Type}).
2262 The @code{%union} declaration specifies the entire list of possible types;
2263 this is instead of defining @code{YYSTYPE}. The allowable types are now
2264 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
2265 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
2267 Since values can now have various types, it is necessary to associate a
2268 type with each grammar symbol whose semantic value is used. These symbols
2269 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
2270 declarations are augmented with information about their data type (placed
2271 between angle brackets).
2273 The Bison construct @code{%type} is used for declaring nonterminal
2274 symbols, just as @code{%token} is used for declaring token types. We
2275 have not used @code{%type} before because nonterminal symbols are
2276 normally declared implicitly by the rules that define them. But
2277 @code{exp} must be declared explicitly so we can specify its value type.
2278 @xref{Type Decl, ,Nonterminal Symbols}.
2281 @subsection Grammar Rules for @code{mfcalc}
2283 Here are the grammar rules for the multi-function calculator.
2284 Most of them are copied directly from @code{calc}; three rules,
2285 those which mention @code{VAR} or @code{FNCT}, are new.
2297 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2298 | error '\n' @{ yyerrok; @}
2303 exp: NUM @{ $$ = $1; @}
2304 | VAR @{ $$ = $1->value.var; @}
2305 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
2306 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
2307 | exp '+' exp @{ $$ = $1 + $3; @}
2308 | exp '-' exp @{ $$ = $1 - $3; @}
2309 | exp '*' exp @{ $$ = $1 * $3; @}
2310 | exp '/' exp @{ $$ = $1 / $3; @}
2311 | '-' exp %prec NEG @{ $$ = -$2; @}
2312 | exp '^' exp @{ $$ = pow ($1, $3); @}
2313 | '(' exp ')' @{ $$ = $2; @}
2316 /* End of grammar. */
2321 @subsection The @code{mfcalc} Symbol Table
2322 @cindex symbol table example
2324 The multi-function calculator requires a symbol table to keep track of the
2325 names and meanings of variables and functions. This doesn't affect the
2326 grammar rules (except for the actions) or the Bison declarations, but it
2327 requires some additional C functions for support.
2329 The symbol table itself consists of a linked list of records. Its
2330 definition, which is kept in the header @file{calc.h}, is as follows. It
2331 provides for either functions or variables to be placed in the table.
2335 /* Function type. */
2336 typedef double (*func_t) (double);
2340 /* Data type for links in the chain of symbols. */
2343 char *name; /* name of symbol */
2344 int type; /* type of symbol: either VAR or FNCT */
2347 double var; /* value of a VAR */
2348 func_t fnctptr; /* value of a FNCT */
2350 struct symrec *next; /* link field */
2355 typedef struct symrec symrec;
2357 /* The symbol table: a chain of `struct symrec'. */
2358 extern symrec *sym_table;
2360 symrec *putsym (char const *, int);
2361 symrec *getsym (char const *);
2365 The new version of @code{main} includes a call to @code{init_table}, a
2366 function that initializes the symbol table. Here it is, and
2367 @code{init_table} as well:
2373 /* Called by yyparse on error. */
2375 yyerror (char const *s)
2385 double (*fnct) (double);
2390 struct init const arith_fncts[] =
2403 /* The symbol table: a chain of `struct symrec'. */
2408 /* Put arithmetic functions in table. */
2414 for (i = 0; arith_fncts[i].fname != 0; i++)
2416 ptr = putsym (arith_fncts[i].fname, FNCT);
2417 ptr->value.fnctptr = arith_fncts[i].fnct;
2432 By simply editing the initialization list and adding the necessary include
2433 files, you can add additional functions to the calculator.
2435 Two important functions allow look-up and installation of symbols in the
2436 symbol table. The function @code{putsym} is passed a name and the type
2437 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2438 linked to the front of the list, and a pointer to the object is returned.
2439 The function @code{getsym} is passed the name of the symbol to look up. If
2440 found, a pointer to that symbol is returned; otherwise zero is returned.
2444 putsym (char const *sym_name, int sym_type)
2447 ptr = (symrec *) malloc (sizeof (symrec));
2448 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2449 strcpy (ptr->name,sym_name);
2450 ptr->type = sym_type;
2451 ptr->value.var = 0; /* Set value to 0 even if fctn. */
2452 ptr->next = (struct symrec *)sym_table;
2458 getsym (char const *sym_name)
2461 for (ptr = sym_table; ptr != (symrec *) 0;
2462 ptr = (symrec *)ptr->next)
2463 if (strcmp (ptr->name,sym_name) == 0)
2469 The function @code{yylex} must now recognize variables, numeric values, and
2470 the single-character arithmetic operators. Strings of alphanumeric
2471 characters with a leading letter are recognized as either variables or
2472 functions depending on what the symbol table says about them.
2474 The string is passed to @code{getsym} for look up in the symbol table. If
2475 the name appears in the table, a pointer to its location and its type
2476 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2477 already in the table, then it is installed as a @code{VAR} using
2478 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2479 returned to @code{yyparse}.
2481 No change is needed in the handling of numeric values and arithmetic
2482 operators in @code{yylex}.
2495 /* Ignore white space, get first nonwhite character. */
2496 while ((c = getchar ()) == ' ' || c == '\t');
2503 /* Char starts a number => parse the number. */
2504 if (c == '.' || isdigit (c))
2507 scanf ("%lf", &yylval.val);
2513 /* Char starts an identifier => read the name. */
2517 static char *symbuf = 0;
2518 static int length = 0;
2523 /* Initially make the buffer long enough
2524 for a 40-character symbol name. */
2526 length = 40, symbuf = (char *)malloc (length + 1);
2533 /* If buffer is full, make it bigger. */
2537 symbuf = (char *) realloc (symbuf, length + 1);
2539 /* Add this character to the buffer. */
2541 /* Get another character. */
2546 while (isalnum (c));
2553 s = getsym (symbuf);
2555 s = putsym (symbuf, VAR);
2560 /* Any other character is a token by itself. */
2566 This program is both powerful and flexible. You may easily add new
2567 functions, and it is a simple job to modify this code to install
2568 predefined variables such as @code{pi} or @code{e} as well.
2576 Add some new functions from @file{math.h} to the initialization list.
2579 Add another array that contains constants and their values. Then
2580 modify @code{init_table} to add these constants to the symbol table.
2581 It will be easiest to give the constants type @code{VAR}.
2584 Make the program report an error if the user refers to an
2585 uninitialized variable in any way except to store a value in it.
2589 @chapter Bison Grammar Files
2591 Bison takes as input a context-free grammar specification and produces a
2592 C-language function that recognizes correct instances of the grammar.
2594 The Bison grammar input file conventionally has a name ending in @samp{.y}.
2595 @xref{Invocation, ,Invoking Bison}.
2598 * Grammar Outline:: Overall layout of the grammar file.
2599 * Symbols:: Terminal and nonterminal symbols.
2600 * Rules:: How to write grammar rules.
2601 * Recursion:: Writing recursive rules.
2602 * Semantics:: Semantic values and actions.
2603 * Locations:: Locations and actions.
2604 * Declarations:: All kinds of Bison declarations are described here.
2605 * Multiple Parsers:: Putting more than one Bison parser in one program.
2608 @node Grammar Outline
2609 @section Outline of a Bison Grammar
2611 A Bison grammar file has four main sections, shown here with the
2612 appropriate delimiters:
2619 @var{Bison declarations}
2628 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2629 As a @acronym{GNU} extension, @samp{//} introduces a comment that
2630 continues until end of line.
2633 * Prologue:: Syntax and usage of the prologue.
2634 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
2635 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2636 * Grammar Rules:: Syntax and usage of the grammar rules section.
2637 * Epilogue:: Syntax and usage of the epilogue.
2641 @subsection The prologue
2642 @cindex declarations section
2644 @cindex declarations
2646 The @var{Prologue} section contains macro definitions and declarations
2647 of functions and variables that are used in the actions in the grammar
2648 rules. These are copied to the beginning of the parser file so that
2649 they precede the definition of @code{yyparse}. You can use
2650 @samp{#include} to get the declarations from a header file. If you
2651 don't need any C declarations, you may omit the @samp{%@{} and
2652 @samp{%@}} delimiters that bracket this section.
2654 The @var{Prologue} section is terminated by the first occurrence
2655 of @samp{%@}} that is outside a comment, a string literal, or a
2658 You may have more than one @var{Prologue} section, intermixed with the
2659 @var{Bison declarations}. This allows you to have C and Bison
2660 declarations that refer to each other. For example, the @code{%union}
2661 declaration may use types defined in a header file, and you may wish to
2662 prototype functions that take arguments of type @code{YYSTYPE}. This
2663 can be done with two @var{Prologue} blocks, one before and one after the
2664 @code{%union} declaration.
2675 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2679 static void print_token_value (FILE *, int, YYSTYPE);
2680 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2686 When in doubt, it is usually safer to put prologue code before all
2687 Bison declarations, rather than after. For example, any definitions
2688 of feature test macros like @code{_GNU_SOURCE} or
2689 @code{_POSIX_C_SOURCE} should appear before all Bison declarations, as
2690 feature test macros can affect the behavior of Bison-generated
2691 @code{#include} directives.
2693 @node Prologue Alternatives
2694 @subsection Prologue Alternatives
2695 @cindex Prologue Alternatives
2698 @findex %code requires
2699 @findex %code provides
2701 (The prologue alternatives described here are experimental.
2702 More user feedback will help to determine whether they should become permanent
2705 The functionality of @var{Prologue} sections can often be subtle and
2707 As an alternative, Bison provides a %code directive with an explicit qualifier
2708 field, which identifies the purpose of the code and thus the location(s) where
2709 Bison should generate it.
2710 For C/C++, the qualifier can be omitted for the default location, or it can be
2711 one of @code{requires}, @code{provides}, @code{top}.
2712 @xref{Decl Summary,,%code}.
2714 Look again at the example of the previous section:
2725 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2729 static void print_token_value (FILE *, int, YYSTYPE);
2730 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2737 Notice that there are two @var{Prologue} sections here, but there's a subtle
2738 distinction between their functionality.
2739 For example, if you decide to override Bison's default definition for
2740 @code{YYLTYPE}, in which @var{Prologue} section should you write your new
2742 You should write it in the first since Bison will insert that code into the
2743 parser source code file @emph{before} the default @code{YYLTYPE} definition.
2744 In which @var{Prologue} section should you prototype an internal function,
2745 @code{trace_token}, that accepts @code{YYLTYPE} and @code{yytokentype} as
2747 You should prototype it in the second since Bison will insert that code
2748 @emph{after} the @code{YYLTYPE} and @code{yytokentype} definitions.
2750 This distinction in functionality between the two @var{Prologue} sections is
2751 established by the appearance of the @code{%union} between them.
2752 This behavior raises a few questions.
2753 First, why should the position of a @code{%union} affect definitions related to
2754 @code{YYLTYPE} and @code{yytokentype}?
2755 Second, what if there is no @code{%union}?
2756 In that case, the second kind of @var{Prologue} section is not available.
2757 This behavior is not intuitive.
2759 To avoid this subtle @code{%union} dependency, rewrite the example using a
2760 @code{%code top} and an unqualified @code{%code}.
2761 Let's go ahead and add the new @code{YYLTYPE} definition and the
2762 @code{trace_token} prototype at the same time:
2769 /* WARNING: The following code really belongs
2770 * in a `%code requires'; see below. */
2773 #define YYLTYPE YYLTYPE
2774 typedef struct YYLTYPE
2786 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2790 static void print_token_value (FILE *, int, YYSTYPE);
2791 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2792 static void trace_token (enum yytokentype token, YYLTYPE loc);
2799 In this way, @code{%code top} and the unqualified @code{%code} achieve the same
2800 functionality as the two kinds of @var{Prologue} sections, but it's always
2801 explicit which kind you intend.
2802 Moreover, both kinds are always available even in the absence of @code{%union}.
2804 The @code{%code top} block above logically contains two parts.
2805 The first two lines before the warning need to appear near the top of the
2806 parser source code file.
2807 The first line after the warning is required by @code{YYSTYPE} and thus also
2808 needs to appear in the parser source code file.
2809 However, if you've instructed Bison to generate a parser header file
2810 (@pxref{Decl Summary, ,%defines}), you probably want that line to appear before
2811 the @code{YYSTYPE} definition in that header file as well.
2812 The @code{YYLTYPE} definition should also appear in the parser header file to
2813 override the default @code{YYLTYPE} definition there.
2815 In other words, in the @code{%code top} block above, all but the first two
2816 lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
2818 Thus, they belong in one or more @code{%code requires}:
2831 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2835 #define YYLTYPE YYLTYPE
2836 typedef struct YYLTYPE
2847 static void print_token_value (FILE *, int, YYSTYPE);
2848 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2849 static void trace_token (enum yytokentype token, YYLTYPE loc);
2856 Now Bison will insert @code{#include "ptypes.h"} and the new @code{YYLTYPE}
2857 definition before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
2858 definitions in both the parser source code file and the parser header file.
2859 (By the same reasoning, @code{%code requires} would also be the appropriate
2860 place to write your own definition for @code{YYSTYPE}.)
2862 When you are writing dependency code for @code{YYSTYPE} and @code{YYLTYPE}, you
2863 should prefer @code{%code requires} over @code{%code top} regardless of whether
2864 you instruct Bison to generate a parser header file.
2865 When you are writing code that you need Bison to insert only into the parser
2866 source code file and that has no special need to appear at the top of that
2867 file, you should prefer the unqualified @code{%code} over @code{%code top}.
2868 These practices will make the purpose of each block of your code explicit to
2869 Bison and to other developers reading your grammar file.
2870 Following these practices, we expect the unqualified @code{%code} and
2871 @code{%code requires} to be the most important of the four @var{Prologue}
2874 At some point while developing your parser, you might decide to provide
2875 @code{trace_token} to modules that are external to your parser.
2876 Thus, you might wish for Bison to insert the prototype into both the parser
2877 header file and the parser source code file.
2878 Since this function is not a dependency required by @code{YYSTYPE} or
2879 @code{YYLTYPE}, it doesn't make sense to move its prototype to a
2880 @code{%code requires}.
2881 More importantly, since it depends upon @code{YYLTYPE} and @code{yytokentype},
2882 @code{%code requires} is not sufficient.
2883 Instead, move its prototype from the unqualified @code{%code} to a
2884 @code{%code provides}:
2897 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2901 #define YYLTYPE YYLTYPE
2902 typedef struct YYLTYPE
2913 void trace_token (enum yytokentype token, YYLTYPE loc);
2917 static void print_token_value (FILE *, int, YYSTYPE);
2918 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2925 Bison will insert the @code{trace_token} prototype into both the parser header
2926 file and the parser source code file after the definitions for
2927 @code{yytokentype}, @code{YYLTYPE}, and @code{YYSTYPE}.
2929 The above examples are careful to write directives in an order that reflects
2930 the layout of the generated parser source code and header files:
2931 @code{%code top}, @code{%code requires}, @code{%code provides}, and then
2933 While your grammar files may generally be easier to read if you also follow
2934 this order, Bison does not require it.
2935 Instead, Bison lets you choose an organization that makes sense to you.
2937 You may declare any of these directives multiple times in the grammar file.
2938 In that case, Bison concatenates the contained code in declaration order.
2939 This is the only way in which the position of one of these directives within
2940 the grammar file affects its functionality.
2942 The result of the previous two properties is greater flexibility in how you may
2943 organize your grammar file.
2944 For example, you may organize semantic-type-related directives by semantic
2948 %code requires @{ #include "type1.h" @}
2949 %union @{ type1 field1; @}
2950 %destructor @{ type1_free ($$); @} <field1>
2951 %printer @{ type1_print ($$); @} <field1>
2953 %code requires @{ #include "type2.h" @}
2954 %union @{ type2 field2; @}
2955 %destructor @{ type2_free ($$); @} <field2>
2956 %printer @{ type2_print ($$); @} <field2>
2960 You could even place each of the above directive groups in the rules section of
2961 the grammar file next to the set of rules that uses the associated semantic
2963 (In the rules section, you must terminate each of those directives with a
2965 And you don't have to worry that some directive (like a @code{%union}) in the
2966 definitions section is going to adversely affect their functionality in some
2967 counter-intuitive manner just because it comes first.
2968 Such an organization is not possible using @var{Prologue} sections.
2970 This section has been concerned with explaining the advantages of the four
2971 @var{Prologue} alternatives over the original Yacc @var{Prologue}.
2972 However, in most cases when using these directives, you shouldn't need to
2973 think about all the low-level ordering issues discussed here.
2974 Instead, you should simply use these directives to label each block of your
2975 code according to its purpose and let Bison handle the ordering.
2976 @code{%code} is the most generic label.
2977 Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
2980 @node Bison Declarations
2981 @subsection The Bison Declarations Section
2982 @cindex Bison declarations (introduction)
2983 @cindex declarations, Bison (introduction)
2985 The @var{Bison declarations} section contains declarations that define
2986 terminal and nonterminal symbols, specify precedence, and so on.
2987 In some simple grammars you may not need any declarations.
2988 @xref{Declarations, ,Bison Declarations}.
2991 @subsection The Grammar Rules Section
2992 @cindex grammar rules section
2993 @cindex rules section for grammar
2995 The @dfn{grammar rules} section contains one or more Bison grammar
2996 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
2998 There must always be at least one grammar rule, and the first
2999 @samp{%%} (which precedes the grammar rules) may never be omitted even
3000 if it is the first thing in the file.
3003 @subsection The epilogue
3004 @cindex additional C code section
3006 @cindex C code, section for additional
3008 The @var{Epilogue} is copied verbatim to the end of the parser file, just as
3009 the @var{Prologue} is copied to the beginning. This is the most convenient
3010 place to put anything that you want to have in the parser file but which need
3011 not come before the definition of @code{yyparse}. For example, the
3012 definitions of @code{yylex} and @code{yyerror} often go here. Because
3013 C requires functions to be declared before being used, you often need
3014 to declare functions like @code{yylex} and @code{yyerror} in the Prologue,
3015 even if you define them in the Epilogue.
3016 @xref{Interface, ,Parser C-Language Interface}.
3018 If the last section is empty, you may omit the @samp{%%} that separates it
3019 from the grammar rules.
3021 The Bison parser itself contains many macros and identifiers whose names
3022 start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3023 any such names (except those documented in this manual) in the epilogue
3024 of the grammar file.
3027 @section Symbols, Terminal and Nonterminal
3028 @cindex nonterminal symbol
3029 @cindex terminal symbol
3033 @dfn{Symbols} in Bison grammars represent the grammatical classifications
3036 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
3037 class of syntactically equivalent tokens. You use the symbol in grammar
3038 rules to mean that a token in that class is allowed. The symbol is
3039 represented in the Bison parser by a numeric code, and the @code{yylex}
3040 function returns a token type code to indicate what kind of token has
3041 been read. You don't need to know what the code value is; you can use
3042 the symbol to stand for it.
3044 A @dfn{nonterminal symbol} stands for a class of syntactically
3045 equivalent groupings. The symbol name is used in writing grammar rules.
3046 By convention, it should be all lower case.
3048 Symbol names can contain letters, digits (not at the beginning),
3049 underscores and periods. Periods make sense only in nonterminals.
3051 There are three ways of writing terminal symbols in the grammar:
3055 A @dfn{named token type} is written with an identifier, like an
3056 identifier in C@. By convention, it should be all upper case. Each
3057 such name must be defined with a Bison declaration such as
3058 @code{%token}. @xref{Token Decl, ,Token Type Names}.
3061 @cindex character token
3062 @cindex literal token
3063 @cindex single-character literal
3064 A @dfn{character token type} (or @dfn{literal character token}) is
3065 written in the grammar using the same syntax used in C for character
3066 constants; for example, @code{'+'} is a character token type. A
3067 character token type doesn't need to be declared unless you need to
3068 specify its semantic value data type (@pxref{Value Type, ,Data Types of
3069 Semantic Values}), associativity, or precedence (@pxref{Precedence,
3070 ,Operator Precedence}).
3072 By convention, a character token type is used only to represent a
3073 token that consists of that particular character. Thus, the token
3074 type @code{'+'} is used to represent the character @samp{+} as a
3075 token. Nothing enforces this convention, but if you depart from it,
3076 your program will confuse other readers.
3078 All the usual escape sequences used in character literals in C can be
3079 used in Bison as well, but you must not use the null character as a
3080 character literal because its numeric code, zero, signifies
3081 end-of-input (@pxref{Calling Convention, ,Calling Convention
3082 for @code{yylex}}). Also, unlike standard C, trigraphs have no
3083 special meaning in Bison character literals, nor is backslash-newline
3087 @cindex string token
3088 @cindex literal string token
3089 @cindex multicharacter literal
3090 A @dfn{literal string token} is written like a C string constant; for
3091 example, @code{"<="} is a literal string token. A literal string token
3092 doesn't need to be declared unless you need to specify its semantic
3093 value data type (@pxref{Value Type}), associativity, or precedence
3094 (@pxref{Precedence}).
3096 You can associate the literal string token with a symbolic name as an
3097 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
3098 Declarations}). If you don't do that, the lexical analyzer has to
3099 retrieve the token number for the literal string token from the
3100 @code{yytname} table (@pxref{Calling Convention}).
3102 @strong{Warning}: literal string tokens do not work in Yacc.
3104 By convention, a literal string token is used only to represent a token
3105 that consists of that particular string. Thus, you should use the token
3106 type @code{"<="} to represent the string @samp{<=} as a token. Bison
3107 does not enforce this convention, but if you depart from it, people who
3108 read your program will be confused.
3110 All the escape sequences used in string literals in C can be used in
3111 Bison as well, except that you must not use a null character within a
3112 string literal. Also, unlike Standard C, trigraphs have no special
3113 meaning in Bison string literals, nor is backslash-newline allowed. A
3114 literal string token must contain two or more characters; for a token
3115 containing just one character, use a character token (see above).
3118 How you choose to write a terminal symbol has no effect on its
3119 grammatical meaning. That depends only on where it appears in rules and
3120 on when the parser function returns that symbol.
3122 The value returned by @code{yylex} is always one of the terminal
3123 symbols, except that a zero or negative value signifies end-of-input.
3124 Whichever way you write the token type in the grammar rules, you write
3125 it the same way in the definition of @code{yylex}. The numeric code
3126 for a character token type is simply the positive numeric code of the
3127 character, so @code{yylex} can use the identical value to generate the
3128 requisite code, though you may need to convert it to @code{unsigned
3129 char} to avoid sign-extension on hosts where @code{char} is signed.
3130 Each named token type becomes a C macro in
3131 the parser file, so @code{yylex} can use the name to stand for the code.
3132 (This is why periods don't make sense in terminal symbols.)
3133 @xref{Calling Convention, ,Calling Convention for @code{yylex}}.
3135 If @code{yylex} is defined in a separate file, you need to arrange for the
3136 token-type macro definitions to be available there. Use the @samp{-d}
3137 option when you run Bison, so that it will write these macro definitions
3138 into a separate header file @file{@var{name}.tab.h} which you can include
3139 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
3141 If you want to write a grammar that is portable to any Standard C
3142 host, you must use only nonnull character tokens taken from the basic
3143 execution character set of Standard C@. This set consists of the ten
3144 digits, the 52 lower- and upper-case English letters, and the
3145 characters in the following C-language string:
3148 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3151 The @code{yylex} function and Bison must use a consistent character set
3152 and encoding for character tokens. For example, if you run Bison in an
3153 @acronym{ASCII} environment, but then compile and run the resulting
3154 program in an environment that uses an incompatible character set like
3155 @acronym{EBCDIC}, the resulting program may not work because the tables
3156 generated by Bison will assume @acronym{ASCII} numeric values for
3157 character tokens. It is standard practice for software distributions to
3158 contain C source files that were generated by Bison in an
3159 @acronym{ASCII} environment, so installers on platforms that are
3160 incompatible with @acronym{ASCII} must rebuild those files before
3163 The symbol @code{error} is a terminal symbol reserved for error recovery
3164 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
3165 In particular, @code{yylex} should never return this value. The default
3166 value of the error token is 256, unless you explicitly assigned 256 to
3167 one of your tokens with a @code{%token} declaration.
3170 @section Syntax of Grammar Rules
3172 @cindex grammar rule syntax
3173 @cindex syntax of grammar rules
3175 A Bison grammar rule has the following general form:
3179 @var{result}: @var{components}@dots{}
3185 where @var{result} is the nonterminal symbol that this rule describes,
3186 and @var{components} are various terminal and nonterminal symbols that
3187 are put together by this rule (@pxref{Symbols}).
3199 says that two groupings of type @code{exp}, with a @samp{+} token in between,
3200 can be combined into a larger grouping of type @code{exp}.
3202 White space in rules is significant only to separate symbols. You can add
3203 extra white space as you wish.
3205 Scattered among the components can be @var{actions} that determine
3206 the semantics of the rule. An action looks like this:
3209 @{@var{C statements}@}
3214 This is an example of @dfn{braced code}, that is, C code surrounded by
3215 braces, much like a compound statement in C@. Braced code can contain
3216 any sequence of C tokens, so long as its braces are balanced. Bison
3217 does not check the braced code for correctness directly; it merely
3218 copies the code to the output file, where the C compiler can check it.
3220 Within braced code, the balanced-brace count is not affected by braces
3221 within comments, string literals, or character constants, but it is
3222 affected by the C digraphs @samp{<%} and @samp{%>} that represent
3223 braces. At the top level braced code must be terminated by @samp{@}}
3224 and not by a digraph. Bison does not look for trigraphs, so if braced
3225 code uses trigraphs you should ensure that they do not affect the
3226 nesting of braces or the boundaries of comments, string literals, or
3227 character constants.
3229 Usually there is only one action and it follows the components.
3233 Multiple rules for the same @var{result} can be written separately or can
3234 be joined with the vertical-bar character @samp{|} as follows:
3238 @var{result}: @var{rule1-components}@dots{}
3239 | @var{rule2-components}@dots{}
3246 They are still considered distinct rules even when joined in this way.
3248 If @var{components} in a rule is empty, it means that @var{result} can
3249 match the empty string. For example, here is how to define a
3250 comma-separated sequence of zero or more @code{exp} groupings:
3267 It is customary to write a comment @samp{/* empty */} in each rule
3271 @section Recursive Rules
3272 @cindex recursive rule
3274 A rule is called @dfn{recursive} when its @var{result} nonterminal
3275 appears also on its right hand side. Nearly all Bison grammars need to
3276 use recursion, because that is the only way to define a sequence of any
3277 number of a particular thing. Consider this recursive definition of a
3278 comma-separated sequence of one or more expressions:
3288 @cindex left recursion
3289 @cindex right recursion
3291 Since the recursive use of @code{expseq1} is the leftmost symbol in the
3292 right hand side, we call this @dfn{left recursion}. By contrast, here
3293 the same construct is defined using @dfn{right recursion}:
3304 Any kind of sequence can be defined using either left recursion or right
3305 recursion, but you should always use left recursion, because it can
3306 parse a sequence of any number of elements with bounded stack space.
3307 Right recursion uses up space on the Bison stack in proportion to the
3308 number of elements in the sequence, because all the elements must be
3309 shifted onto the stack before the rule can be applied even once.
3310 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
3313 @cindex mutual recursion
3314 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3315 rule does not appear directly on its right hand side, but does appear
3316 in rules for other nonterminals which do appear on its right hand
3324 | primary '+' primary
3336 defines two mutually-recursive nonterminals, since each refers to the
3340 @section Defining Language Semantics
3341 @cindex defining language semantics
3342 @cindex language semantics, defining
3344 The grammar rules for a language determine only the syntax. The semantics
3345 are determined by the semantic values associated with various tokens and
3346 groupings, and by the actions taken when various groupings are recognized.
3348 For example, the calculator calculates properly because the value
3349 associated with each expression is the proper number; it adds properly
3350 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3351 the numbers associated with @var{x} and @var{y}.
3354 * Value Type:: Specifying one data type for all semantic values.
3355 * Multiple Types:: Specifying several alternative data types.
3356 * Actions:: An action is the semantic definition of a grammar rule.
3357 * Action Types:: Specifying data types for actions to operate on.
3358 * Mid-Rule Actions:: Most actions go at the end of a rule.
3359 This says when, why and how to use the exceptional
3360 action in the middle of a rule.
3364 @subsection Data Types of Semantic Values
3365 @cindex semantic value type
3366 @cindex value type, semantic
3367 @cindex data types of semantic values
3368 @cindex default data type
3370 In a simple program it may be sufficient to use the same data type for
3371 the semantic values of all language constructs. This was true in the
3372 @acronym{RPN} and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
3373 Notation Calculator}).
3375 Bison normally uses the type @code{int} for semantic values if your
3376 program uses the same data type for all language constructs. To
3377 specify some other type, define @code{YYSTYPE} as a macro, like this:
3380 #define YYSTYPE double
3384 @code{YYSTYPE}'s replacement list should be a type name
3385 that does not contain parentheses or square brackets.
3386 This macro definition must go in the prologue of the grammar file
3387 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
3389 @node Multiple Types
3390 @subsection More Than One Value Type
3392 In most programs, you will need different data types for different kinds
3393 of tokens and groupings. For example, a numeric constant may need type
3394 @code{int} or @code{long int}, while a string constant needs type
3395 @code{char *}, and an identifier might need a pointer to an entry in the
3398 To use more than one data type for semantic values in one parser, Bison
3399 requires you to do two things:
3403 Specify the entire collection of possible data types, either by using the
3404 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
3405 Value Types}), or by using a @code{typedef} or a @code{#define} to
3406 define @code{YYSTYPE} to be a union type whose member names are
3410 Choose one of those types for each symbol (terminal or nonterminal) for
3411 which semantic values are used. This is done for tokens with the
3412 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
3413 and for groupings with the @code{%type} Bison declaration (@pxref{Type
3414 Decl, ,Nonterminal Symbols}).
3423 An action accompanies a syntactic rule and contains C code to be executed
3424 each time an instance of that rule is recognized. The task of most actions
3425 is to compute a semantic value for the grouping built by the rule from the
3426 semantic values associated with tokens or smaller groupings.
3428 An action consists of braced code containing C statements, and can be
3429 placed at any position in the rule;
3430 it is executed at that position. Most rules have just one action at the
3431 end of the rule, following all the components. Actions in the middle of
3432 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
3433 Actions, ,Actions in Mid-Rule}).
3435 The C code in an action can refer to the semantic values of the components
3436 matched by the rule with the construct @code{$@var{n}}, which stands for
3437 the value of the @var{n}th component. The semantic value for the grouping
3438 being constructed is @code{$$}. Bison translates both of these
3439 constructs into expressions of the appropriate type when it copies the
3440 actions into the parser file. @code{$$} is translated to a modifiable
3441 lvalue, so it can be assigned to.
3443 Here is a typical example:
3454 This rule constructs an @code{exp} from two smaller @code{exp} groupings
3455 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
3456 refer to the semantic values of the two component @code{exp} groupings,
3457 which are the first and third symbols on the right hand side of the rule.
3458 The sum is stored into @code{$$} so that it becomes the semantic value of
3459 the addition-expression just recognized by the rule. If there were a
3460 useful semantic value associated with the @samp{+} token, it could be
3461 referred to as @code{$2}.
3463 Note that the vertical-bar character @samp{|} is really a rule
3464 separator, and actions are attached to a single rule. This is a
3465 difference with tools like Flex, for which @samp{|} stands for either
3466 ``or'', or ``the same action as that of the next rule''. In the
3467 following example, the action is triggered only when @samp{b} is found:
3471 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
3475 @cindex default action
3476 If you don't specify an action for a rule, Bison supplies a default:
3477 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule
3478 becomes the value of the whole rule. Of course, the default action is
3479 valid only if the two data types match. There is no meaningful default
3480 action for an empty rule; every empty rule must have an explicit action
3481 unless the rule's value does not matter.
3483 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
3484 to tokens and groupings on the stack @emph{before} those that match the
3485 current rule. This is a very risky practice, and to use it reliably
3486 you must be certain of the context in which the rule is applied. Here
3487 is a case in which you can use this reliably:
3491 foo: expr bar '+' expr @{ @dots{} @}
3492 | expr bar '-' expr @{ @dots{} @}
3498 @{ previous_expr = $0; @}
3503 As long as @code{bar} is used only in the fashion shown here, @code{$0}
3504 always refers to the @code{expr} which precedes @code{bar} in the
3505 definition of @code{foo}.
3508 It is also possible to access the semantic value of the lookahead token, if
3509 any, from a semantic action.
3510 This semantic value is stored in @code{yylval}.
3511 @xref{Action Features, ,Special Features for Use in Actions}.
3514 @subsection Data Types of Values in Actions
3515 @cindex action data types
3516 @cindex data types in actions
3518 If you have chosen a single data type for semantic values, the @code{$$}
3519 and @code{$@var{n}} constructs always have that data type.
3521 If you have used @code{%union} to specify a variety of data types, then you
3522 must declare a choice among these types for each terminal or nonterminal
3523 symbol that can have a semantic value. Then each time you use @code{$$} or
3524 @code{$@var{n}}, its data type is determined by which symbol it refers to
3525 in the rule. In this example,
3536 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
3537 have the data type declared for the nonterminal symbol @code{exp}. If
3538 @code{$2} were used, it would have the data type declared for the
3539 terminal symbol @code{'+'}, whatever that might be.
3541 Alternatively, you can specify the data type when you refer to the value,
3542 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
3543 reference. For example, if you have defined types as shown here:
3555 then you can write @code{$<itype>1} to refer to the first subunit of the
3556 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
3558 @node Mid-Rule Actions
3559 @subsection Actions in Mid-Rule
3560 @cindex actions in mid-rule
3561 @cindex mid-rule actions
3563 Occasionally it is useful to put an action in the middle of a rule.
3564 These actions are written just like usual end-of-rule actions, but they
3565 are executed before the parser even recognizes the following components.
3567 A mid-rule action may refer to the components preceding it using
3568 @code{$@var{n}}, but it may not refer to subsequent components because
3569 it is run before they are parsed.
3571 The mid-rule action itself counts as one of the components of the rule.
3572 This makes a difference when there is another action later in the same rule
3573 (and usually there is another at the end): you have to count the actions
3574 along with the symbols when working out which number @var{n} to use in
3577 The mid-rule action can also have a semantic value. The action can set
3578 its value with an assignment to @code{$$}, and actions later in the rule
3579 can refer to the value using @code{$@var{n}}. Since there is no symbol
3580 to name the action, there is no way to declare a data type for the value
3581 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
3582 specify a data type each time you refer to this value.
3584 There is no way to set the value of the entire rule with a mid-rule
3585 action, because assignments to @code{$$} do not have that effect. The
3586 only way to set the value for the entire rule is with an ordinary action
3587 at the end of the rule.
3589 Here is an example from a hypothetical compiler, handling a @code{let}
3590 statement that looks like @samp{let (@var{variable}) @var{statement}} and
3591 serves to create a variable named @var{variable} temporarily for the
3592 duration of @var{statement}. To parse this construct, we must put
3593 @var{variable} into the symbol table while @var{statement} is parsed, then
3594 remove it afterward. Here is how it is done:
3598 stmt: LET '(' var ')'
3599 @{ $<context>$ = push_context ();
3600 declare_variable ($3); @}
3602 pop_context ($<context>5); @}
3607 As soon as @samp{let (@var{variable})} has been recognized, the first
3608 action is run. It saves a copy of the current semantic context (the
3609 list of accessible variables) as its semantic value, using alternative
3610 @code{context} in the data-type union. Then it calls
3611 @code{declare_variable} to add the new variable to that list. Once the
3612 first action is finished, the embedded statement @code{stmt} can be
3613 parsed. Note that the mid-rule action is component number 5, so the
3614 @samp{stmt} is component number 6.
3616 After the embedded statement is parsed, its semantic value becomes the
3617 value of the entire @code{let}-statement. Then the semantic value from the
3618 earlier action is used to restore the prior list of variables. This
3619 removes the temporary @code{let}-variable from the list so that it won't
3620 appear to exist while the rest of the program is parsed.
3623 @cindex discarded symbols, mid-rule actions
3624 @cindex error recovery, mid-rule actions
3625 In the above example, if the parser initiates error recovery (@pxref{Error
3626 Recovery}) while parsing the tokens in the embedded statement @code{stmt},
3627 it might discard the previous semantic context @code{$<context>5} without
3629 Thus, @code{$<context>5} needs a destructor (@pxref{Destructor Decl, , Freeing
3630 Discarded Symbols}).
3631 However, Bison currently provides no means to declare a destructor specific to
3632 a particular mid-rule action's semantic value.
3634 One solution is to bury the mid-rule action inside a nonterminal symbol and to
3635 declare a destructor for that symbol:
3640 %destructor @{ pop_context ($$); @} let
3646 pop_context ($1); @}
3649 let: LET '(' var ')'
3650 @{ $$ = push_context ();
3651 declare_variable ($3); @}
3658 Note that the action is now at the end of its rule.
3659 Any mid-rule action can be converted to an end-of-rule action in this way, and
3660 this is what Bison actually does to implement mid-rule actions.
3662 Taking action before a rule is completely recognized often leads to
3663 conflicts since the parser must commit to a parse in order to execute the
3664 action. For example, the following two rules, without mid-rule actions,
3665 can coexist in a working parser because the parser can shift the open-brace
3666 token and look at what follows before deciding whether there is a
3671 compound: '@{' declarations statements '@}'
3672 | '@{' statements '@}'
3678 But when we add a mid-rule action as follows, the rules become nonfunctional:
3682 compound: @{ prepare_for_local_variables (); @}
3683 '@{' declarations statements '@}'
3686 | '@{' statements '@}'
3692 Now the parser is forced to decide whether to run the mid-rule action
3693 when it has read no farther than the open-brace. In other words, it
3694 must commit to using one rule or the other, without sufficient
3695 information to do it correctly. (The open-brace token is what is called
3696 the @dfn{lookahead} token at this time, since the parser is still
3697 deciding what to do about it. @xref{Lookahead, ,Lookahead Tokens}.)
3699 You might think that you could correct the problem by putting identical
3700 actions into the two rules, like this:
3704 compound: @{ prepare_for_local_variables (); @}
3705 '@{' declarations statements '@}'
3706 | @{ prepare_for_local_variables (); @}
3707 '@{' statements '@}'
3713 But this does not help, because Bison does not realize that the two actions
3714 are identical. (Bison never tries to understand the C code in an action.)
3716 If the grammar is such that a declaration can be distinguished from a
3717 statement by the first token (which is true in C), then one solution which
3718 does work is to put the action after the open-brace, like this:
3722 compound: '@{' @{ prepare_for_local_variables (); @}
3723 declarations statements '@}'
3724 | '@{' statements '@}'
3730 Now the first token of the following declaration or statement,
3731 which would in any case tell Bison which rule to use, can still do so.
3733 Another solution is to bury the action inside a nonterminal symbol which
3734 serves as a subroutine:
3738 subroutine: /* empty */
3739 @{ prepare_for_local_variables (); @}
3745 compound: subroutine
3746 '@{' declarations statements '@}'
3748 '@{' statements '@}'
3754 Now Bison can execute the action in the rule for @code{subroutine} without
3755 deciding which rule for @code{compound} it will eventually use.
3758 @section Tracking Locations
3760 @cindex textual location
3761 @cindex location, textual
3763 Though grammar rules and semantic actions are enough to write a fully
3764 functional parser, it can be useful to process some additional information,
3765 especially symbol locations.
3767 The way locations are handled is defined by providing a data type, and
3768 actions to take when rules are matched.
3771 * Location Type:: Specifying a data type for locations.
3772 * Actions and Locations:: Using locations in actions.
3773 * Location Default Action:: Defining a general way to compute locations.
3777 @subsection Data Type of Locations
3778 @cindex data type of locations
3779 @cindex default location type
3781 Defining a data type for locations is much simpler than for semantic values,
3782 since all tokens and groupings always use the same type.
3784 You can specify the type of locations by defining a macro called
3785 @code{YYLTYPE}, just as you can specify the semantic value type by
3786 defining a @code{YYSTYPE} macro (@pxref{Value Type}).
3787 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3791 typedef struct YYLTYPE
3800 At the beginning of the parsing, Bison initializes all these fields to 1
3803 @node Actions and Locations
3804 @subsection Actions and Locations
3805 @cindex location actions
3806 @cindex actions, location
3810 Actions are not only useful for defining language semantics, but also for
3811 describing the behavior of the output parser with locations.
3813 The most obvious way for building locations of syntactic groupings is very
3814 similar to the way semantic values are computed. In a given rule, several
3815 constructs can be used to access the locations of the elements being matched.
3816 The location of the @var{n}th component of the right hand side is
3817 @code{@@@var{n}}, while the location of the left hand side grouping is
3820 Here is a basic example using the default data type for locations:
3827 @@$.first_column = @@1.first_column;
3828 @@$.first_line = @@1.first_line;
3829 @@$.last_column = @@3.last_column;
3830 @@$.last_line = @@3.last_line;
3837 "Division by zero, l%d,c%d-l%d,c%d",
3838 @@3.first_line, @@3.first_column,
3839 @@3.last_line, @@3.last_column);
3845 As for semantic values, there is a default action for locations that is
3846 run each time a rule is matched. It sets the beginning of @code{@@$} to the
3847 beginning of the first symbol, and the end of @code{@@$} to the end of the
3850 With this default action, the location tracking can be fully automatic. The
3851 example above simply rewrites this way:
3864 "Division by zero, l%d,c%d-l%d,c%d",
3865 @@3.first_line, @@3.first_column,
3866 @@3.last_line, @@3.last_column);
3873 It is also possible to access the location of the lookahead token, if any,
3874 from a semantic action.
3875 This location is stored in @code{yylloc}.
3876 @xref{Action Features, ,Special Features for Use in Actions}.
3878 @node Location Default Action
3879 @subsection Default Action for Locations
3880 @vindex YYLLOC_DEFAULT
3881 @cindex @acronym{GLR} parsers and @code{YYLLOC_DEFAULT}
3883 Actually, actions are not the best place to compute locations. Since
3884 locations are much more general than semantic values, there is room in
3885 the output parser to redefine the default action to take for each
3886 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
3887 matched, before the associated action is run. It is also invoked
3888 while processing a syntax error, to compute the error's location.
3889 Before reporting an unresolvable syntactic ambiguity, a @acronym{GLR}
3890 parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
3893 Most of the time, this macro is general enough to suppress location
3894 dedicated code from semantic actions.
3896 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
3897 the location of the grouping (the result of the computation). When a
3898 rule is matched, the second parameter identifies locations of
3899 all right hand side elements of the rule being matched, and the third
3900 parameter is the size of the rule's right hand side.
3901 When a @acronym{GLR} parser reports an ambiguity, which of multiple candidate
3902 right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
3903 When processing a syntax error, the second parameter identifies locations
3904 of the symbols that were discarded during error processing, and the third
3905 parameter is the number of discarded symbols.
3907 By default, @code{YYLLOC_DEFAULT} is defined this way:
3911 # define YYLLOC_DEFAULT(Current, Rhs, N) \
3915 (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
3916 (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
3917 (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
3918 (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
3922 (Current).first_line = (Current).last_line = \
3923 YYRHSLOC(Rhs, 0).last_line; \
3924 (Current).first_column = (Current).last_column = \
3925 YYRHSLOC(Rhs, 0).last_column; \
3931 where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
3932 in @var{rhs} when @var{k} is positive, and the location of the symbol
3933 just before the reduction when @var{k} and @var{n} are both zero.
3935 When defining @code{YYLLOC_DEFAULT}, you should consider that:
3939 All arguments are free of side-effects. However, only the first one (the
3940 result) should be modified by @code{YYLLOC_DEFAULT}.
3943 For consistency with semantic actions, valid indexes within the
3944 right hand side range from 1 to @var{n}. When @var{n} is zero, only 0 is a
3945 valid index, and it refers to the symbol just before the reduction.
3946 During error processing @var{n} is always positive.
3949 Your macro should parenthesize its arguments, if need be, since the
3950 actual arguments may not be surrounded by parentheses. Also, your
3951 macro should expand to something that can be used as a single
3952 statement when it is followed by a semicolon.
3956 @section Bison Declarations
3957 @cindex declarations, Bison
3958 @cindex Bison declarations
3960 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
3961 used in formulating the grammar and the data types of semantic values.
3964 All token type names (but not single-character literal tokens such as
3965 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
3966 declared if you need to specify which data type to use for the semantic
3967 value (@pxref{Multiple Types, ,More Than One Value Type}).
3969 The first rule in the file also specifies the start symbol, by default.
3970 If you want some other symbol to be the start symbol, you must declare
3971 it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free
3975 * Require Decl:: Requiring a Bison version.
3976 * Token Decl:: Declaring terminal symbols.
3977 * Precedence Decl:: Declaring terminals with precedence and associativity.
3978 * Union Decl:: Declaring the set of all semantic value types.
3979 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
3980 * Initial Action Decl:: Code run before parsing starts.
3981 * Destructor Decl:: Declaring how symbols are freed.
3982 * Expect Decl:: Suppressing warnings about parsing conflicts.
3983 * Start Decl:: Specifying the start symbol.
3984 * Pure Decl:: Requesting a reentrant parser.
3985 * Push Decl:: Requesting a push parser.
3986 * Decl Summary:: Table of all Bison declarations.
3990 @subsection Require a Version of Bison
3991 @cindex version requirement
3992 @cindex requiring a version of Bison
3995 You may require the minimum version of Bison to process the grammar. If
3996 the requirement is not met, @command{bison} exits with an error (exit
4000 %require "@var{version}"
4004 @subsection Token Type Names
4005 @cindex declaring token type names
4006 @cindex token type names, declaring
4007 @cindex declaring literal string tokens
4010 The basic way to declare a token type name (terminal symbol) is as follows:
4016 Bison will convert this into a @code{#define} directive in
4017 the parser, so that the function @code{yylex} (if it is in this file)
4018 can use the name @var{name} to stand for this token type's code.
4020 Alternatively, you can use @code{%left}, @code{%right}, or
4021 @code{%nonassoc} instead of @code{%token}, if you wish to specify
4022 associativity and precedence. @xref{Precedence Decl, ,Operator
4025 You can explicitly specify the numeric code for a token type by appending
4026 a nonnegative decimal or hexadecimal integer value in the field immediately
4027 following the token name:
4031 %token XNUM 0x12d // a GNU extension
4035 It is generally best, however, to let Bison choose the numeric codes for
4036 all token types. Bison will automatically select codes that don't conflict
4037 with each other or with normal characters.
4039 In the event that the stack type is a union, you must augment the
4040 @code{%token} or other token declaration to include the data type
4041 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
4042 Than One Value Type}).
4048 %union @{ /* define stack type */
4052 %token <val> NUM /* define token NUM and its type */
4056 You can associate a literal string token with a token type name by
4057 writing the literal string at the end of a @code{%token}
4058 declaration which declares the name. For example:
4065 For example, a grammar for the C language might specify these names with
4066 equivalent literal string tokens:
4069 %token <operator> OR "||"
4070 %token <operator> LE 134 "<="
4075 Once you equate the literal string and the token name, you can use them
4076 interchangeably in further declarations or the grammar rules. The
4077 @code{yylex} function can use the token name or the literal string to
4078 obtain the token type code number (@pxref{Calling Convention}).
4079 Syntax error messages passed to @code{yyerror} from the parser will reference
4080 the literal string instead of the token name.
4082 The token numbered as 0 corresponds to end of file; the following line
4083 allows for nicer error messages referring to ``end of file'' instead
4087 %token END 0 "end of file"
4090 @node Precedence Decl
4091 @subsection Operator Precedence
4092 @cindex precedence declarations
4093 @cindex declaring operator precedence
4094 @cindex operator precedence, declaring
4096 Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
4097 declare a token and specify its precedence and associativity, all at
4098 once. These are called @dfn{precedence declarations}.
4099 @xref{Precedence, ,Operator Precedence}, for general information on
4100 operator precedence.
4102 The syntax of a precedence declaration is nearly the same as that of
4103 @code{%token}: either
4106 %left @var{symbols}@dots{}
4113 %left <@var{type}> @var{symbols}@dots{}
4116 And indeed any of these declarations serves the purposes of @code{%token}.
4117 But in addition, they specify the associativity and relative precedence for
4118 all the @var{symbols}:
4122 The associativity of an operator @var{op} determines how repeated uses
4123 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
4124 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
4125 grouping @var{y} with @var{z} first. @code{%left} specifies
4126 left-associativity (grouping @var{x} with @var{y} first) and
4127 @code{%right} specifies right-associativity (grouping @var{y} with
4128 @var{z} first). @code{%nonassoc} specifies no associativity, which
4129 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
4130 considered a syntax error.
4133 The precedence of an operator determines how it nests with other operators.
4134 All the tokens declared in a single precedence declaration have equal
4135 precedence and nest together according to their associativity.
4136 When two tokens declared in different precedence declarations associate,
4137 the one declared later has the higher precedence and is grouped first.
4140 For backward compatibility, there is a confusing difference between the
4141 argument lists of @code{%token} and precedence declarations.
4142 Only a @code{%token} can associate a literal string with a token type name.
4143 A precedence declaration always interprets a literal string as a reference to a
4148 %left OR "<=" // Does not declare an alias.
4149 %left OR 134 "<=" 135 // Declares 134 for OR and 135 for "<=".
4153 @subsection The Collection of Value Types
4154 @cindex declaring value types
4155 @cindex value types, declaring
4158 The @code{%union} declaration specifies the entire collection of
4159 possible data types for semantic values. The keyword @code{%union} is
4160 followed by braced code containing the same thing that goes inside a
4175 This says that the two alternative types are @code{double} and @code{symrec
4176 *}. They are given names @code{val} and @code{tptr}; these names are used
4177 in the @code{%token} and @code{%type} declarations to pick one of the types
4178 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
4180 As an extension to @acronym{POSIX}, a tag is allowed after the
4181 @code{union}. For example:
4193 specifies the union tag @code{value}, so the corresponding C type is
4194 @code{union value}. If you do not specify a tag, it defaults to
4197 As another extension to @acronym{POSIX}, you may specify multiple
4198 @code{%union} declarations; their contents are concatenated. However,
4199 only the first @code{%union} declaration can specify a tag.
4201 Note that, unlike making a @code{union} declaration in C, you need not write
4202 a semicolon after the closing brace.
4204 Instead of @code{%union}, you can define and use your own union type
4205 @code{YYSTYPE} if your grammar contains at least one
4206 @samp{<@var{type}>} tag. For example, you can put the following into
4207 a header file @file{parser.h}:
4215 typedef union YYSTYPE YYSTYPE;
4220 and then your grammar can use the following
4221 instead of @code{%union}:
4234 @subsection Nonterminal Symbols
4235 @cindex declaring value types, nonterminals
4236 @cindex value types, nonterminals, declaring
4240 When you use @code{%union} to specify multiple value types, you must
4241 declare the value type of each nonterminal symbol for which values are
4242 used. This is done with a @code{%type} declaration, like this:
4245 %type <@var{type}> @var{nonterminal}@dots{}
4249 Here @var{nonterminal} is the name of a nonterminal symbol, and
4250 @var{type} is the name given in the @code{%union} to the alternative
4251 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
4252 can give any number of nonterminal symbols in the same @code{%type}
4253 declaration, if they have the same value type. Use spaces to separate
4256 You can also declare the value type of a terminal symbol. To do this,
4257 use the same @code{<@var{type}>} construction in a declaration for the
4258 terminal symbol. All kinds of token declarations allow
4259 @code{<@var{type}>}.
4261 @node Initial Action Decl
4262 @subsection Performing Actions before Parsing
4263 @findex %initial-action
4265 Sometimes your parser needs to perform some initializations before
4266 parsing. The @code{%initial-action} directive allows for such arbitrary
4269 @deffn {Directive} %initial-action @{ @var{code} @}
4270 @findex %initial-action
4271 Declare that the braced @var{code} must be invoked before parsing each time
4272 @code{yyparse} is called. The @var{code} may use @code{$$} and
4273 @code{@@$} --- initial value and location of the lookahead --- and the
4274 @code{%parse-param}.
4277 For instance, if your locations use a file name, you may use
4280 %parse-param @{ char const *file_name @};
4283 @@$.initialize (file_name);
4288 @node Destructor Decl
4289 @subsection Freeing Discarded Symbols
4290 @cindex freeing discarded symbols
4294 During error recovery (@pxref{Error Recovery}), symbols already pushed
4295 on the stack and tokens coming from the rest of the file are discarded
4296 until the parser falls on its feet. If the parser runs out of memory,
4297 or if it returns via @code{YYABORT} or @code{YYACCEPT}, all the
4298 symbols on the stack must be discarded. Even if the parser succeeds, it
4299 must discard the start symbol.
4301 When discarded symbols convey heap based information, this memory is
4302 lost. While this behavior can be tolerable for batch parsers, such as
4303 in traditional compilers, it is unacceptable for programs like shells or
4304 protocol implementations that may parse and execute indefinitely.
4306 The @code{%destructor} directive defines code that is called when a
4307 symbol is automatically discarded.
4309 @deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
4311 Invoke the braced @var{code} whenever the parser discards one of the
4313 Within @var{code}, @code{$$} designates the semantic value associated
4314 with the discarded symbol, and @code{@@$} designates its location.
4315 The additional parser parameters are also available (@pxref{Parser Function, ,
4316 The Parser Function @code{yyparse}}).
4318 When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
4319 per-symbol @code{%destructor}.
4320 You may also define a per-type @code{%destructor} by listing a semantic type
4321 tag among @var{symbols}.
4322 In that case, the parser will invoke this @var{code} whenever it discards any
4323 grammar symbol that has that semantic type tag unless that symbol has its own
4324 per-symbol @code{%destructor}.
4326 Finally, you can define two different kinds of default @code{%destructor}s.
4327 (These default forms are experimental.
4328 More user feedback will help to determine whether they should become permanent
4330 You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
4331 exactly one @code{%destructor} declaration in your grammar file.
4332 The parser will invoke the @var{code} associated with one of these whenever it
4333 discards any user-defined grammar symbol that has no per-symbol and no per-type
4335 The parser uses the @var{code} for @code{<*>} in the case of such a grammar
4336 symbol for which you have formally declared a semantic type tag (@code{%type}
4337 counts as such a declaration, but @code{$<tag>$} does not).
4338 The parser uses the @var{code} for @code{<>} in the case of such a grammar
4339 symbol that has no declared semantic type tag.
4346 %union @{ char *string; @}
4347 %token <string> STRING1
4348 %token <string> STRING2
4349 %type <string> string1
4350 %type <string> string2
4351 %union @{ char character; @}
4352 %token <character> CHR
4353 %type <character> chr
4356 %destructor @{ @} <character>
4357 %destructor @{ free ($$); @} <*>
4358 %destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
4359 %destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
4363 guarantees that, when the parser discards any user-defined symbol that has a
4364 semantic type tag other than @code{<character>}, it passes its semantic value
4365 to @code{free} by default.
4366 However, when the parser discards a @code{STRING1} or a @code{string1}, it also
4367 prints its line number to @code{stdout}.
4368 It performs only the second @code{%destructor} in this case, so it invokes
4369 @code{free} only once.
4370 Finally, the parser merely prints a message whenever it discards any symbol,
4371 such as @code{TAGLESS}, that has no semantic type tag.
4373 A Bison-generated parser invokes the default @code{%destructor}s only for
4374 user-defined as opposed to Bison-defined symbols.
4375 For example, the parser will not invoke either kind of default
4376 @code{%destructor} for the special Bison-defined symbols @code{$accept},
4377 @code{$undefined}, or @code{$end} (@pxref{Table of Symbols, ,Bison Symbols}),
4378 none of which you can reference in your grammar.
4379 It also will not invoke either for the @code{error} token (@pxref{Table of
4380 Symbols, ,error}), which is always defined by Bison regardless of whether you
4381 reference it in your grammar.
4382 However, it may invoke one of them for the end token (token 0) if you
4383 redefine it from @code{$end} to, for example, @code{END}:
4389 @cindex actions in mid-rule
4390 @cindex mid-rule actions
4391 Finally, Bison will never invoke a @code{%destructor} for an unreferenced
4392 mid-rule semantic value (@pxref{Mid-Rule Actions,,Actions in Mid-Rule}).
4393 That is, Bison does not consider a mid-rule to have a semantic value if you do
4394 not reference @code{$$} in the mid-rule's action or @code{$@var{n}} (where
4395 @var{n} is the RHS symbol position of the mid-rule) in any later action in that
4397 However, if you do reference either, the Bison-generated parser will invoke the
4398 @code{<>} @code{%destructor} whenever it discards the mid-rule symbol.
4402 In the future, it may be possible to redefine the @code{error} token as a
4403 nonterminal that captures the discarded symbols.
4404 In that case, the parser will invoke the default destructor for it as well.
4409 @cindex discarded symbols
4410 @dfn{Discarded symbols} are the following:
4414 stacked symbols popped during the first phase of error recovery,
4416 incoming terminals during the second phase of error recovery,
4418 the current lookahead and the entire stack (except the current
4419 right-hand side symbols) when the parser returns immediately, and
4421 the start symbol, when the parser succeeds.
4424 The parser can @dfn{return immediately} because of an explicit call to
4425 @code{YYABORT} or @code{YYACCEPT}, or failed error recovery, or memory
4428 Right-hand side symbols of a rule that explicitly triggers a syntax
4429 error via @code{YYERROR} are not discarded automatically. As a rule
4430 of thumb, destructors are invoked only when user actions cannot manage
4434 @subsection Suppressing Conflict Warnings
4435 @cindex suppressing conflict warnings
4436 @cindex preventing warnings about conflicts
4437 @cindex warnings, preventing
4438 @cindex conflicts, suppressing warnings of
4442 Bison normally warns if there are any conflicts in the grammar
4443 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
4444 have harmless shift/reduce conflicts which are resolved in a predictable
4445 way and would be difficult to eliminate. It is desirable to suppress
4446 the warning about these conflicts unless the number of conflicts
4447 changes. You can do this with the @code{%expect} declaration.
4449 The declaration looks like this:
4455 Here @var{n} is a decimal integer. The declaration says there should
4456 be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
4457 Bison reports an error if the number of shift/reduce conflicts differs
4458 from @var{n}, or if there are any reduce/reduce conflicts.
4460 For normal @acronym{LALR}(1) parsers, reduce/reduce conflicts are more
4461 serious, and should be eliminated entirely. Bison will always report
4462 reduce/reduce conflicts for these parsers. With @acronym{GLR}
4463 parsers, however, both kinds of conflicts are routine; otherwise,
4464 there would be no need to use @acronym{GLR} parsing. Therefore, it is
4465 also possible to specify an expected number of reduce/reduce conflicts
4466 in @acronym{GLR} parsers, using the declaration:
4472 In general, using @code{%expect} involves these steps:
4476 Compile your grammar without @code{%expect}. Use the @samp{-v} option
4477 to get a verbose list of where the conflicts occur. Bison will also
4478 print the number of conflicts.
4481 Check each of the conflicts to make sure that Bison's default
4482 resolution is what you really want. If not, rewrite the grammar and
4483 go back to the beginning.
4486 Add an @code{%expect} declaration, copying the number @var{n} from the
4487 number which Bison printed. With @acronym{GLR} parsers, add an
4488 @code{%expect-rr} declaration as well.
4491 Now Bison will warn you if you introduce an unexpected conflict, but
4492 will keep silent otherwise.
4495 @subsection The Start-Symbol
4496 @cindex declaring the start symbol
4497 @cindex start symbol, declaring
4498 @cindex default start symbol
4501 Bison assumes by default that the start symbol for the grammar is the first
4502 nonterminal specified in the grammar specification section. The programmer
4503 may override this restriction with the @code{%start} declaration as follows:
4510 @subsection A Pure (Reentrant) Parser
4511 @cindex reentrant parser
4513 @findex %define api.pure
4515 A @dfn{reentrant} program is one which does not alter in the course of
4516 execution; in other words, it consists entirely of @dfn{pure} (read-only)
4517 code. Reentrancy is important whenever asynchronous execution is possible;
4518 for example, a nonreentrant program may not be safe to call from a signal
4519 handler. In systems with multiple threads of control, a nonreentrant
4520 program must be called only within interlocks.
4522 Normally, Bison generates a parser which is not reentrant. This is
4523 suitable for most uses, and it permits compatibility with Yacc. (The
4524 standard Yacc interfaces are inherently nonreentrant, because they use
4525 statically allocated variables for communication with @code{yylex},
4526 including @code{yylval} and @code{yylloc}.)
4528 Alternatively, you can generate a pure, reentrant parser. The Bison
4529 declaration @code{%define api.pure} says that you want the parser to be
4530 reentrant. It looks like this:
4536 The result is that the communication variables @code{yylval} and
4537 @code{yylloc} become local variables in @code{yyparse}, and a different
4538 calling convention is used for the lexical analyzer function
4539 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
4540 Parsers}, for the details of this. The variable @code{yynerrs}
4541 becomes local in @code{yyparse} in pull mode but it becomes a member
4542 of yypstate in push mode. (@pxref{Error Reporting, ,The Error
4543 Reporting Function @code{yyerror}}). The convention for calling
4544 @code{yyparse} itself is unchanged.
4546 Whether the parser is pure has nothing to do with the grammar rules.
4547 You can generate either a pure parser or a nonreentrant parser from any
4551 @subsection A Push Parser
4554 @findex %define api.push_pull
4556 A pull parser is called once and it takes control until all its input
4557 is completely parsed. A push parser, on the other hand, is called
4558 each time a new token is made available.
4560 A push parser is typically useful when the parser is part of a
4561 main event loop in the client's application. This is typically
4562 a requirement of a GUI, when the main event loop needs to be triggered
4563 within a certain time period.
4565 Normally, Bison generates a pull parser.
4566 The following Bison declaration says that you want the parser to be a push
4567 parser (@pxref{Decl Summary,,%define api.push_pull}):
4570 %define api.push_pull "push"
4573 In almost all cases, you want to ensure that your push parser is also
4574 a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}). The only
4575 time you should create an impure push parser is to have backwards
4576 compatibility with the impure Yacc pull mode interface. Unless you know
4577 what you are doing, your declarations should look like this:
4581 %define api.push_pull "push"
4584 There is a major notable functional difference between the pure push parser
4585 and the impure push parser. It is acceptable for a pure push parser to have
4586 many parser instances, of the same type of parser, in memory at the same time.
4587 An impure push parser should only use one parser at a time.
4589 When a push parser is selected, Bison will generate some new symbols in
4590 the generated parser. @code{yypstate} is a structure that the generated
4591 parser uses to store the parser's state. @code{yypstate_new} is the
4592 function that will create a new parser instance. @code{yypstate_delete}
4593 will free the resources associated with the corresponding parser instance.
4594 Finally, @code{yypush_parse} is the function that should be called whenever a
4595 token is available to provide the parser. A trivial example
4596 of using a pure push parser would look like this:
4600 yypstate *ps = yypstate_new ();
4602 status = yypush_parse (ps, yylex (), NULL);
4603 @} while (status == YYPUSH_MORE);
4604 yypstate_delete (ps);
4607 If the user decided to use an impure push parser, a few things about
4608 the generated parser will change. The @code{yychar} variable becomes
4609 a global variable instead of a variable in the @code{yypush_parse} function.
4610 For this reason, the signature of the @code{yypush_parse} function is
4611 changed to remove the token as a parameter. A nonreentrant push parser
4612 example would thus look like this:
4617 yypstate *ps = yypstate_new ();
4620 status = yypush_parse (ps);
4621 @} while (status == YYPUSH_MORE);
4622 yypstate_delete (ps);
4625 That's it. Notice the next token is put into the global variable @code{yychar}
4626 for use by the next invocation of the @code{yypush_parse} function.
4628 Bison also supports both the push parser interface along with the pull parser
4629 interface in the same generated parser. In order to get this functionality,
4630 you should replace the @code{%define api.push_pull "push"} declaration with the
4631 @code{%define api.push_pull "both"} declaration. Doing this will create all of
4632 the symbols mentioned earlier along with the two extra symbols, @code{yyparse}
4633 and @code{yypull_parse}. @code{yyparse} can be used exactly as it normally
4634 would be used. However, the user should note that it is implemented in the
4635 generated parser by calling @code{yypull_parse}.
4636 This makes the @code{yyparse} function that is generated with the
4637 @code{%define api.push_pull "both"} declaration slower than the normal
4638 @code{yyparse} function. If the user
4639 calls the @code{yypull_parse} function it will parse the rest of the input
4640 stream. It is possible to @code{yypush_parse} tokens to select a subgrammar
4641 and then @code{yypull_parse} the rest of the input stream. If you would like
4642 to switch back and forth between between parsing styles, you would have to
4643 write your own @code{yypull_parse} function that knows when to quit looking
4644 for input. An example of using the @code{yypull_parse} function would look
4648 yypstate *ps = yypstate_new ();
4649 yypull_parse (ps); /* Will call the lexer */
4650 yypstate_delete (ps);
4653 Adding the @code{%define api.pure} declaration does exactly the same thing to
4654 the generated parser with @code{%define api.push_pull "both"} as it did for
4655 @code{%define api.push_pull "push"}.
4658 @subsection Bison Declaration Summary
4659 @cindex Bison declaration summary
4660 @cindex declaration summary
4661 @cindex summary, Bison declaration
4663 Here is a summary of the declarations used to define a grammar:
4665 @deffn {Directive} %union
4666 Declare the collection of data types that semantic values may have
4667 (@pxref{Union Decl, ,The Collection of Value Types}).
4670 @deffn {Directive} %token
4671 Declare a terminal symbol (token type name) with no precedence
4672 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
4675 @deffn {Directive} %right
4676 Declare a terminal symbol (token type name) that is right-associative
4677 (@pxref{Precedence Decl, ,Operator Precedence}).
4680 @deffn {Directive} %left
4681 Declare a terminal symbol (token type name) that is left-associative
4682 (@pxref{Precedence Decl, ,Operator Precedence}).
4685 @deffn {Directive} %nonassoc
4686 Declare a terminal symbol (token type name) that is nonassociative
4687 (@pxref{Precedence Decl, ,Operator Precedence}).
4688 Using it in a way that would be associative is a syntax error.
4692 @deffn {Directive} %default-prec
4693 Assign a precedence to rules lacking an explicit @code{%prec} modifier
4694 (@pxref{Contextual Precedence, ,Context-Dependent Precedence}).
4698 @deffn {Directive} %type
4699 Declare the type of semantic values for a nonterminal symbol
4700 (@pxref{Type Decl, ,Nonterminal Symbols}).
4703 @deffn {Directive} %start
4704 Specify the grammar's start symbol (@pxref{Start Decl, ,The
4708 @deffn {Directive} %expect
4709 Declare the expected number of shift-reduce conflicts
4710 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
4716 In order to change the behavior of @command{bison}, use the following
4719 @deffn {Directive} %code @{@var{code}@}
4721 This is the unqualified form of the @code{%code} directive.
4722 It inserts @var{code} verbatim at a language-dependent default location in the
4723 output@footnote{The default location is actually skeleton-dependent;
4724 writers of non-standard skeletons however should choose the default location
4725 consistently with the behavior of the standard Bison skeletons.}.
4728 For C/C++, the default location is the parser source code
4729 file after the usual contents of the parser header file.
4730 Thus, @code{%code} replaces the traditional Yacc prologue,
4731 @code{%@{@var{code}%@}}, for most purposes.
4732 For a detailed discussion, see @ref{Prologue Alternatives}.
4734 For Java, the default location is inside the parser class.
4736 (Like all the Yacc prologue alternatives, this directive is experimental.
4737 More user feedback will help to determine whether it should become a permanent
4741 @deffn {Directive} %code @var{qualifier} @{@var{code}@}
4742 This is the qualified form of the @code{%code} directive.
4743 If you need to specify location-sensitive verbatim @var{code} that does not
4744 belong at the default location selected by the unqualified @code{%code} form,
4745 use this form instead.
4747 @var{qualifier} identifies the purpose of @var{code} and thus the location(s)
4748 where Bison should generate it.
4749 Not all values of @var{qualifier} are available for all target languages:
4753 @findex %code requires
4756 @item Language(s): C, C++
4758 @item Purpose: This is the best place to write dependency code required for
4759 @code{YYSTYPE} and @code{YYLTYPE}.
4760 In other words, it's the best place to define types referenced in @code{%union}
4761 directives, and it's the best place to override Bison's default @code{YYSTYPE}
4762 and @code{YYLTYPE} definitions.
4764 @item Location(s): The parser header file and the parser source code file
4765 before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE} definitions.
4769 @findex %code provides
4772 @item Language(s): C, C++
4774 @item Purpose: This is the best place to write additional definitions and
4775 declarations that should be provided to other modules.
4777 @item Location(s): The parser header file and the parser source code file after
4778 the Bison-generated @code{YYSTYPE}, @code{YYLTYPE}, and token definitions.
4785 @item Language(s): C, C++
4787 @item Purpose: The unqualified @code{%code} or @code{%code requires} should
4788 usually be more appropriate than @code{%code top}.
4789 However, occasionally it is necessary to insert code much nearer the top of the
4790 parser source code file.
4800 @item Location(s): Near the top of the parser source code file.
4804 @findex %code imports
4807 @item Language(s): Java
4809 @item Purpose: This is the best place to write Java import directives.
4811 @item Location(s): The parser Java file after any Java package directive and
4812 before any class definitions.
4816 (Like all the Yacc prologue alternatives, this directive is experimental.
4817 More user feedback will help to determine whether it should become a permanent
4821 For a detailed discussion of how to use @code{%code} in place of the
4822 traditional Yacc prologue for C/C++, see @ref{Prologue Alternatives}.
4825 @deffn {Directive} %debug
4826 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
4827 already defined, so that the debugging facilities are compiled.
4829 @xref{Tracing, ,Tracing Your Parser}.
4831 @deffn {Directive} %define @var{variable}
4832 @deffnx {Directive} %define @var{variable} "@var{value}"
4833 Define a variable to adjust Bison's behavior.
4834 The possible choices for @var{variable}, as well as their meanings, depend on
4835 the selected target language and/or the parser skeleton (@pxref{Decl
4836 Summary,,%language}).
4838 Bison will warn if a @var{variable} is defined multiple times.
4840 Omitting @code{"@var{value}"} is always equivalent to specifying it as
4843 Some @var{variable}s may be used as Booleans.
4844 In this case, Bison will complain if the variable definition does not meet one
4845 of the following four conditions:
4848 @item @code{"@var{value}"} is @code{"true"}
4850 @item @code{"@var{value}"} is omitted (or is @code{""}).
4851 This is equivalent to @code{"true"}.
4853 @item @code{"@var{value}"} is @code{"false"}.
4855 @item @var{variable} is never defined.
4856 In this case, Bison selects a default value, which may depend on the selected
4857 target language and/or parser skeleton.
4860 Some of the accepted @var{variable}s are:
4864 @findex %define api.pure
4867 @item Language(s): C
4869 @item Purpose: Request a pure (reentrant) parser program.
4870 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
4872 @item Accepted Values: Boolean
4874 @item Default Value: @code{"false"}
4878 @findex %define api.push_pull
4881 @item Language(s): C (LALR(1) only)
4883 @item Purpose: Requests a pull parser, a push parser, or both.
4884 @xref{Push Decl, ,A Push Parser}.
4886 @item Accepted Values: @code{"pull"}, @code{"push"}, @code{"both"}
4888 @item Default Value: @code{"pull"}
4891 @item lr.keep_unreachable_states
4892 @findex %define lr.keep_unreachable_states
4895 @item Language(s): all
4897 @item Purpose: Requests that Bison allow unreachable parser states to remain in
4899 Bison considers a state to be unreachable if there exists no sequence of
4900 transitions from the start state to that state.
4901 A state can become unreachable during conflict resolution if Bison disables a
4902 shift action leading to it from a predecessor state.
4903 Keeping unreachable states is sometimes useful for analysis purposes, but they
4904 are useless in the generated parser.
4906 @item Accepted Values: Boolean
4908 @item Default Value: @code{"false"}
4914 @item Unreachable states may contain conflicts and may use rules not used in
4916 Thus, keeping unreachable states may induce warnings that are irrelevant to
4917 your parser's behavior, and it may eliminate warnings that are relevant.
4918 Of course, the change in warnings may actually be relevant to a parser table
4919 analysis that wants to keep unreachable states, so this behavior will likely
4920 remain in future Bison releases.
4922 @item While Bison is able to remove unreachable states, it is not guaranteed to
4923 remove other kinds of useless states.
4924 Specifically, when Bison disables reduce actions during conflict resolution,
4925 some goto actions may become useless, and thus some additional states may
4927 If Bison were to compute which goto actions were useless and then disable those
4928 actions, it could identify such states as unreachable and then remove those
4930 However, Bison does not compute which goto actions are useless.
4935 @findex %define namespace
4938 @item Languages(s): C++
4940 @item Purpose: Specifies the namespace for the parser class.
4941 For example, if you specify:
4944 %define namespace "foo::bar"
4947 Bison uses @code{foo::bar} verbatim in references such as:
4950 foo::bar::parser::semantic_type
4953 However, to open a namespace, Bison removes any leading @code{::} and then
4954 splits on any remaining occurrences:
4957 namespace foo @{ namespace bar @{
4963 @item Accepted Values: Any absolute or relative C++ namespace reference without
4964 a trailing @code{"::"}.
4965 For example, @code{"foo"} or @code{"::foo::bar"}.
4967 @item Default Value: The value specified by @code{%name-prefix}, which defaults
4969 This usage of @code{%name-prefix} is for backward compatibility and can be
4970 confusing since @code{%name-prefix} also specifies the textual prefix for the
4971 lexical analyzer function.
4972 Thus, if you specify @code{%name-prefix}, it is best to also specify
4973 @code{%define namespace} so that @code{%name-prefix} @emph{only} affects the
4974 lexical analyzer function.
4975 For example, if you specify:
4978 %define namespace "foo"
4979 %name-prefix "bar::"
4982 The parser namespace is @code{foo} and @code{yylex} is referenced as
4989 @deffn {Directive} %defines
4990 Write a header file containing macro definitions for the token type
4991 names defined in the grammar as well as a few other declarations.
4992 If the parser output file is named @file{@var{name}.c} then this file
4993 is named @file{@var{name}.h}.
4995 For C parsers, the output header declares @code{YYSTYPE} unless
4996 @code{YYSTYPE} is already defined as a macro or you have used a
4997 @code{<@var{type}>} tag without using @code{%union}.
4998 Therefore, if you are using a @code{%union}
4999 (@pxref{Multiple Types, ,More Than One Value Type}) with components that
5000 require other definitions, or if you have defined a @code{YYSTYPE} macro
5002 (@pxref{Value Type, ,Data Types of Semantic Values}), you need to
5003 arrange for these definitions to be propagated to all modules, e.g., by
5004 putting them in a prerequisite header that is included both by your
5005 parser and by any other module that needs @code{YYSTYPE}.
5007 Unless your parser is pure, the output header declares @code{yylval}
5008 as an external variable. @xref{Pure Decl, ,A Pure (Reentrant)
5011 If you have also used locations, the output header declares
5012 @code{YYLTYPE} and @code{yylloc} using a protocol similar to that of
5013 the @code{YYSTYPE} macro and @code{yylval}. @xref{Locations, ,Tracking
5016 This output file is normally essential if you wish to put the definition
5017 of @code{yylex} in a separate source file, because @code{yylex}
5018 typically needs to be able to refer to the above-mentioned declarations
5019 and to the token type codes. @xref{Token Values, ,Semantic Values of
5022 @findex %code requires
5023 @findex %code provides
5024 If you have declared @code{%code requires} or @code{%code provides}, the output
5025 header also contains their code.
5026 @xref{Decl Summary, ,%code}.
5029 @deffn {Directive} %defines @var{defines-file}
5030 Same as above, but save in the file @var{defines-file}.
5033 @deffn {Directive} %destructor
5034 Specify how the parser should reclaim the memory associated to
5035 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
5038 @deffn {Directive} %file-prefix "@var{prefix}"
5039 Specify a prefix to use for all Bison output file names. The names are
5040 chosen as if the input file were named @file{@var{prefix}.y}.
5043 @deffn {Directive} %language "@var{language}"
5044 Specify the programming language for the generated parser. Currently
5045 supported languages include C and C++.
5046 @var{language} is case-insensitive.
5049 @deffn {Directive} %locations
5050 Generate the code processing the locations (@pxref{Action Features,
5051 ,Special Features for Use in Actions}). This mode is enabled as soon as
5052 the grammar uses the special @samp{@@@var{n}} tokens, but if your
5053 grammar does not use it, using @samp{%locations} allows for more
5054 accurate syntax error messages.
5057 @deffn {Directive} %name-prefix "@var{prefix}"
5058 Rename the external symbols used in the parser so that they start with
5059 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
5061 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
5062 @code{yylval}, @code{yychar}, @code{yydebug}, and
5063 (if locations are used) @code{yylloc}. If you use a push parser,
5064 @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5065 @code{yypstate_new} and @code{yypstate_delete} will
5066 also be renamed. For example, if you use @samp{%name-prefix "c_"}, the
5067 names become @code{c_parse}, @code{c_lex}, and so on.
5068 For C++ parsers, see the @code{%define namespace} documentation in this
5070 @xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
5074 @deffn {Directive} %no-default-prec
5075 Do not assign a precedence to rules lacking an explicit @code{%prec}
5076 modifier (@pxref{Contextual Precedence, ,Context-Dependent
5081 @deffn {Directive} %no-lines
5082 Don't generate any @code{#line} preprocessor commands in the parser
5083 file. Ordinarily Bison writes these commands in the parser file so that
5084 the C compiler and debuggers will associate errors and object code with
5085 your source file (the grammar file). This directive causes them to
5086 associate errors with the parser file, treating it an independent source
5087 file in its own right.
5090 @deffn {Directive} %output "@var{file}"
5091 Specify @var{file} for the parser file.
5094 @deffn {Directive} %pure-parser
5095 Deprecated version of @code{%define api.pure} (@pxref{Decl Summary, ,%define}),
5096 for which Bison is more careful to warn about unreasonable usage.
5099 @deffn {Directive} %require "@var{version}"
5100 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
5101 Require a Version of Bison}.
5104 @deffn {Directive} %skeleton "@var{file}"
5105 Specify the skeleton to use.
5107 You probably don't need this option unless you are developing Bison.
5108 You should use @code{%language} if you want to specify the skeleton for a
5109 different language, because it is clearer and because it will always choose the
5110 correct skeleton for non-deterministic or push parsers.
5112 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
5113 file in the Bison installation directory.
5114 If it does, @var{file} is an absolute file name or a file name relative to the
5115 directory of the grammar file.
5116 This is similar to how most shells resolve commands.
5119 @deffn {Directive} %token-table
5120 Generate an array of token names in the parser file. The name of the
5121 array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
5122 token whose internal Bison token code number is @var{i}. The first
5123 three elements of @code{yytname} correspond to the predefined tokens
5125 @code{"error"}, and @code{"$undefined"}; after these come the symbols
5126 defined in the grammar file.
5128 The name in the table includes all the characters needed to represent
5129 the token in Bison. For single-character literals and literal
5130 strings, this includes the surrounding quoting characters and any
5131 escape sequences. For example, the Bison single-character literal
5132 @code{'+'} corresponds to a three-character name, represented in C as
5133 @code{"'+'"}; and the Bison two-character literal string @code{"\\/"}
5134 corresponds to a five-character name, represented in C as
5137 When you specify @code{%token-table}, Bison also generates macro
5138 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
5139 @code{YYNRULES}, and @code{YYNSTATES}:
5143 The highest token number, plus one.
5145 The number of nonterminal symbols.
5147 The number of grammar rules,
5149 The number of parser states (@pxref{Parser States}).
5153 @deffn {Directive} %verbose
5154 Write an extra output file containing verbose descriptions of the
5155 parser states and what is done for each type of lookahead token in
5156 that state. @xref{Understanding, , Understanding Your Parser}, for more
5160 @deffn {Directive} %yacc
5161 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
5162 including its naming conventions. @xref{Bison Options}, for more.
5166 @node Multiple Parsers
5167 @section Multiple Parsers in the Same Program
5169 Most programs that use Bison parse only one language and therefore contain
5170 only one Bison parser. But what if you want to parse more than one
5171 language with the same program? Then you need to avoid a name conflict
5172 between different definitions of @code{yyparse}, @code{yylval}, and so on.
5174 The easy way to do this is to use the option @samp{-p @var{prefix}}
5175 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
5176 functions and variables of the Bison parser to start with @var{prefix}
5177 instead of @samp{yy}. You can use this to give each parser distinct
5178 names that do not conflict.
5180 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
5181 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
5182 @code{yychar} and @code{yydebug}. If you use a push parser,
5183 @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5184 @code{yypstate_new} and @code{yypstate_delete} will also be renamed.
5185 For example, if you use @samp{-p c}, the names become @code{cparse},
5186 @code{clex}, and so on.
5188 @strong{All the other variables and macros associated with Bison are not
5189 renamed.} These others are not global; there is no conflict if the same
5190 name is used in different parsers. For example, @code{YYSTYPE} is not
5191 renamed, but defining this in different ways in different parsers causes
5192 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
5194 The @samp{-p} option works by adding macro definitions to the beginning
5195 of the parser source file, defining @code{yyparse} as
5196 @code{@var{prefix}parse}, and so on. This effectively substitutes one
5197 name for the other in the entire parser file.
5200 @chapter Parser C-Language Interface
5201 @cindex C-language interface
5204 The Bison parser is actually a C function named @code{yyparse}. Here we
5205 describe the interface conventions of @code{yyparse} and the other
5206 functions that it needs to use.
5208 Keep in mind that the parser uses many C identifiers starting with
5209 @samp{yy} and @samp{YY} for internal purposes. If you use such an
5210 identifier (aside from those in this manual) in an action or in epilogue
5211 in the grammar file, you are likely to run into trouble.
5214 * Parser Function:: How to call @code{yyparse} and what it returns.
5215 * Push Parser Function:: How to call @code{yypush_parse} and what it returns.
5216 * Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
5217 * Parser Create Function:: How to call @code{yypstate_new} and what it
5219 * Parser Delete Function:: How to call @code{yypstate_delete} and what it
5221 * Lexical:: You must supply a function @code{yylex}
5223 * Error Reporting:: You must supply a function @code{yyerror}.
5224 * Action Features:: Special features for use in actions.
5225 * Internationalization:: How to let the parser speak in the user's
5229 @node Parser Function
5230 @section The Parser Function @code{yyparse}
5233 You call the function @code{yyparse} to cause parsing to occur. This
5234 function reads tokens, executes actions, and ultimately returns when it
5235 encounters end-of-input or an unrecoverable syntax error. You can also
5236 write an action which directs @code{yyparse} to return immediately
5237 without reading further.
5240 @deftypefun int yyparse (void)
5241 The value returned by @code{yyparse} is 0 if parsing was successful (return
5242 is due to end-of-input).
5244 The value is 1 if parsing failed because of invalid input, i.e., input
5245 that contains a syntax error or that causes @code{YYABORT} to be
5248 The value is 2 if parsing failed due to memory exhaustion.
5251 In an action, you can cause immediate return from @code{yyparse} by using
5256 Return immediately with value 0 (to report success).
5261 Return immediately with value 1 (to report failure).
5264 If you use a reentrant parser, you can optionally pass additional
5265 parameter information to it in a reentrant way. To do so, use the
5266 declaration @code{%parse-param}:
5268 @deffn {Directive} %parse-param @{@var{argument-declaration}@}
5269 @findex %parse-param
5270 Declare that an argument declared by the braced-code
5271 @var{argument-declaration} is an additional @code{yyparse} argument.
5272 The @var{argument-declaration} is used when declaring
5273 functions or prototypes. The last identifier in
5274 @var{argument-declaration} must be the argument name.
5277 Here's an example. Write this in the parser:
5280 %parse-param @{int *nastiness@}
5281 %parse-param @{int *randomness@}
5285 Then call the parser like this:
5289 int nastiness, randomness;
5290 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
5291 value = yyparse (&nastiness, &randomness);
5297 In the grammar actions, use expressions like this to refer to the data:
5300 exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
5303 @node Push Parser Function
5304 @section The Push Parser Function @code{yypush_parse}
5305 @findex yypush_parse
5307 You call the function @code{yypush_parse} to parse a single token. This
5308 function is available if either the @code{%define api.push_pull "push"} or
5309 @code{%define api.push_pull "both"} declaration is used.
5310 @xref{Push Decl, ,A Push Parser}.
5312 @deftypefun int yypush_parse (yypstate *yyps)
5313 The value returned by @code{yypush_parse} is the same as for yyparse with the
5314 following exception. @code{yypush_parse} will return YYPUSH_MORE if more input
5315 is required to finish parsing the grammar.
5318 @node Pull Parser Function
5319 @section The Pull Parser Function @code{yypull_parse}
5320 @findex yypull_parse
5322 You call the function @code{yypull_parse} to parse the rest of the input
5323 stream. This function is available if the @code{%define api.push_pull "both"}
5324 declaration is used.
5325 @xref{Push Decl, ,A Push Parser}.
5327 @deftypefun int yypull_parse (yypstate *yyps)
5328 The value returned by @code{yypull_parse} is the same as for @code{yyparse}.
5331 @node Parser Create Function
5332 @section The Parser Create Function @code{yystate_new}
5333 @findex yypstate_new
5335 You call the function @code{yypstate_new} to create a new parser instance.
5336 This function is available if either the @code{%define api.push_pull "push"} or
5337 @code{%define api.push_pull "both"} declaration is used.
5338 @xref{Push Decl, ,A Push Parser}.
5340 @deftypefun yypstate *yypstate_new (void)
5341 The fuction will return a valid parser instance if there was memory available
5342 or NULL if no memory was available.
5345 @node Parser Delete Function
5346 @section The Parser Delete Function @code{yystate_delete}
5347 @findex yypstate_delete
5349 You call the function @code{yypstate_delete} to delete a parser instance.
5350 function is available if either the @code{%define api.push_pull "push"} or
5351 @code{%define api.push_pull "both"} declaration is used.
5352 @xref{Push Decl, ,A Push Parser}.
5354 @deftypefun void yypstate_delete (yypstate *yyps)
5355 This function will reclaim the memory associated with a parser instance.
5356 After this call, you should no longer attempt to use the parser instance.
5360 @section The Lexical Analyzer Function @code{yylex}
5362 @cindex lexical analyzer
5364 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
5365 the input stream and returns them to the parser. Bison does not create
5366 this function automatically; you must write it so that @code{yyparse} can
5367 call it. The function is sometimes referred to as a lexical scanner.
5369 In simple programs, @code{yylex} is often defined at the end of the Bison
5370 grammar file. If @code{yylex} is defined in a separate source file, you
5371 need to arrange for the token-type macro definitions to be available there.
5372 To do this, use the @samp{-d} option when you run Bison, so that it will
5373 write these macro definitions into a separate header file
5374 @file{@var{name}.tab.h} which you can include in the other source files
5375 that need it. @xref{Invocation, ,Invoking Bison}.
5378 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
5379 * Token Values:: How @code{yylex} must return the semantic value
5380 of the token it has read.
5381 * Token Locations:: How @code{yylex} must return the text location
5382 (line number, etc.) of the token, if the
5384 * Pure Calling:: How the calling convention differs
5385 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
5388 @node Calling Convention
5389 @subsection Calling Convention for @code{yylex}
5391 The value that @code{yylex} returns must be the positive numeric code
5392 for the type of token it has just found; a zero or negative value
5393 signifies end-of-input.
5395 When a token is referred to in the grammar rules by a name, that name
5396 in the parser file becomes a C macro whose definition is the proper
5397 numeric code for that token type. So @code{yylex} can use the name
5398 to indicate that type. @xref{Symbols}.
5400 When a token is referred to in the grammar rules by a character literal,
5401 the numeric code for that character is also the code for the token type.
5402 So @code{yylex} can simply return that character code, possibly converted
5403 to @code{unsigned char} to avoid sign-extension. The null character
5404 must not be used this way, because its code is zero and that
5405 signifies end-of-input.
5407 Here is an example showing these things:
5414 if (c == EOF) /* Detect end-of-input. */
5417 if (c == '+' || c == '-')
5418 return c; /* Assume token type for `+' is '+'. */
5420 return INT; /* Return the type of the token. */
5426 This interface has been designed so that the output from the @code{lex}
5427 utility can be used without change as the definition of @code{yylex}.
5429 If the grammar uses literal string tokens, there are two ways that
5430 @code{yylex} can determine the token type codes for them:
5434 If the grammar defines symbolic token names as aliases for the
5435 literal string tokens, @code{yylex} can use these symbolic names like
5436 all others. In this case, the use of the literal string tokens in
5437 the grammar file has no effect on @code{yylex}.
5440 @code{yylex} can find the multicharacter token in the @code{yytname}
5441 table. The index of the token in the table is the token type's code.
5442 The name of a multicharacter token is recorded in @code{yytname} with a
5443 double-quote, the token's characters, and another double-quote. The
5444 token's characters are escaped as necessary to be suitable as input
5447 Here's code for looking up a multicharacter token in @code{yytname},
5448 assuming that the characters of the token are stored in
5449 @code{token_buffer}, and assuming that the token does not contain any
5450 characters like @samp{"} that require escaping.
5453 for (i = 0; i < YYNTOKENS; i++)
5456 && yytname[i][0] == '"'
5457 && ! strncmp (yytname[i] + 1, token_buffer,
5458 strlen (token_buffer))
5459 && yytname[i][strlen (token_buffer) + 1] == '"'
5460 && yytname[i][strlen (token_buffer) + 2] == 0)
5465 The @code{yytname} table is generated only if you use the
5466 @code{%token-table} declaration. @xref{Decl Summary}.
5470 @subsection Semantic Values of Tokens
5473 In an ordinary (nonreentrant) parser, the semantic value of the token must
5474 be stored into the global variable @code{yylval}. When you are using
5475 just one data type for semantic values, @code{yylval} has that type.
5476 Thus, if the type is @code{int} (the default), you might write this in
5482 yylval = value; /* Put value onto Bison stack. */
5483 return INT; /* Return the type of the token. */
5488 When you are using multiple data types, @code{yylval}'s type is a union
5489 made from the @code{%union} declaration (@pxref{Union Decl, ,The
5490 Collection of Value Types}). So when you store a token's value, you
5491 must use the proper member of the union. If the @code{%union}
5492 declaration looks like this:
5505 then the code in @code{yylex} might look like this:
5510 yylval.intval = value; /* Put value onto Bison stack. */
5511 return INT; /* Return the type of the token. */
5516 @node Token Locations
5517 @subsection Textual Locations of Tokens
5520 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
5521 Tracking Locations}) in actions to keep track of the textual locations
5522 of tokens and groupings, then you must provide this information in
5523 @code{yylex}. The function @code{yyparse} expects to find the textual
5524 location of a token just parsed in the global variable @code{yylloc}.
5525 So @code{yylex} must store the proper data in that variable.
5527 By default, the value of @code{yylloc} is a structure and you need only
5528 initialize the members that are going to be used by the actions. The
5529 four members are called @code{first_line}, @code{first_column},
5530 @code{last_line} and @code{last_column}. Note that the use of this
5531 feature makes the parser noticeably slower.
5534 The data type of @code{yylloc} has the name @code{YYLTYPE}.
5537 @subsection Calling Conventions for Pure Parsers
5539 When you use the Bison declaration @code{%define api.pure} to request a
5540 pure, reentrant parser, the global communication variables @code{yylval}
5541 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
5542 Parser}.) In such parsers the two global variables are replaced by
5543 pointers passed as arguments to @code{yylex}. You must declare them as
5544 shown here, and pass the information back by storing it through those
5549 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
5552 *lvalp = value; /* Put value onto Bison stack. */
5553 return INT; /* Return the type of the token. */
5558 If the grammar file does not use the @samp{@@} constructs to refer to
5559 textual locations, then the type @code{YYLTYPE} will not be defined. In
5560 this case, omit the second argument; @code{yylex} will be called with
5564 If you wish to pass the additional parameter data to @code{yylex}, use
5565 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
5568 @deffn {Directive} lex-param @{@var{argument-declaration}@}
5570 Declare that the braced-code @var{argument-declaration} is an
5571 additional @code{yylex} argument declaration.
5577 %parse-param @{int *nastiness@}
5578 %lex-param @{int *nastiness@}
5579 %parse-param @{int *randomness@}
5583 results in the following signature:
5586 int yylex (int *nastiness);
5587 int yyparse (int *nastiness, int *randomness);
5590 If @code{%define api.pure} is added:
5593 int yylex (YYSTYPE *lvalp, int *nastiness);
5594 int yyparse (int *nastiness, int *randomness);
5598 and finally, if both @code{%define api.pure} and @code{%locations} are used:
5601 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
5602 int yyparse (int *nastiness, int *randomness);
5605 @node Error Reporting
5606 @section The Error Reporting Function @code{yyerror}
5607 @cindex error reporting function
5610 @cindex syntax error
5612 The Bison parser detects a @dfn{syntax error} or @dfn{parse error}
5613 whenever it reads a token which cannot satisfy any syntax rule. An
5614 action in the grammar can also explicitly proclaim an error, using the
5615 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
5618 The Bison parser expects to report the error by calling an error
5619 reporting function named @code{yyerror}, which you must supply. It is
5620 called by @code{yyparse} whenever a syntax error is found, and it
5621 receives one argument. For a syntax error, the string is normally
5622 @w{@code{"syntax error"}}.
5624 @findex %error-verbose
5625 If you invoke the directive @code{%error-verbose} in the Bison
5626 declarations section (@pxref{Bison Declarations, ,The Bison Declarations
5627 Section}), then Bison provides a more verbose and specific error message
5628 string instead of just plain @w{@code{"syntax error"}}.
5630 The parser can detect one other kind of error: memory exhaustion. This
5631 can happen when the input contains constructions that are very deeply
5632 nested. It isn't likely you will encounter this, since the Bison
5633 parser normally extends its stack automatically up to a very large limit. But
5634 if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
5635 fashion, except that the argument string is @w{@code{"memory exhausted"}}.
5637 In some cases diagnostics like @w{@code{"syntax error"}} are
5638 translated automatically from English to some other language before
5639 they are passed to @code{yyerror}. @xref{Internationalization}.
5641 The following definition suffices in simple programs:
5646 yyerror (char const *s)
5650 fprintf (stderr, "%s\n", s);
5655 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
5656 error recovery if you have written suitable error recovery grammar rules
5657 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
5658 immediately return 1.
5660 Obviously, in location tracking pure parsers, @code{yyerror} should have
5661 an access to the current location.
5662 This is indeed the case for the @acronym{GLR}
5663 parsers, but not for the Yacc parser, for historical reasons. I.e., if
5664 @samp{%locations %define api.pure} is passed then the prototypes for
5668 void yyerror (char const *msg); /* Yacc parsers. */
5669 void yyerror (YYLTYPE *locp, char const *msg); /* GLR parsers. */
5672 If @samp{%parse-param @{int *nastiness@}} is used, then:
5675 void yyerror (int *nastiness, char const *msg); /* Yacc parsers. */
5676 void yyerror (int *nastiness, char const *msg); /* GLR parsers. */
5679 Finally, @acronym{GLR} and Yacc parsers share the same @code{yyerror} calling
5680 convention for absolutely pure parsers, i.e., when the calling
5681 convention of @code{yylex} @emph{and} the calling convention of
5682 @code{%define api.pure} are pure.
5686 /* Location tracking. */
5690 %lex-param @{int *nastiness@}
5692 %parse-param @{int *nastiness@}
5693 %parse-param @{int *randomness@}
5697 results in the following signatures for all the parser kinds:
5700 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
5701 int yyparse (int *nastiness, int *randomness);
5702 void yyerror (YYLTYPE *locp,
5703 int *nastiness, int *randomness,
5708 The prototypes are only indications of how the code produced by Bison
5709 uses @code{yyerror}. Bison-generated code always ignores the returned
5710 value, so @code{yyerror} can return any type, including @code{void}.
5711 Also, @code{yyerror} can be a variadic function; that is why the
5712 message is always passed last.
5714 Traditionally @code{yyerror} returns an @code{int} that is always
5715 ignored, but this is purely for historical reasons, and @code{void} is
5716 preferable since it more accurately describes the return type for
5720 The variable @code{yynerrs} contains the number of syntax errors
5721 reported so far. Normally this variable is global; but if you
5722 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
5723 then it is a local variable which only the actions can access.
5725 @node Action Features
5726 @section Special Features for Use in Actions
5727 @cindex summary, action features
5728 @cindex action features summary
5730 Here is a table of Bison constructs, variables and macros that
5731 are useful in actions.
5733 @deffn {Variable} $$
5734 Acts like a variable that contains the semantic value for the
5735 grouping made by the current rule. @xref{Actions}.
5738 @deffn {Variable} $@var{n}
5739 Acts like a variable that contains the semantic value for the
5740 @var{n}th component of the current rule. @xref{Actions}.
5743 @deffn {Variable} $<@var{typealt}>$
5744 Like @code{$$} but specifies alternative @var{typealt} in the union
5745 specified by the @code{%union} declaration. @xref{Action Types, ,Data
5746 Types of Values in Actions}.
5749 @deffn {Variable} $<@var{typealt}>@var{n}
5750 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
5751 union specified by the @code{%union} declaration.
5752 @xref{Action Types, ,Data Types of Values in Actions}.
5755 @deffn {Macro} YYABORT;
5756 Return immediately from @code{yyparse}, indicating failure.
5757 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
5760 @deffn {Macro} YYACCEPT;
5761 Return immediately from @code{yyparse}, indicating success.
5762 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
5765 @deffn {Macro} YYBACKUP (@var{token}, @var{value});
5767 Unshift a token. This macro is allowed only for rules that reduce
5768 a single value, and only when there is no lookahead token.
5769 It is also disallowed in @acronym{GLR} parsers.
5770 It installs a lookahead token with token type @var{token} and
5771 semantic value @var{value}; then it discards the value that was
5772 going to be reduced by this rule.
5774 If the macro is used when it is not valid, such as when there is
5775 a lookahead token already, then it reports a syntax error with
5776 a message @samp{cannot back up} and performs ordinary error
5779 In either case, the rest of the action is not executed.
5782 @deffn {Macro} YYEMPTY
5784 Value stored in @code{yychar} when there is no lookahead token.
5787 @deffn {Macro} YYEOF
5789 Value stored in @code{yychar} when the lookahead is the end of the input
5793 @deffn {Macro} YYERROR;
5795 Cause an immediate syntax error. This statement initiates error
5796 recovery just as if the parser itself had detected an error; however, it
5797 does not call @code{yyerror}, and does not print any message. If you
5798 want to print an error message, call @code{yyerror} explicitly before
5799 the @samp{YYERROR;} statement. @xref{Error Recovery}.
5802 @deffn {Macro} YYRECOVERING
5803 @findex YYRECOVERING
5804 The expression @code{YYRECOVERING ()} yields 1 when the parser
5805 is recovering from a syntax error, and 0 otherwise.
5806 @xref{Error Recovery}.
5809 @deffn {Variable} yychar
5810 Variable containing either the lookahead token, or @code{YYEOF} when the
5811 lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
5812 has been performed so the next token is not yet known.
5813 Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
5815 @xref{Lookahead, ,Lookahead Tokens}.
5818 @deffn {Macro} yyclearin;
5819 Discard the current lookahead token. This is useful primarily in
5821 Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
5823 @xref{Error Recovery}.
5826 @deffn {Macro} yyerrok;
5827 Resume generating error messages immediately for subsequent syntax
5828 errors. This is useful primarily in error rules.
5829 @xref{Error Recovery}.
5832 @deffn {Variable} yylloc
5833 Variable containing the lookahead token location when @code{yychar} is not set
5834 to @code{YYEMPTY} or @code{YYEOF}.
5835 Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
5837 @xref{Actions and Locations, ,Actions and Locations}.
5840 @deffn {Variable} yylval
5841 Variable containing the lookahead token semantic value when @code{yychar} is
5842 not set to @code{YYEMPTY} or @code{YYEOF}.
5843 Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
5845 @xref{Actions, ,Actions}.
5850 Acts like a structure variable containing information on the textual location
5851 of the grouping made by the current rule. @xref{Locations, ,
5852 Tracking Locations}.
5854 @c Check if those paragraphs are still useful or not.
5858 @c int first_line, last_line;
5859 @c int first_column, last_column;
5863 @c Thus, to get the starting line number of the third component, you would
5864 @c use @samp{@@3.first_line}.
5866 @c In order for the members of this structure to contain valid information,
5867 @c you must make @code{yylex} supply this information about each token.
5868 @c If you need only certain members, then @code{yylex} need only fill in
5871 @c The use of this feature makes the parser noticeably slower.
5874 @deffn {Value} @@@var{n}
5876 Acts like a structure variable containing information on the textual location
5877 of the @var{n}th component of the current rule. @xref{Locations, ,
5878 Tracking Locations}.
5881 @node Internationalization
5882 @section Parser Internationalization
5883 @cindex internationalization
5889 A Bison-generated parser can print diagnostics, including error and
5890 tracing messages. By default, they appear in English. However, Bison
5891 also supports outputting diagnostics in the user's native language. To
5892 make this work, the user should set the usual environment variables.
5893 @xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
5894 For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
5895 set the user's locale to French Canadian using the @acronym{UTF}-8
5896 encoding. The exact set of available locales depends on the user's
5899 The maintainer of a package that uses a Bison-generated parser enables
5900 the internationalization of the parser's output through the following
5901 steps. Here we assume a package that uses @acronym{GNU} Autoconf and
5902 @acronym{GNU} Automake.
5906 @cindex bison-i18n.m4
5907 Into the directory containing the @acronym{GNU} Autoconf macros used
5908 by the package---often called @file{m4}---copy the
5909 @file{bison-i18n.m4} file installed by Bison under
5910 @samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
5914 cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
5919 @vindex BISON_LOCALEDIR
5920 @vindex YYENABLE_NLS
5921 In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
5922 invocation, add an invocation of @code{BISON_I18N}. This macro is
5923 defined in the file @file{bison-i18n.m4} that you copied earlier. It
5924 causes @samp{configure} to find the value of the
5925 @code{BISON_LOCALEDIR} variable, and it defines the source-language
5926 symbol @code{YYENABLE_NLS} to enable translations in the
5927 Bison-generated parser.
5930 In the @code{main} function of your program, designate the directory
5931 containing Bison's runtime message catalog, through a call to
5932 @samp{bindtextdomain} with domain name @samp{bison-runtime}.
5936 bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
5939 Typically this appears after any other call @code{bindtextdomain
5940 (PACKAGE, LOCALEDIR)} that your package already has. Here we rely on
5941 @samp{BISON_LOCALEDIR} to be defined as a string through the
5945 In the @file{Makefile.am} that controls the compilation of the @code{main}
5946 function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
5947 either in @samp{DEFS} or in @samp{AM_CPPFLAGS}. For example:
5950 DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
5956 AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
5960 Finally, invoke the command @command{autoreconf} to generate the build
5966 @chapter The Bison Parser Algorithm
5967 @cindex Bison parser algorithm
5968 @cindex algorithm of parser
5971 @cindex parser stack
5972 @cindex stack, parser
5974 As Bison reads tokens, it pushes them onto a stack along with their
5975 semantic values. The stack is called the @dfn{parser stack}. Pushing a
5976 token is traditionally called @dfn{shifting}.
5978 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
5979 @samp{3} to come. The stack will have four elements, one for each token
5982 But the stack does not always have an element for each token read. When
5983 the last @var{n} tokens and groupings shifted match the components of a
5984 grammar rule, they can be combined according to that rule. This is called
5985 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
5986 single grouping whose symbol is the result (left hand side) of that rule.
5987 Running the rule's action is part of the process of reduction, because this
5988 is what computes the semantic value of the resulting grouping.
5990 For example, if the infix calculator's parser stack contains this:
5997 and the next input token is a newline character, then the last three
5998 elements can be reduced to 15 via the rule:
6001 expr: expr '*' expr;
6005 Then the stack contains just these three elements:
6012 At this point, another reduction can be made, resulting in the single value
6013 16. Then the newline token can be shifted.
6015 The parser tries, by shifts and reductions, to reduce the entire input down
6016 to a single grouping whose symbol is the grammar's start-symbol
6017 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
6019 This kind of parser is known in the literature as a bottom-up parser.
6022 * Lookahead:: Parser looks one token ahead when deciding what to do.
6023 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
6024 * Precedence:: Operator precedence works by resolving conflicts.
6025 * Contextual Precedence:: When an operator's precedence depends on context.
6026 * Parser States:: The parser is a finite-state-machine with stack.
6027 * Reduce/Reduce:: When two rules are applicable in the same situation.
6028 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
6029 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
6030 * Memory Management:: What happens when memory is exhausted. How to avoid it.
6034 @section Lookahead Tokens
6035 @cindex lookahead token
6037 The Bison parser does @emph{not} always reduce immediately as soon as the
6038 last @var{n} tokens and groupings match a rule. This is because such a
6039 simple strategy is inadequate to handle most languages. Instead, when a
6040 reduction is possible, the parser sometimes ``looks ahead'' at the next
6041 token in order to decide what to do.
6043 When a token is read, it is not immediately shifted; first it becomes the
6044 @dfn{lookahead token}, which is not on the stack. Now the parser can
6045 perform one or more reductions of tokens and groupings on the stack, while
6046 the lookahead token remains off to the side. When no more reductions
6047 should take place, the lookahead token is shifted onto the stack. This
6048 does not mean that all possible reductions have been done; depending on the
6049 token type of the lookahead token, some rules may choose to delay their
6052 Here is a simple case where lookahead is needed. These three rules define
6053 expressions which contain binary addition operators and postfix unary
6054 factorial operators (@samp{!}), and allow parentheses for grouping.
6071 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
6072 should be done? If the following token is @samp{)}, then the first three
6073 tokens must be reduced to form an @code{expr}. This is the only valid
6074 course, because shifting the @samp{)} would produce a sequence of symbols
6075 @w{@code{term ')'}}, and no rule allows this.
6077 If the following token is @samp{!}, then it must be shifted immediately so
6078 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
6079 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
6080 @code{expr}. It would then be impossible to shift the @samp{!} because
6081 doing so would produce on the stack the sequence of symbols @code{expr
6082 '!'}. No rule allows that sequence.
6087 The lookahead token is stored in the variable @code{yychar}.
6088 Its semantic value and location, if any, are stored in the variables
6089 @code{yylval} and @code{yylloc}.
6090 @xref{Action Features, ,Special Features for Use in Actions}.
6093 @section Shift/Reduce Conflicts
6095 @cindex shift/reduce conflicts
6096 @cindex dangling @code{else}
6097 @cindex @code{else}, dangling
6099 Suppose we are parsing a language which has if-then and if-then-else
6100 statements, with a pair of rules like this:
6106 | IF expr THEN stmt ELSE stmt
6112 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
6113 terminal symbols for specific keyword tokens.
6115 When the @code{ELSE} token is read and becomes the lookahead token, the
6116 contents of the stack (assuming the input is valid) are just right for
6117 reduction by the first rule. But it is also legitimate to shift the
6118 @code{ELSE}, because that would lead to eventual reduction by the second
6121 This situation, where either a shift or a reduction would be valid, is
6122 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
6123 these conflicts by choosing to shift, unless otherwise directed by
6124 operator precedence declarations. To see the reason for this, let's
6125 contrast it with the other alternative.
6127 Since the parser prefers to shift the @code{ELSE}, the result is to attach
6128 the else-clause to the innermost if-statement, making these two inputs
6132 if x then if y then win (); else lose;
6134 if x then do; if y then win (); else lose; end;
6137 But if the parser chose to reduce when possible rather than shift, the
6138 result would be to attach the else-clause to the outermost if-statement,
6139 making these two inputs equivalent:
6142 if x then if y then win (); else lose;
6144 if x then do; if y then win (); end; else lose;
6147 The conflict exists because the grammar as written is ambiguous: either
6148 parsing of the simple nested if-statement is legitimate. The established
6149 convention is that these ambiguities are resolved by attaching the
6150 else-clause to the innermost if-statement; this is what Bison accomplishes
6151 by choosing to shift rather than reduce. (It would ideally be cleaner to
6152 write an unambiguous grammar, but that is very hard to do in this case.)
6153 This particular ambiguity was first encountered in the specifications of
6154 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
6156 To avoid warnings from Bison about predictable, legitimate shift/reduce
6157 conflicts, use the @code{%expect @var{n}} declaration. There will be no
6158 warning as long as the number of shift/reduce conflicts is exactly @var{n}.
6159 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
6161 The definition of @code{if_stmt} above is solely to blame for the
6162 conflict, but the conflict does not actually appear without additional
6163 rules. Here is a complete Bison input file that actually manifests the
6168 %token IF THEN ELSE variable
6180 | IF expr THEN stmt ELSE stmt
6189 @section Operator Precedence
6190 @cindex operator precedence
6191 @cindex precedence of operators
6193 Another situation where shift/reduce conflicts appear is in arithmetic
6194 expressions. Here shifting is not always the preferred resolution; the
6195 Bison declarations for operator precedence allow you to specify when to
6196 shift and when to reduce.
6199 * Why Precedence:: An example showing why precedence is needed.
6200 * Using Precedence:: How to specify precedence in Bison grammars.
6201 * Precedence Examples:: How these features are used in the previous example.
6202 * How Precedence:: How they work.
6205 @node Why Precedence
6206 @subsection When Precedence is Needed
6208 Consider the following ambiguous grammar fragment (ambiguous because the
6209 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
6223 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
6224 should it reduce them via the rule for the subtraction operator? It
6225 depends on the next token. Of course, if the next token is @samp{)}, we
6226 must reduce; shifting is invalid because no single rule can reduce the
6227 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
6228 the next token is @samp{*} or @samp{<}, we have a choice: either
6229 shifting or reduction would allow the parse to complete, but with
6232 To decide which one Bison should do, we must consider the results. If
6233 the next operator token @var{op} is shifted, then it must be reduced
6234 first in order to permit another opportunity to reduce the difference.
6235 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
6236 hand, if the subtraction is reduced before shifting @var{op}, the result
6237 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
6238 reduce should depend on the relative precedence of the operators
6239 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
6242 @cindex associativity
6243 What about input such as @w{@samp{1 - 2 - 5}}; should this be
6244 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
6245 operators we prefer the former, which is called @dfn{left association}.
6246 The latter alternative, @dfn{right association}, is desirable for
6247 assignment operators. The choice of left or right association is a
6248 matter of whether the parser chooses to shift or reduce when the stack
6249 contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
6250 makes right-associativity.
6252 @node Using Precedence
6253 @subsection Specifying Operator Precedence
6258 Bison allows you to specify these choices with the operator precedence
6259 declarations @code{%left} and @code{%right}. Each such declaration
6260 contains a list of tokens, which are operators whose precedence and
6261 associativity is being declared. The @code{%left} declaration makes all
6262 those operators left-associative and the @code{%right} declaration makes
6263 them right-associative. A third alternative is @code{%nonassoc}, which
6264 declares that it is a syntax error to find the same operator twice ``in a
6267 The relative precedence of different operators is controlled by the
6268 order in which they are declared. The first @code{%left} or
6269 @code{%right} declaration in the file declares the operators whose
6270 precedence is lowest, the next such declaration declares the operators
6271 whose precedence is a little higher, and so on.
6273 @node Precedence Examples
6274 @subsection Precedence Examples
6276 In our example, we would want the following declarations:
6284 In a more complete example, which supports other operators as well, we
6285 would declare them in groups of equal precedence. For example, @code{'+'} is
6286 declared with @code{'-'}:
6289 %left '<' '>' '=' NE LE GE
6295 (Here @code{NE} and so on stand for the operators for ``not equal''
6296 and so on. We assume that these tokens are more than one character long
6297 and therefore are represented by names, not character literals.)
6299 @node How Precedence
6300 @subsection How Precedence Works
6302 The first effect of the precedence declarations is to assign precedence
6303 levels to the terminal symbols declared. The second effect is to assign
6304 precedence levels to certain rules: each rule gets its precedence from
6305 the last terminal symbol mentioned in the components. (You can also
6306 specify explicitly the precedence of a rule. @xref{Contextual
6307 Precedence, ,Context-Dependent Precedence}.)
6309 Finally, the resolution of conflicts works by comparing the precedence
6310 of the rule being considered with that of the lookahead token. If the
6311 token's precedence is higher, the choice is to shift. If the rule's
6312 precedence is higher, the choice is to reduce. If they have equal
6313 precedence, the choice is made based on the associativity of that
6314 precedence level. The verbose output file made by @samp{-v}
6315 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
6318 Not all rules and not all tokens have precedence. If either the rule or
6319 the lookahead token has no precedence, then the default is to shift.
6321 @node Contextual Precedence
6322 @section Context-Dependent Precedence
6323 @cindex context-dependent precedence
6324 @cindex unary operator precedence
6325 @cindex precedence, context-dependent
6326 @cindex precedence, unary operator
6329 Often the precedence of an operator depends on the context. This sounds
6330 outlandish at first, but it is really very common. For example, a minus
6331 sign typically has a very high precedence as a unary operator, and a
6332 somewhat lower precedence (lower than multiplication) as a binary operator.
6334 The Bison precedence declarations, @code{%left}, @code{%right} and
6335 @code{%nonassoc}, can only be used once for a given token; so a token has
6336 only one precedence declared in this way. For context-dependent
6337 precedence, you need to use an additional mechanism: the @code{%prec}
6340 The @code{%prec} modifier declares the precedence of a particular rule by
6341 specifying a terminal symbol whose precedence should be used for that rule.
6342 It's not necessary for that symbol to appear otherwise in the rule. The
6343 modifier's syntax is:
6346 %prec @var{terminal-symbol}
6350 and it is written after the components of the rule. Its effect is to
6351 assign the rule the precedence of @var{terminal-symbol}, overriding
6352 the precedence that would be deduced for it in the ordinary way. The
6353 altered rule precedence then affects how conflicts involving that rule
6354 are resolved (@pxref{Precedence, ,Operator Precedence}).
6356 Here is how @code{%prec} solves the problem of unary minus. First, declare
6357 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
6358 are no tokens of this type, but the symbol serves to stand for its
6368 Now the precedence of @code{UMINUS} can be used in specific rules:
6375 | '-' exp %prec UMINUS
6380 If you forget to append @code{%prec UMINUS} to the rule for unary
6381 minus, Bison silently assumes that minus has its usual precedence.
6382 This kind of problem can be tricky to debug, since one typically
6383 discovers the mistake only by testing the code.
6385 The @code{%no-default-prec;} declaration makes it easier to discover
6386 this kind of problem systematically. It causes rules that lack a
6387 @code{%prec} modifier to have no precedence, even if the last terminal
6388 symbol mentioned in their components has a declared precedence.
6390 If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
6391 for all rules that participate in precedence conflict resolution.
6392 Then you will see any shift/reduce conflict until you tell Bison how
6393 to resolve it, either by changing your grammar or by adding an
6394 explicit precedence. This will probably add declarations to the
6395 grammar, but it helps to protect against incorrect rule precedences.
6397 The effect of @code{%no-default-prec;} can be reversed by giving
6398 @code{%default-prec;}, which is the default.
6402 @section Parser States
6403 @cindex finite-state machine
6404 @cindex parser state
6405 @cindex state (of parser)
6407 The function @code{yyparse} is implemented using a finite-state machine.
6408 The values pushed on the parser stack are not simply token type codes; they
6409 represent the entire sequence of terminal and nonterminal symbols at or
6410 near the top of the stack. The current state collects all the information
6411 about previous input which is relevant to deciding what to do next.
6413 Each time a lookahead token is read, the current parser state together
6414 with the type of lookahead token are looked up in a table. This table
6415 entry can say, ``Shift the lookahead token.'' In this case, it also
6416 specifies the new parser state, which is pushed onto the top of the
6417 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
6418 This means that a certain number of tokens or groupings are taken off
6419 the top of the stack, and replaced by one grouping. In other words,
6420 that number of states are popped from the stack, and one new state is
6423 There is one other alternative: the table can say that the lookahead token
6424 is erroneous in the current state. This causes error processing to begin
6425 (@pxref{Error Recovery}).
6428 @section Reduce/Reduce Conflicts
6429 @cindex reduce/reduce conflict
6430 @cindex conflicts, reduce/reduce
6432 A reduce/reduce conflict occurs if there are two or more rules that apply
6433 to the same sequence of input. This usually indicates a serious error
6436 For example, here is an erroneous attempt to define a sequence
6437 of zero or more @code{word} groupings.
6440 sequence: /* empty */
6441 @{ printf ("empty sequence\n"); @}
6444 @{ printf ("added word %s\n", $2); @}
6447 maybeword: /* empty */
6448 @{ printf ("empty maybeword\n"); @}
6450 @{ printf ("single word %s\n", $1); @}
6455 The error is an ambiguity: there is more than one way to parse a single
6456 @code{word} into a @code{sequence}. It could be reduced to a
6457 @code{maybeword} and then into a @code{sequence} via the second rule.
6458 Alternatively, nothing-at-all could be reduced into a @code{sequence}
6459 via the first rule, and this could be combined with the @code{word}
6460 using the third rule for @code{sequence}.
6462 There is also more than one way to reduce nothing-at-all into a
6463 @code{sequence}. This can be done directly via the first rule,
6464 or indirectly via @code{maybeword} and then the second rule.
6466 You might think that this is a distinction without a difference, because it
6467 does not change whether any particular input is valid or not. But it does
6468 affect which actions are run. One parsing order runs the second rule's
6469 action; the other runs the first rule's action and the third rule's action.
6470 In this example, the output of the program changes.
6472 Bison resolves a reduce/reduce conflict by choosing to use the rule that
6473 appears first in the grammar, but it is very risky to rely on this. Every
6474 reduce/reduce conflict must be studied and usually eliminated. Here is the
6475 proper way to define @code{sequence}:
6478 sequence: /* empty */
6479 @{ printf ("empty sequence\n"); @}
6481 @{ printf ("added word %s\n", $2); @}
6485 Here is another common error that yields a reduce/reduce conflict:
6488 sequence: /* empty */
6490 | sequence redirects
6497 redirects:/* empty */
6498 | redirects redirect
6503 The intention here is to define a sequence which can contain either
6504 @code{word} or @code{redirect} groupings. The individual definitions of
6505 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
6506 three together make a subtle ambiguity: even an empty input can be parsed
6507 in infinitely many ways!
6509 Consider: nothing-at-all could be a @code{words}. Or it could be two
6510 @code{words} in a row, or three, or any number. It could equally well be a
6511 @code{redirects}, or two, or any number. Or it could be a @code{words}
6512 followed by three @code{redirects} and another @code{words}. And so on.
6514 Here are two ways to correct these rules. First, to make it a single level
6518 sequence: /* empty */
6524 Second, to prevent either a @code{words} or a @code{redirects}
6528 sequence: /* empty */
6530 | sequence redirects
6538 | redirects redirect
6542 @node Mystery Conflicts
6543 @section Mysterious Reduce/Reduce Conflicts
6545 Sometimes reduce/reduce conflicts can occur that don't look warranted.
6553 def: param_spec return_spec ','
6557 | name_list ':' type
6575 | name ',' name_list
6580 It would seem that this grammar can be parsed with only a single token
6581 of lookahead: when a @code{param_spec} is being read, an @code{ID} is
6582 a @code{name} if a comma or colon follows, or a @code{type} if another
6583 @code{ID} follows. In other words, this grammar is @acronym{LR}(1).
6585 @cindex @acronym{LR}(1)
6586 @cindex @acronym{LALR}(1)
6587 However, Bison, like most parser generators, cannot actually handle all
6588 @acronym{LR}(1) grammars. In this grammar, two contexts, that after
6590 at the beginning of a @code{param_spec} and likewise at the beginning of
6591 a @code{return_spec}, are similar enough that Bison assumes they are the
6592 same. They appear similar because the same set of rules would be
6593 active---the rule for reducing to a @code{name} and that for reducing to
6594 a @code{type}. Bison is unable to determine at that stage of processing
6595 that the rules would require different lookahead tokens in the two
6596 contexts, so it makes a single parser state for them both. Combining
6597 the two contexts causes a conflict later. In parser terminology, this
6598 occurrence means that the grammar is not @acronym{LALR}(1).
6600 In general, it is better to fix deficiencies than to document them. But
6601 this particular deficiency is intrinsically hard to fix; parser
6602 generators that can handle @acronym{LR}(1) grammars are hard to write
6604 produce parsers that are very large. In practice, Bison is more useful
6607 When the problem arises, you can often fix it by identifying the two
6608 parser states that are being confused, and adding something to make them
6609 look distinct. In the above example, adding one rule to
6610 @code{return_spec} as follows makes the problem go away:
6621 /* This rule is never used. */
6627 This corrects the problem because it introduces the possibility of an
6628 additional active rule in the context after the @code{ID} at the beginning of
6629 @code{return_spec}. This rule is not active in the corresponding context
6630 in a @code{param_spec}, so the two contexts receive distinct parser states.
6631 As long as the token @code{BOGUS} is never generated by @code{yylex},
6632 the added rule cannot alter the way actual input is parsed.
6634 In this particular example, there is another way to solve the problem:
6635 rewrite the rule for @code{return_spec} to use @code{ID} directly
6636 instead of via @code{name}. This also causes the two confusing
6637 contexts to have different sets of active rules, because the one for
6638 @code{return_spec} activates the altered rule for @code{return_spec}
6639 rather than the one for @code{name}.
6644 | name_list ':' type
6652 For a more detailed exposition of @acronym{LALR}(1) parsers and parser
6653 generators, please see:
6654 Frank DeRemer and Thomas Pennello, Efficient Computation of
6655 @acronym{LALR}(1) Look-Ahead Sets, @cite{@acronym{ACM} Transactions on
6656 Programming Languages and Systems}, Vol.@: 4, No.@: 4 (October 1982),
6657 pp.@: 615--649 @uref{http://doi.acm.org/10.1145/69622.357187}.
6659 @node Generalized LR Parsing
6660 @section Generalized @acronym{LR} (@acronym{GLR}) Parsing
6661 @cindex @acronym{GLR} parsing
6662 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
6663 @cindex ambiguous grammars
6664 @cindex nondeterministic parsing
6666 Bison produces @emph{deterministic} parsers that choose uniquely
6667 when to reduce and which reduction to apply
6668 based on a summary of the preceding input and on one extra token of lookahead.
6669 As a result, normal Bison handles a proper subset of the family of
6670 context-free languages.
6671 Ambiguous grammars, since they have strings with more than one possible
6672 sequence of reductions cannot have deterministic parsers in this sense.
6673 The same is true of languages that require more than one symbol of
6674 lookahead, since the parser lacks the information necessary to make a
6675 decision at the point it must be made in a shift-reduce parser.
6676 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
6677 there are languages where Bison's particular choice of how to
6678 summarize the input seen so far loses necessary information.
6680 When you use the @samp{%glr-parser} declaration in your grammar file,
6681 Bison generates a parser that uses a different algorithm, called
6682 Generalized @acronym{LR} (or @acronym{GLR}). A Bison @acronym{GLR}
6683 parser uses the same basic
6684 algorithm for parsing as an ordinary Bison parser, but behaves
6685 differently in cases where there is a shift-reduce conflict that has not
6686 been resolved by precedence rules (@pxref{Precedence}) or a
6687 reduce-reduce conflict. When a @acronym{GLR} parser encounters such a
6689 effectively @emph{splits} into a several parsers, one for each possible
6690 shift or reduction. These parsers then proceed as usual, consuming
6691 tokens in lock-step. Some of the stacks may encounter other conflicts
6692 and split further, with the result that instead of a sequence of states,
6693 a Bison @acronym{GLR} parsing stack is what is in effect a tree of states.
6695 In effect, each stack represents a guess as to what the proper parse
6696 is. Additional input may indicate that a guess was wrong, in which case
6697 the appropriate stack silently disappears. Otherwise, the semantics
6698 actions generated in each stack are saved, rather than being executed
6699 immediately. When a stack disappears, its saved semantic actions never
6700 get executed. When a reduction causes two stacks to become equivalent,
6701 their sets of semantic actions are both saved with the state that
6702 results from the reduction. We say that two stacks are equivalent
6703 when they both represent the same sequence of states,
6704 and each pair of corresponding states represents a
6705 grammar symbol that produces the same segment of the input token
6708 Whenever the parser makes a transition from having multiple
6709 states to having one, it reverts to the normal @acronym{LALR}(1) parsing
6710 algorithm, after resolving and executing the saved-up actions.
6711 At this transition, some of the states on the stack will have semantic
6712 values that are sets (actually multisets) of possible actions. The
6713 parser tries to pick one of the actions by first finding one whose rule
6714 has the highest dynamic precedence, as set by the @samp{%dprec}
6715 declaration. Otherwise, if the alternative actions are not ordered by
6716 precedence, but there the same merging function is declared for both
6717 rules by the @samp{%merge} declaration,
6718 Bison resolves and evaluates both and then calls the merge function on
6719 the result. Otherwise, it reports an ambiguity.
6721 It is possible to use a data structure for the @acronym{GLR} parsing tree that
6722 permits the processing of any @acronym{LALR}(1) grammar in linear time (in the
6723 size of the input), any unambiguous (not necessarily
6724 @acronym{LALR}(1)) grammar in
6725 quadratic worst-case time, and any general (possibly ambiguous)
6726 context-free grammar in cubic worst-case time. However, Bison currently
6727 uses a simpler data structure that requires time proportional to the
6728 length of the input times the maximum number of stacks required for any
6729 prefix of the input. Thus, really ambiguous or nondeterministic
6730 grammars can require exponential time and space to process. Such badly
6731 behaving examples, however, are not generally of practical interest.
6732 Usually, nondeterminism in a grammar is local---the parser is ``in
6733 doubt'' only for a few tokens at a time. Therefore, the current data
6734 structure should generally be adequate. On @acronym{LALR}(1) portions of a
6735 grammar, in particular, it is only slightly slower than with the default
6738 For a more detailed exposition of @acronym{GLR} parsers, please see: Elizabeth
6739 Scott, Adrian Johnstone and Shamsa Sadaf Hussain, Tomita-Style
6740 Generalised @acronym{LR} Parsers, Royal Holloway, University of
6741 London, Department of Computer Science, TR-00-12,
6742 @uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps},
6745 @node Memory Management
6746 @section Memory Management, and How to Avoid Memory Exhaustion
6747 @cindex memory exhaustion
6748 @cindex memory management
6749 @cindex stack overflow
6750 @cindex parser stack overflow
6751 @cindex overflow of parser stack
6753 The Bison parser stack can run out of memory if too many tokens are shifted and
6754 not reduced. When this happens, the parser function @code{yyparse}
6755 calls @code{yyerror} and then returns 2.
6757 Because Bison parsers have growing stacks, hitting the upper limit
6758 usually results from using a right recursion instead of a left
6759 recursion, @xref{Recursion, ,Recursive Rules}.
6762 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
6763 parser stack can become before memory is exhausted. Define the
6764 macro with a value that is an integer. This value is the maximum number
6765 of tokens that can be shifted (and not reduced) before overflow.
6767 The stack space allowed is not necessarily allocated. If you specify a
6768 large value for @code{YYMAXDEPTH}, the parser normally allocates a small
6769 stack at first, and then makes it bigger by stages as needed. This
6770 increasing allocation happens automatically and silently. Therefore,
6771 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
6772 space for ordinary inputs that do not need much stack.
6774 However, do not allow @code{YYMAXDEPTH} to be a value so large that
6775 arithmetic overflow could occur when calculating the size of the stack
6776 space. Also, do not allow @code{YYMAXDEPTH} to be less than
6779 @cindex default stack limit
6780 The default value of @code{YYMAXDEPTH}, if you do not define it, is
6784 You can control how much stack is allocated initially by defining the
6785 macro @code{YYINITDEPTH} to a positive integer. For the C
6786 @acronym{LALR}(1) parser, this value must be a compile-time constant
6787 unless you are assuming C99 or some other target language or compiler
6788 that allows variable-length arrays. The default is 200.
6790 Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
6792 @c FIXME: C++ output.
6793 Because of semantical differences between C and C++, the
6794 @acronym{LALR}(1) parsers in C produced by Bison cannot grow when compiled
6795 by C++ compilers. In this precise case (compiling a C parser as C++) you are
6796 suggested to grow @code{YYINITDEPTH}. The Bison maintainers hope to fix
6797 this deficiency in a future release.
6799 @node Error Recovery
6800 @chapter Error Recovery
6801 @cindex error recovery
6802 @cindex recovery from errors
6804 It is not usually acceptable to have a program terminate on a syntax
6805 error. For example, a compiler should recover sufficiently to parse the
6806 rest of the input file and check it for errors; a calculator should accept
6809 In a simple interactive command parser where each input is one line, it may
6810 be sufficient to allow @code{yyparse} to return 1 on error and have the
6811 caller ignore the rest of the input line when that happens (and then call
6812 @code{yyparse} again). But this is inadequate for a compiler, because it
6813 forgets all the syntactic context leading up to the error. A syntax error
6814 deep within a function in the compiler input should not cause the compiler
6815 to treat the following line like the beginning of a source file.
6818 You can define how to recover from a syntax error by writing rules to
6819 recognize the special token @code{error}. This is a terminal symbol that
6820 is always defined (you need not declare it) and reserved for error
6821 handling. The Bison parser generates an @code{error} token whenever a
6822 syntax error happens; if you have provided a rule to recognize this token
6823 in the current context, the parse can continue.
6828 stmnts: /* empty string */
6834 The fourth rule in this example says that an error followed by a newline
6835 makes a valid addition to any @code{stmnts}.
6837 What happens if a syntax error occurs in the middle of an @code{exp}? The
6838 error recovery rule, interpreted strictly, applies to the precise sequence
6839 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
6840 the middle of an @code{exp}, there will probably be some additional tokens
6841 and subexpressions on the stack after the last @code{stmnts}, and there
6842 will be tokens to read before the next newline. So the rule is not
6843 applicable in the ordinary way.
6845 But Bison can force the situation to fit the rule, by discarding part of
6846 the semantic context and part of the input. First it discards states
6847 and objects from the stack until it gets back to a state in which the
6848 @code{error} token is acceptable. (This means that the subexpressions
6849 already parsed are discarded, back to the last complete @code{stmnts}.)
6850 At this point the @code{error} token can be shifted. Then, if the old
6851 lookahead token is not acceptable to be shifted next, the parser reads
6852 tokens and discards them until it finds a token which is acceptable. In
6853 this example, Bison reads and discards input until the next newline so
6854 that the fourth rule can apply. Note that discarded symbols are
6855 possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
6856 Discarded Symbols}, for a means to reclaim this memory.
6858 The choice of error rules in the grammar is a choice of strategies for
6859 error recovery. A simple and useful strategy is simply to skip the rest of
6860 the current input line or current statement if an error is detected:
6863 stmnt: error ';' /* On error, skip until ';' is read. */
6866 It is also useful to recover to the matching close-delimiter of an
6867 opening-delimiter that has already been parsed. Otherwise the
6868 close-delimiter will probably appear to be unmatched, and generate another,
6869 spurious error message:
6872 primary: '(' expr ')'
6878 Error recovery strategies are necessarily guesses. When they guess wrong,
6879 one syntax error often leads to another. In the above example, the error
6880 recovery rule guesses that an error is due to bad input within one
6881 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
6882 middle of a valid @code{stmnt}. After the error recovery rule recovers
6883 from the first error, another syntax error will be found straightaway,
6884 since the text following the spurious semicolon is also an invalid
6887 To prevent an outpouring of error messages, the parser will output no error
6888 message for another syntax error that happens shortly after the first; only
6889 after three consecutive input tokens have been successfully shifted will
6890 error messages resume.
6892 Note that rules which accept the @code{error} token may have actions, just
6893 as any other rules can.
6896 You can make error messages resume immediately by using the macro
6897 @code{yyerrok} in an action. If you do this in the error rule's action, no
6898 error messages will be suppressed. This macro requires no arguments;
6899 @samp{yyerrok;} is a valid C statement.
6902 The previous lookahead token is reanalyzed immediately after an error. If
6903 this is unacceptable, then the macro @code{yyclearin} may be used to clear
6904 this token. Write the statement @samp{yyclearin;} in the error rule's
6906 @xref{Action Features, ,Special Features for Use in Actions}.
6908 For example, suppose that on a syntax error, an error handling routine is
6909 called that advances the input stream to some point where parsing should
6910 once again commence. The next symbol returned by the lexical scanner is
6911 probably correct. The previous lookahead token ought to be discarded
6912 with @samp{yyclearin;}.
6914 @vindex YYRECOVERING
6915 The expression @code{YYRECOVERING ()} yields 1 when the parser
6916 is recovering from a syntax error, and 0 otherwise.
6917 Syntax error diagnostics are suppressed while recovering from a syntax
6920 @node Context Dependency
6921 @chapter Handling Context Dependencies
6923 The Bison paradigm is to parse tokens first, then group them into larger
6924 syntactic units. In many languages, the meaning of a token is affected by
6925 its context. Although this violates the Bison paradigm, certain techniques
6926 (known as @dfn{kludges}) may enable you to write Bison parsers for such
6930 * Semantic Tokens:: Token parsing can depend on the semantic context.
6931 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
6932 * Tie-in Recovery:: Lexical tie-ins have implications for how
6933 error recovery rules must be written.
6936 (Actually, ``kludge'' means any technique that gets its job done but is
6937 neither clean nor robust.)
6939 @node Semantic Tokens
6940 @section Semantic Info in Token Types
6942 The C language has a context dependency: the way an identifier is used
6943 depends on what its current meaning is. For example, consider this:
6949 This looks like a function call statement, but if @code{foo} is a typedef
6950 name, then this is actually a declaration of @code{x}. How can a Bison
6951 parser for C decide how to parse this input?
6953 The method used in @acronym{GNU} C is to have two different token types,
6954 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
6955 identifier, it looks up the current declaration of the identifier in order
6956 to decide which token type to return: @code{TYPENAME} if the identifier is
6957 declared as a typedef, @code{IDENTIFIER} otherwise.
6959 The grammar rules can then express the context dependency by the choice of
6960 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
6961 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
6962 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
6963 is @emph{not} significant, such as in declarations that can shadow a
6964 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
6965 accepted---there is one rule for each of the two token types.
6967 This technique is simple to use if the decision of which kinds of
6968 identifiers to allow is made at a place close to where the identifier is
6969 parsed. But in C this is not always so: C allows a declaration to
6970 redeclare a typedef name provided an explicit type has been specified
6974 typedef int foo, bar;
6977 static bar (bar); /* @r{redeclare @code{bar} as static variable} */
6978 extern foo foo (foo); /* @r{redeclare @code{foo} as function} */
6983 Unfortunately, the name being declared is separated from the declaration
6984 construct itself by a complicated syntactic structure---the ``declarator''.
6986 As a result, part of the Bison parser for C needs to be duplicated, with
6987 all the nonterminal names changed: once for parsing a declaration in
6988 which a typedef name can be redefined, and once for parsing a
6989 declaration in which that can't be done. Here is a part of the
6990 duplication, with actions omitted for brevity:
6994 declarator maybeasm '='
6996 | declarator maybeasm
7000 notype_declarator maybeasm '='
7002 | notype_declarator maybeasm
7007 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
7008 cannot. The distinction between @code{declarator} and
7009 @code{notype_declarator} is the same sort of thing.
7011 There is some similarity between this technique and a lexical tie-in
7012 (described next), in that information which alters the lexical analysis is
7013 changed during parsing by other parts of the program. The difference is
7014 here the information is global, and is used for other purposes in the
7015 program. A true lexical tie-in has a special-purpose flag controlled by
7016 the syntactic context.
7018 @node Lexical Tie-ins
7019 @section Lexical Tie-ins
7020 @cindex lexical tie-in
7022 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
7023 which is set by Bison actions, whose purpose is to alter the way tokens are
7026 For example, suppose we have a language vaguely like C, but with a special
7027 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
7028 an expression in parentheses in which all integers are hexadecimal. In
7029 particular, the token @samp{a1b} must be treated as an integer rather than
7030 as an identifier if it appears in that context. Here is how you can do it:
7037 void yyerror (char const *);
7051 @{ $$ = make_sum ($1, $3); @}
7065 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
7066 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
7067 with letters are parsed as integers if possible.
7069 The declaration of @code{hexflag} shown in the prologue of the parser file
7070 is needed to make it accessible to the actions (@pxref{Prologue, ,The Prologue}).
7071 You must also write the code in @code{yylex} to obey the flag.
7073 @node Tie-in Recovery
7074 @section Lexical Tie-ins and Error Recovery
7076 Lexical tie-ins make strict demands on any error recovery rules you have.
7077 @xref{Error Recovery}.
7079 The reason for this is that the purpose of an error recovery rule is to
7080 abort the parsing of one construct and resume in some larger construct.
7081 For example, in C-like languages, a typical error recovery rule is to skip
7082 tokens until the next semicolon, and then start a new statement, like this:
7086 | IF '(' expr ')' stmt @{ @dots{} @}
7093 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
7094 construct, this error rule will apply, and then the action for the
7095 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
7096 remain set for the entire rest of the input, or until the next @code{hex}
7097 keyword, causing identifiers to be misinterpreted as integers.
7099 To avoid this problem the error recovery rule itself clears @code{hexflag}.
7101 There may also be an error recovery rule that works within expressions.
7102 For example, there could be a rule which applies within parentheses
7103 and skips to the close-parenthesis:
7115 If this rule acts within the @code{hex} construct, it is not going to abort
7116 that construct (since it applies to an inner level of parentheses within
7117 the construct). Therefore, it should not clear the flag: the rest of
7118 the @code{hex} construct should be parsed with the flag still in effect.
7120 What if there is an error recovery rule which might abort out of the
7121 @code{hex} construct or might not, depending on circumstances? There is no
7122 way you can write the action to determine whether a @code{hex} construct is
7123 being aborted or not. So if you are using a lexical tie-in, you had better
7124 make sure your error recovery rules are not of this kind. Each rule must
7125 be such that you can be sure that it always will, or always won't, have to
7128 @c ================================================== Debugging Your Parser
7131 @chapter Debugging Your Parser
7133 Developing a parser can be a challenge, especially if you don't
7134 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
7135 Algorithm}). Even so, sometimes a detailed description of the automaton
7136 can help (@pxref{Understanding, , Understanding Your Parser}), or
7137 tracing the execution of the parser can give some insight on why it
7138 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
7141 * Understanding:: Understanding the structure of your parser.
7142 * Tracing:: Tracing the execution of your parser.
7146 @section Understanding Your Parser
7148 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
7149 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
7150 frequent than one would hope), looking at this automaton is required to
7151 tune or simply fix a parser. Bison provides two different
7152 representation of it, either textually or graphically (as a DOT file).
7154 The textual file is generated when the options @option{--report} or
7155 @option{--verbose} are specified, see @xref{Invocation, , Invoking
7156 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
7157 the parser output file name, and adding @samp{.output} instead.
7158 Therefore, if the input file is @file{foo.y}, then the parser file is
7159 called @file{foo.tab.c} by default. As a consequence, the verbose
7160 output file is called @file{foo.output}.
7162 The following grammar file, @file{calc.y}, will be used in the sequel:
7179 @command{bison} reports:
7182 calc.y: warning: 1 nonterminal and 1 rule useless in grammar
7183 calc.y:11.1-7: warning: nonterminal useless in grammar: useless
7184 calc.y:11.10-12: warning: rule useless in grammar: useless: STR
7185 calc.y: conflicts: 7 shift/reduce
7188 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
7189 creates a file @file{calc.output} with contents detailed below. The
7190 order of the output and the exact presentation might vary, but the
7191 interpretation is the same.
7193 The first section includes details on conflicts that were solved thanks
7194 to precedence and/or associativity:
7197 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
7198 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
7199 Conflict in state 8 between rule 2 and token '*' resolved as shift.
7204 The next section lists states that still have conflicts.
7207 State 8 conflicts: 1 shift/reduce
7208 State 9 conflicts: 1 shift/reduce
7209 State 10 conflicts: 1 shift/reduce
7210 State 11 conflicts: 4 shift/reduce
7214 @cindex token, useless
7215 @cindex useless token
7216 @cindex nonterminal, useless
7217 @cindex useless nonterminal
7218 @cindex rule, useless
7219 @cindex useless rule
7220 The next section reports useless tokens, nonterminal and rules. Useless
7221 nonterminals and rules are removed in order to produce a smaller parser,
7222 but useless tokens are preserved, since they might be used by the
7223 scanner (note the difference between ``useless'' and ``unused''
7227 Nonterminals useless in grammar:
7230 Terminals unused in grammar:
7233 Rules useless in grammar:
7238 The next section reproduces the exact grammar that Bison used:
7244 0 5 $accept -> exp $end
7245 1 5 exp -> exp '+' exp
7246 2 6 exp -> exp '-' exp
7247 3 7 exp -> exp '*' exp
7248 4 8 exp -> exp '/' exp
7253 and reports the uses of the symbols:
7256 Terminals, with rules where they appear
7266 Nonterminals, with rules where they appear
7271 on left: 1 2 3 4 5, on right: 0 1 2 3 4
7276 @cindex pointed rule
7277 @cindex rule, pointed
7278 Bison then proceeds onto the automaton itself, describing each state
7279 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
7280 item is a production rule together with a point (marked by @samp{.})
7281 that the input cursor.
7286 $accept -> . exp $ (rule 0)
7288 NUM shift, and go to state 1
7293 This reads as follows: ``state 0 corresponds to being at the very
7294 beginning of the parsing, in the initial rule, right before the start
7295 symbol (here, @code{exp}). When the parser returns to this state right
7296 after having reduced a rule that produced an @code{exp}, the control
7297 flow jumps to state 2. If there is no such transition on a nonterminal
7298 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
7299 the parse stack, and the control flow jumps to state 1. Any other
7300 lookahead triggers a syntax error.''
7302 @cindex core, item set
7303 @cindex item set core
7304 @cindex kernel, item set
7305 @cindex item set core
7306 Even though the only active rule in state 0 seems to be rule 0, the
7307 report lists @code{NUM} as a lookahead token because @code{NUM} can be
7308 at the beginning of any rule deriving an @code{exp}. By default Bison
7309 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
7310 you want to see more detail you can invoke @command{bison} with
7311 @option{--report=itemset} to list all the items, include those that can
7317 $accept -> . exp $ (rule 0)
7318 exp -> . exp '+' exp (rule 1)
7319 exp -> . exp '-' exp (rule 2)
7320 exp -> . exp '*' exp (rule 3)
7321 exp -> . exp '/' exp (rule 4)
7322 exp -> . NUM (rule 5)
7324 NUM shift, and go to state 1
7335 exp -> NUM . (rule 5)
7337 $default reduce using rule 5 (exp)
7341 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead token
7342 (@samp{$default}), the parser will reduce it. If it was coming from
7343 state 0, then, after this reduction it will return to state 0, and will
7344 jump to state 2 (@samp{exp: go to state 2}).
7349 $accept -> exp . $ (rule 0)
7350 exp -> exp . '+' exp (rule 1)
7351 exp -> exp . '-' exp (rule 2)
7352 exp -> exp . '*' exp (rule 3)
7353 exp -> exp . '/' exp (rule 4)
7355 $ shift, and go to state 3
7356 '+' shift, and go to state 4
7357 '-' shift, and go to state 5
7358 '*' shift, and go to state 6
7359 '/' shift, and go to state 7
7363 In state 2, the automaton can only shift a symbol. For instance,
7364 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
7365 @samp{+}, it will be shifted on the parse stack, and the automaton
7366 control will jump to state 4, corresponding to the item @samp{exp -> exp
7367 '+' . exp}. Since there is no default action, any other token than
7368 those listed above will trigger a syntax error.
7370 The state 3 is named the @dfn{final state}, or the @dfn{accepting
7376 $accept -> exp $ . (rule 0)
7382 the initial rule is completed (the start symbol and the end
7383 of input were read), the parsing exits successfully.
7385 The interpretation of states 4 to 7 is straightforward, and is left to
7391 exp -> exp '+' . exp (rule 1)
7393 NUM shift, and go to state 1
7399 exp -> exp '-' . exp (rule 2)
7401 NUM shift, and go to state 1
7407 exp -> exp '*' . exp (rule 3)
7409 NUM shift, and go to state 1
7415 exp -> exp '/' . exp (rule 4)
7417 NUM shift, and go to state 1
7422 As was announced in beginning of the report, @samp{State 8 conflicts:
7428 exp -> exp . '+' exp (rule 1)
7429 exp -> exp '+' exp . (rule 1)
7430 exp -> exp . '-' exp (rule 2)
7431 exp -> exp . '*' exp (rule 3)
7432 exp -> exp . '/' exp (rule 4)
7434 '*' shift, and go to state 6
7435 '/' shift, and go to state 7
7437 '/' [reduce using rule 1 (exp)]
7438 $default reduce using rule 1 (exp)
7441 Indeed, there are two actions associated to the lookahead @samp{/}:
7442 either shifting (and going to state 7), or reducing rule 1. The
7443 conflict means that either the grammar is ambiguous, or the parser lacks
7444 information to make the right decision. Indeed the grammar is
7445 ambiguous, as, since we did not specify the precedence of @samp{/}, the
7446 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
7447 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
7448 NUM}, which corresponds to reducing rule 1.
7450 Because in @acronym{LALR}(1) parsing a single decision can be made, Bison
7451 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
7452 Shift/Reduce Conflicts}. Discarded actions are reported in between
7455 Note that all the previous states had a single possible action: either
7456 shifting the next token and going to the corresponding state, or
7457 reducing a single rule. In the other cases, i.e., when shifting
7458 @emph{and} reducing is possible or when @emph{several} reductions are
7459 possible, the lookahead is required to select the action. State 8 is
7460 one such state: if the lookahead is @samp{*} or @samp{/} then the action
7461 is shifting, otherwise the action is reducing rule 1. In other words,
7462 the first two items, corresponding to rule 1, are not eligible when the
7463 lookahead token is @samp{*}, since we specified that @samp{*} has higher
7464 precedence than @samp{+}. More generally, some items are eligible only
7465 with some set of possible lookahead tokens. When run with
7466 @option{--report=lookahead}, Bison specifies these lookahead tokens:
7471 exp -> exp . '+' exp (rule 1)
7472 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
7473 exp -> exp . '-' exp (rule 2)
7474 exp -> exp . '*' exp (rule 3)
7475 exp -> exp . '/' exp (rule 4)
7477 '*' shift, and go to state 6
7478 '/' shift, and go to state 7
7480 '/' [reduce using rule 1 (exp)]
7481 $default reduce using rule 1 (exp)
7484 The remaining states are similar:
7489 exp -> exp . '+' exp (rule 1)
7490 exp -> exp . '-' exp (rule 2)
7491 exp -> exp '-' exp . (rule 2)
7492 exp -> exp . '*' exp (rule 3)
7493 exp -> exp . '/' exp (rule 4)
7495 '*' shift, and go to state 6
7496 '/' shift, and go to state 7
7498 '/' [reduce using rule 2 (exp)]
7499 $default reduce using rule 2 (exp)
7503 exp -> exp . '+' exp (rule 1)
7504 exp -> exp . '-' exp (rule 2)
7505 exp -> exp . '*' exp (rule 3)
7506 exp -> exp '*' exp . (rule 3)
7507 exp -> exp . '/' exp (rule 4)
7509 '/' shift, and go to state 7
7511 '/' [reduce using rule 3 (exp)]
7512 $default reduce using rule 3 (exp)
7516 exp -> exp . '+' exp (rule 1)
7517 exp -> exp . '-' exp (rule 2)
7518 exp -> exp . '*' exp (rule 3)
7519 exp -> exp . '/' exp (rule 4)
7520 exp -> exp '/' exp . (rule 4)
7522 '+' shift, and go to state 4
7523 '-' shift, and go to state 5
7524 '*' shift, and go to state 6
7525 '/' shift, and go to state 7
7527 '+' [reduce using rule 4 (exp)]
7528 '-' [reduce using rule 4 (exp)]
7529 '*' [reduce using rule 4 (exp)]
7530 '/' [reduce using rule 4 (exp)]
7531 $default reduce using rule 4 (exp)
7535 Observe that state 11 contains conflicts not only due to the lack of
7536 precedence of @samp{/} with respect to @samp{+}, @samp{-}, and
7537 @samp{*}, but also because the
7538 associativity of @samp{/} is not specified.
7542 @section Tracing Your Parser
7545 @cindex tracing the parser
7547 If a Bison grammar compiles properly but doesn't do what you want when it
7548 runs, the @code{yydebug} parser-trace feature can help you figure out why.
7550 There are several means to enable compilation of trace facilities:
7553 @item the macro @code{YYDEBUG}
7555 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
7556 parser. This is compliant with @acronym{POSIX} Yacc. You could use
7557 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
7558 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
7561 @item the option @option{-t}, @option{--debug}
7562 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
7563 ,Invoking Bison}). This is @acronym{POSIX} compliant too.
7565 @item the directive @samp{%debug}
7567 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison
7568 Declaration Summary}). This is a Bison extension, which will prove
7569 useful when Bison will output parsers for languages that don't use a
7570 preprocessor. Unless @acronym{POSIX} and Yacc portability matter to
7572 the preferred solution.
7575 We suggest that you always enable the debug option so that debugging is
7578 The trace facility outputs messages with macro calls of the form
7579 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
7580 @var{format} and @var{args} are the usual @code{printf} format and variadic
7581 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
7582 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
7583 and @code{YYFPRINTF} is defined to @code{fprintf}.
7585 Once you have compiled the program with trace facilities, the way to
7586 request a trace is to store a nonzero value in the variable @code{yydebug}.
7587 You can do this by making the C code do it (in @code{main}, perhaps), or
7588 you can alter the value with a C debugger.
7590 Each step taken by the parser when @code{yydebug} is nonzero produces a
7591 line or two of trace information, written on @code{stderr}. The trace
7592 messages tell you these things:
7596 Each time the parser calls @code{yylex}, what kind of token was read.
7599 Each time a token is shifted, the depth and complete contents of the
7600 state stack (@pxref{Parser States}).
7603 Each time a rule is reduced, which rule it is, and the complete contents
7604 of the state stack afterward.
7607 To make sense of this information, it helps to refer to the listing file
7608 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
7609 Bison}). This file shows the meaning of each state in terms of
7610 positions in various rules, and also what each state will do with each
7611 possible input token. As you read the successive trace messages, you
7612 can see that the parser is functioning according to its specification in
7613 the listing file. Eventually you will arrive at the place where
7614 something undesirable happens, and you will see which parts of the
7615 grammar are to blame.
7617 The parser file is a C program and you can use C debuggers on it, but it's
7618 not easy to interpret what it is doing. The parser function is a
7619 finite-state machine interpreter, and aside from the actions it executes
7620 the same code over and over. Only the values of variables show where in
7621 the grammar it is working.
7624 The debugging information normally gives the token type of each token
7625 read, but not its semantic value. You can optionally define a macro
7626 named @code{YYPRINT} to provide a way to print the value. If you define
7627 @code{YYPRINT}, it should take three arguments. The parser will pass a
7628 standard I/O stream, the numeric code for the token type, and the token
7629 value (from @code{yylval}).
7631 Here is an example of @code{YYPRINT} suitable for the multi-function
7632 calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
7636 static void print_token_value (FILE *, int, YYSTYPE);
7637 #define YYPRINT(file, type, value) print_token_value (file, type, value)
7640 @dots{} %% @dots{} %% @dots{}
7643 print_token_value (FILE *file, int type, YYSTYPE value)
7646 fprintf (file, "%s", value.tptr->name);
7647 else if (type == NUM)
7648 fprintf (file, "%d", value.val);
7652 @c ================================================= Invoking Bison
7655 @chapter Invoking Bison
7656 @cindex invoking Bison
7657 @cindex Bison invocation
7658 @cindex options for invoking Bison
7660 The usual way to invoke Bison is as follows:
7666 Here @var{infile} is the grammar file name, which usually ends in
7667 @samp{.y}. The parser file's name is made by replacing the @samp{.y}
7668 with @samp{.tab.c} and removing any leading directory. Thus, the
7669 @samp{bison foo.y} file name yields
7670 @file{foo.tab.c}, and the @samp{bison hack/foo.y} file name yields
7671 @file{foo.tab.c}. It's also possible, in case you are writing
7672 C++ code instead of C in your grammar file, to name it @file{foo.ypp}
7673 or @file{foo.y++}. Then, the output files will take an extension like
7674 the given one as input (respectively @file{foo.tab.cpp} and
7675 @file{foo.tab.c++}).
7676 This feature takes effect with all options that manipulate file names like
7677 @samp{-o} or @samp{-d}.
7682 bison -d @var{infile.yxx}
7685 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
7688 bison -d -o @var{output.c++} @var{infile.y}
7691 will produce @file{output.c++} and @file{outfile.h++}.
7693 For compatibility with @acronym{POSIX}, the standard Bison
7694 distribution also contains a shell script called @command{yacc} that
7695 invokes Bison with the @option{-y} option.
7698 * Bison Options:: All the options described in detail,
7699 in alphabetical order by short options.
7700 * Option Cross Key:: Alphabetical list of long options.
7701 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
7705 @section Bison Options
7707 Bison supports both traditional single-letter options and mnemonic long
7708 option names. Long option names are indicated with @samp{--} instead of
7709 @samp{-}. Abbreviations for option names are allowed as long as they
7710 are unique. When a long option takes an argument, like
7711 @samp{--file-prefix}, connect the option name and the argument with
7714 Here is a list of options that can be used with Bison, alphabetized by
7715 short option. It is followed by a cross key alphabetized by long
7718 @c Please, keep this ordered as in `bison --help'.
7724 Print a summary of the command-line options to Bison and exit.
7728 Print the version number of Bison and exit.
7730 @item --print-localedir
7731 Print the name of the directory containing locale-dependent data.
7733 @item --print-datadir
7734 Print the name of the directory containing skeletons and XSLT.
7738 Act more like the traditional Yacc command. This can cause
7739 different diagnostics to be generated, and may change behavior in
7740 other minor ways. Most importantly, imitate Yacc's output
7741 file name conventions, so that the parser output file is called
7742 @file{y.tab.c}, and the other outputs are called @file{y.output} and
7744 Also, if generating an @acronym{LALR}(1) parser in C, generate @code{#define}
7745 statements in addition to an @code{enum} to associate token numbers with token
7747 Thus, the following shell script can substitute for Yacc, and the Bison
7748 distribution contains such a script for compatibility with @acronym{POSIX}:
7755 The @option{-y}/@option{--yacc} option is intended for use with
7756 traditional Yacc grammars. If your grammar uses a Bison extension
7757 like @samp{%glr-parser}, Bison might not be Yacc-compatible even if
7758 this option is specified.
7768 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
7769 already defined, so that the debugging facilities are compiled.
7770 @xref{Tracing, ,Tracing Your Parser}.
7772 @item -L @var{language}
7773 @itemx --language=@var{language}
7774 Specify the programming language for the generated parser, as if
7775 @code{%language} was specified (@pxref{Decl Summary, , Bison Declaration
7776 Summary}). Currently supported languages include C and C++.
7777 @var{language} is case-insensitive.
7780 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
7782 @item -p @var{prefix}
7783 @itemx --name-prefix=@var{prefix}
7784 Pretend that @code{%name-prefix "@var{prefix}"} was specified.
7785 @xref{Decl Summary}.
7789 Don't put any @code{#line} preprocessor commands in the parser file.
7790 Ordinarily Bison puts them in the parser file so that the C compiler
7791 and debuggers will associate errors with your source file, the
7792 grammar file. This option causes them to associate errors with the
7793 parser file, treating it as an independent source file in its own right.
7796 @itemx --skeleton=@var{file}
7797 Specify the skeleton to use, similar to @code{%skeleton}
7798 (@pxref{Decl Summary, , Bison Declaration Summary}).
7800 You probably don't need this option unless you are developing Bison.
7801 You should use @option{--language} if you want to specify the skeleton for a
7802 different language, because it is clearer and because it will always
7803 choose the correct skeleton for non-deterministic or push parsers.
7805 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
7806 file in the Bison installation directory.
7807 If it does, @var{file} is an absolute file name or a file name relative to the
7808 current working directory.
7809 This is similar to how most shells resolve commands.
7812 @itemx --token-table
7813 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
7822 Pretend that @code{%defines} was specified, i.e., write an extra output
7823 file containing macro definitions for the token type names defined in
7824 the grammar, as well as a few other declarations. @xref{Decl Summary}.
7826 @item --defines=@var{defines-file}
7827 Same as above, but save in the file @var{defines-file}.
7829 @item -b @var{file-prefix}
7830 @itemx --file-prefix=@var{prefix}
7831 Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
7832 for all Bison output file names. @xref{Decl Summary}.
7834 @item -r @var{things}
7835 @itemx --report=@var{things}
7836 Write an extra output file containing verbose description of the comma
7837 separated list of @var{things} among:
7841 Description of the grammar, conflicts (resolved and unresolved), and
7842 @acronym{LALR} automaton.
7845 Implies @code{state} and augments the description of the automaton with
7846 each rule's lookahead set.
7849 Implies @code{state} and augments the description of the automaton with
7850 the full set of items for each state, instead of its core only.
7853 @item --report-file=@var{file}
7854 Specify the @var{file} for the verbose description.
7858 Pretend that @code{%verbose} was specified, i.e., write an extra output
7859 file containing verbose descriptions of the grammar and
7860 parser. @xref{Decl Summary}.
7863 @itemx --output=@var{file}
7864 Specify the @var{file} for the parser file.
7866 The other output files' names are constructed from @var{file} as
7867 described under the @samp{-v} and @samp{-d} options.
7870 Output a graphical representation of the @acronym{LALR}(1) grammar
7871 automaton computed by Bison, in @uref{http://www.graphviz.org/, Graphviz}
7872 @uref{http://www.graphviz.org/doc/info/lang.html, @acronym{DOT}} format.
7873 If the grammar file is @file{foo.y}, the output file will
7876 @item --graph=@var{graph-file}
7877 The behavior of @var{--graph} is the same than @samp{-g}. The only
7878 difference is that it has an optional argument which is the name of
7879 the output graph file.
7882 @node Option Cross Key
7883 @section Option Cross Key
7885 @c FIXME: How about putting the directives too?
7886 Here is a list of options, alphabetized by long option, to help you find
7887 the corresponding short option.
7889 @multitable {@option{--defines=@var{defines-file}}} {@option{-b @var{file-prefix}XXX}}
7890 @headitem Long Option @tab Short Option
7891 @include cross-options.texi
7895 @section Yacc Library
7897 The Yacc library contains default implementations of the
7898 @code{yyerror} and @code{main} functions. These default
7899 implementations are normally not useful, but @acronym{POSIX} requires
7900 them. To use the Yacc library, link your program with the
7901 @option{-ly} option. Note that Bison's implementation of the Yacc
7902 library is distributed under the terms of the @acronym{GNU} General
7903 Public License (@pxref{Copying}).
7905 If you use the Yacc library's @code{yyerror} function, you should
7906 declare @code{yyerror} as follows:
7909 int yyerror (char const *);
7912 Bison ignores the @code{int} value returned by this @code{yyerror}.
7913 If you use the Yacc library's @code{main} function, your
7914 @code{yyparse} function should have the following type signature:
7920 @c ================================================= C++ Bison
7922 @node Other Languages
7923 @chapter Parsers Written In Other Languages
7926 * C++ Parsers:: The interface to generate C++ parser classes
7927 * Java Parsers:: The interface to generate Java parser classes
7931 @section C++ Parsers
7934 * C++ Bison Interface:: Asking for C++ parser generation
7935 * C++ Semantic Values:: %union vs. C++
7936 * C++ Location Values:: The position and location classes
7937 * C++ Parser Interface:: Instantiating and running the parser
7938 * C++ Scanner Interface:: Exchanges between yylex and parse
7939 * A Complete C++ Example:: Demonstrating their use
7942 @node C++ Bison Interface
7943 @subsection C++ Bison Interface
7944 @c - %language "C++"
7948 The C++ @acronym{LALR}(1) parser is selected using the language directive,
7949 @samp{%language "C++"}, or the synonymous command-line option
7950 @option{--language=c++}.
7951 @xref{Decl Summary}.
7953 When run, @command{bison} will create several entities in the @samp{yy}
7955 @findex %define namespace
7956 Use the @samp{%define namespace} directive to change the namespace name, see
7958 The various classes are generated in the following files:
7963 The definition of the classes @code{position} and @code{location},
7964 used for location tracking. @xref{C++ Location Values}.
7967 An auxiliary class @code{stack} used by the parser.
7970 @itemx @var{file}.cc
7971 (Assuming the extension of the input file was @samp{.yy}.) The
7972 declaration and implementation of the C++ parser class. The basename
7973 and extension of these two files follow the same rules as with regular C
7974 parsers (@pxref{Invocation}).
7976 The header is @emph{mandatory}; you must either pass
7977 @option{-d}/@option{--defines} to @command{bison}, or use the
7978 @samp{%defines} directive.
7981 All these files are documented using Doxygen; run @command{doxygen}
7982 for a complete and accurate documentation.
7984 @node C++ Semantic Values
7985 @subsection C++ Semantic Values
7986 @c - No objects in unions
7988 @c - Printer and destructor
7990 The @code{%union} directive works as for C, see @ref{Union Decl, ,The
7991 Collection of Value Types}. In particular it produces a genuine
7992 @code{union}@footnote{In the future techniques to allow complex types
7993 within pseudo-unions (similar to Boost variants) might be implemented to
7994 alleviate these issues.}, which have a few specific features in C++.
7997 The type @code{YYSTYPE} is defined but its use is discouraged: rather
7998 you should refer to the parser's encapsulated type
7999 @code{yy::parser::semantic_type}.
8001 Non POD (Plain Old Data) types cannot be used. C++ forbids any
8002 instance of classes with constructors in unions: only @emph{pointers}
8003 to such objects are allowed.
8006 Because objects have to be stored via pointers, memory is not
8007 reclaimed automatically: using the @code{%destructor} directive is the
8008 only means to avoid leaks. @xref{Destructor Decl, , Freeing Discarded
8012 @node C++ Location Values
8013 @subsection C++ Location Values
8017 @c - %define filename_type "const symbol::Symbol"
8019 When the directive @code{%locations} is used, the C++ parser supports
8020 location tracking, see @ref{Locations, , Locations Overview}. Two
8021 auxiliary classes define a @code{position}, a single point in a file,
8022 and a @code{location}, a range composed of a pair of
8023 @code{position}s (possibly spanning several files).
8025 @deftypemethod {position} {std::string*} file
8026 The name of the file. It will always be handled as a pointer, the
8027 parser will never duplicate nor deallocate it. As an experimental
8028 feature you may change it to @samp{@var{type}*} using @samp{%define
8029 filename_type "@var{type}"}.
8032 @deftypemethod {position} {unsigned int} line
8033 The line, starting at 1.
8036 @deftypemethod {position} {unsigned int} lines (int @var{height} = 1)
8037 Advance by @var{height} lines, resetting the column number.
8040 @deftypemethod {position} {unsigned int} column
8041 The column, starting at 0.
8044 @deftypemethod {position} {unsigned int} columns (int @var{width} = 1)
8045 Advance by @var{width} columns, without changing the line number.
8048 @deftypemethod {position} {position&} operator+= (position& @var{pos}, int @var{width})
8049 @deftypemethodx {position} {position} operator+ (const position& @var{pos}, int @var{width})
8050 @deftypemethodx {position} {position&} operator-= (const position& @var{pos}, int @var{width})
8051 @deftypemethodx {position} {position} operator- (position& @var{pos}, int @var{width})
8052 Various forms of syntactic sugar for @code{columns}.
8055 @deftypemethod {position} {position} operator<< (std::ostream @var{o}, const position& @var{p})
8056 Report @var{p} on @var{o} like this:
8057 @samp{@var{file}:@var{line}.@var{column}}, or
8058 @samp{@var{line}.@var{column}} if @var{file} is null.
8061 @deftypemethod {location} {position} begin
8062 @deftypemethodx {location} {position} end
8063 The first, inclusive, position of the range, and the first beyond.
8066 @deftypemethod {location} {unsigned int} columns (int @var{width} = 1)
8067 @deftypemethodx {location} {unsigned int} lines (int @var{height} = 1)
8068 Advance the @code{end} position.
8071 @deftypemethod {location} {location} operator+ (const location& @var{begin}, const location& @var{end})
8072 @deftypemethodx {location} {location} operator+ (const location& @var{begin}, int @var{width})
8073 @deftypemethodx {location} {location} operator+= (const location& @var{loc}, int @var{width})
8074 Various forms of syntactic sugar.
8077 @deftypemethod {location} {void} step ()
8078 Move @code{begin} onto @code{end}.
8082 @node C++ Parser Interface
8083 @subsection C++ Parser Interface
8084 @c - define parser_class_name
8086 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
8088 @c - Reporting errors
8090 The output files @file{@var{output}.hh} and @file{@var{output}.cc}
8091 declare and define the parser class in the namespace @code{yy}. The
8092 class name defaults to @code{parser}, but may be changed using
8093 @samp{%define parser_class_name "@var{name}"}. The interface of
8094 this class is detailed below. It can be extended using the
8095 @code{%parse-param} feature: its semantics is slightly changed since
8096 it describes an additional member of the parser class, and an
8097 additional argument for its constructor.
8099 @defcv {Type} {parser} {semantic_value_type}
8100 @defcvx {Type} {parser} {location_value_type}
8101 The types for semantics value and locations.
8104 @deftypemethod {parser} {} parser (@var{type1} @var{arg1}, ...)
8105 Build a new parser object. There are no arguments by default, unless
8106 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
8109 @deftypemethod {parser} {int} parse ()
8110 Run the syntactic analysis, and return 0 on success, 1 otherwise.
8113 @deftypemethod {parser} {std::ostream&} debug_stream ()
8114 @deftypemethodx {parser} {void} set_debug_stream (std::ostream& @var{o})
8115 Get or set the stream used for tracing the parsing. It defaults to
8119 @deftypemethod {parser} {debug_level_type} debug_level ()
8120 @deftypemethodx {parser} {void} set_debug_level (debug_level @var{l})
8121 Get or set the tracing level. Currently its value is either 0, no trace,
8122 or nonzero, full tracing.
8125 @deftypemethod {parser} {void} error (const location_type& @var{l}, const std::string& @var{m})
8126 The definition for this member function must be supplied by the user:
8127 the parser uses it to report a parser error occurring at @var{l},
8128 described by @var{m}.
8132 @node C++ Scanner Interface
8133 @subsection C++ Scanner Interface
8134 @c - prefix for yylex.
8135 @c - Pure interface to yylex
8138 The parser invokes the scanner by calling @code{yylex}. Contrary to C
8139 parsers, C++ parsers are always pure: there is no point in using the
8140 @code{%define api.pure} directive. Therefore the interface is as follows.
8142 @deftypemethod {parser} {int} yylex (semantic_value_type& @var{yylval}, location_type& @var{yylloc}, @var{type1} @var{arg1}, ...)
8143 Return the next token. Its type is the return value, its semantic
8144 value and location being @var{yylval} and @var{yylloc}. Invocations of
8145 @samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
8149 @node A Complete C++ Example
8150 @subsection A Complete C++ Example
8152 This section demonstrates the use of a C++ parser with a simple but
8153 complete example. This example should be available on your system,
8154 ready to compile, in the directory @dfn{../bison/examples/calc++}. It
8155 focuses on the use of Bison, therefore the design of the various C++
8156 classes is very naive: no accessors, no encapsulation of members etc.
8157 We will use a Lex scanner, and more precisely, a Flex scanner, to
8158 demonstrate the various interaction. A hand written scanner is
8159 actually easier to interface with.
8162 * Calc++ --- C++ Calculator:: The specifications
8163 * Calc++ Parsing Driver:: An active parsing context
8164 * Calc++ Parser:: A parser class
8165 * Calc++ Scanner:: A pure C++ Flex scanner
8166 * Calc++ Top Level:: Conducting the band
8169 @node Calc++ --- C++ Calculator
8170 @subsubsection Calc++ --- C++ Calculator
8172 Of course the grammar is dedicated to arithmetics, a single
8173 expression, possibly preceded by variable assignments. An
8174 environment containing possibly predefined variables such as
8175 @code{one} and @code{two}, is exchanged with the parser. An example
8176 of valid input follows.
8180 seven := one + two * three
8184 @node Calc++ Parsing Driver
8185 @subsubsection Calc++ Parsing Driver
8187 @c - A place to store error messages
8188 @c - A place for the result
8190 To support a pure interface with the parser (and the scanner) the
8191 technique of the ``parsing context'' is convenient: a structure
8192 containing all the data to exchange. Since, in addition to simply
8193 launch the parsing, there are several auxiliary tasks to execute (open
8194 the file for parsing, instantiate the parser etc.), we recommend
8195 transforming the simple parsing context structure into a fully blown
8196 @dfn{parsing driver} class.
8198 The declaration of this driver class, @file{calc++-driver.hh}, is as
8199 follows. The first part includes the CPP guard and imports the
8200 required standard library components, and the declaration of the parser
8203 @comment file: calc++-driver.hh
8205 #ifndef CALCXX_DRIVER_HH
8206 # define CALCXX_DRIVER_HH
8209 # include "calc++-parser.hh"
8214 Then comes the declaration of the scanning function. Flex expects
8215 the signature of @code{yylex} to be defined in the macro
8216 @code{YY_DECL}, and the C++ parser expects it to be declared. We can
8217 factor both as follows.
8219 @comment file: calc++-driver.hh
8221 // Tell Flex the lexer's prototype ...
8223 yy::calcxx_parser::token_type \
8224 yylex (yy::calcxx_parser::semantic_type* yylval, \
8225 yy::calcxx_parser::location_type* yylloc, \
8226 calcxx_driver& driver)
8227 // ... and declare it for the parser's sake.
8232 The @code{calcxx_driver} class is then declared with its most obvious
8235 @comment file: calc++-driver.hh
8237 // Conducting the whole scanning and parsing of Calc++.
8242 virtual ~calcxx_driver ();
8244 std::map<std::string, int> variables;
8250 To encapsulate the coordination with the Flex scanner, it is useful to
8251 have two members function to open and close the scanning phase.
8253 @comment file: calc++-driver.hh
8255 // Handling the scanner.
8258 bool trace_scanning;
8262 Similarly for the parser itself.
8264 @comment file: calc++-driver.hh
8266 // Run the parser. Return 0 on success.
8267 int parse (const std::string& f);
8273 To demonstrate pure handling of parse errors, instead of simply
8274 dumping them on the standard error output, we will pass them to the
8275 compiler driver using the following two member functions. Finally, we
8276 close the class declaration and CPP guard.
8278 @comment file: calc++-driver.hh
8281 void error (const yy::location& l, const std::string& m);
8282 void error (const std::string& m);
8284 #endif // ! CALCXX_DRIVER_HH
8287 The implementation of the driver is straightforward. The @code{parse}
8288 member function deserves some attention. The @code{error} functions
8289 are simple stubs, they should actually register the located error
8290 messages and set error state.
8292 @comment file: calc++-driver.cc
8294 #include "calc++-driver.hh"
8295 #include "calc++-parser.hh"
8297 calcxx_driver::calcxx_driver ()
8298 : trace_scanning (false), trace_parsing (false)
8300 variables["one"] = 1;
8301 variables["two"] = 2;
8304 calcxx_driver::~calcxx_driver ()
8309 calcxx_driver::parse (const std::string &f)
8313 yy::calcxx_parser parser (*this);
8314 parser.set_debug_level (trace_parsing);
8315 int res = parser.parse ();
8321 calcxx_driver::error (const yy::location& l, const std::string& m)
8323 std::cerr << l << ": " << m << std::endl;
8327 calcxx_driver::error (const std::string& m)
8329 std::cerr << m << std::endl;
8334 @subsubsection Calc++ Parser
8336 The parser definition file @file{calc++-parser.yy} starts by asking for
8337 the C++ LALR(1) skeleton, the creation of the parser header file, and
8338 specifies the name of the parser class. Because the C++ skeleton
8339 changed several times, it is safer to require the version you designed
8342 @comment file: calc++-parser.yy
8344 %language "C++" /* -*- C++ -*- */
8345 %require "@value{VERSION}"
8347 %define parser_class_name "calcxx_parser"
8351 @findex %code requires
8352 Then come the declarations/inclusions needed to define the
8353 @code{%union}. Because the parser uses the parsing driver and
8354 reciprocally, both cannot include the header of the other. Because the
8355 driver's header needs detailed knowledge about the parser class (in
8356 particular its inner types), it is the parser's header which will simply
8357 use a forward declaration of the driver.
8358 @xref{Decl Summary, ,%code}.
8360 @comment file: calc++-parser.yy
8364 class calcxx_driver;
8369 The driver is passed by reference to the parser and to the scanner.
8370 This provides a simple but effective pure interface, not relying on
8373 @comment file: calc++-parser.yy
8375 // The parsing context.
8376 %parse-param @{ calcxx_driver& driver @}
8377 %lex-param @{ calcxx_driver& driver @}
8381 Then we request the location tracking feature, and initialize the
8382 first location's file name. Afterwards new locations are computed
8383 relatively to the previous locations: the file name will be
8384 automatically propagated.
8386 @comment file: calc++-parser.yy
8391 // Initialize the initial location.
8392 @@$.begin.filename = @@$.end.filename = &driver.file;
8397 Use the two following directives to enable parser tracing and verbose
8400 @comment file: calc++-parser.yy
8407 Semantic values cannot use ``real'' objects, but only pointers to
8410 @comment file: calc++-parser.yy
8422 The code between @samp{%code @{} and @samp{@}} is output in the
8423 @file{*.cc} file; it needs detailed knowledge about the driver.
8425 @comment file: calc++-parser.yy
8428 # include "calc++-driver.hh"
8434 The token numbered as 0 corresponds to end of file; the following line
8435 allows for nicer error messages referring to ``end of file'' instead
8436 of ``$end''. Similarly user friendly named are provided for each
8437 symbol. Note that the tokens names are prefixed by @code{TOKEN_} to
8440 @comment file: calc++-parser.yy
8442 %token END 0 "end of file"
8444 %token <sval> IDENTIFIER "identifier"
8445 %token <ival> NUMBER "number"
8450 To enable memory deallocation during error recovery, use
8453 @c FIXME: Document %printer, and mention that it takes a braced-code operand.
8454 @comment file: calc++-parser.yy
8456 %printer @{ debug_stream () << *$$; @} "identifier"
8457 %destructor @{ delete $$; @} "identifier"
8459 %printer @{ debug_stream () << $$; @} <ival>
8463 The grammar itself is straightforward.
8465 @comment file: calc++-parser.yy
8469 unit: assignments exp @{ driver.result = $2; @};
8471 assignments: assignments assignment @{@}
8472 | /* Nothing. */ @{@};
8475 "identifier" ":=" exp
8476 @{ driver.variables[*$1] = $3; delete $1; @};
8480 exp: exp '+' exp @{ $$ = $1 + $3; @}
8481 | exp '-' exp @{ $$ = $1 - $3; @}
8482 | exp '*' exp @{ $$ = $1 * $3; @}
8483 | exp '/' exp @{ $$ = $1 / $3; @}
8484 | "identifier" @{ $$ = driver.variables[*$1]; delete $1; @}
8485 | "number" @{ $$ = $1; @};
8490 Finally the @code{error} member function registers the errors to the
8493 @comment file: calc++-parser.yy
8496 yy::calcxx_parser::error (const yy::calcxx_parser::location_type& l,
8497 const std::string& m)
8499 driver.error (l, m);
8503 @node Calc++ Scanner
8504 @subsubsection Calc++ Scanner
8506 The Flex scanner first includes the driver declaration, then the
8507 parser's to get the set of defined tokens.
8509 @comment file: calc++-scanner.ll
8511 %@{ /* -*- C++ -*- */
8514 # include <limits.h>
8516 # include "calc++-driver.hh"
8517 # include "calc++-parser.hh"
8519 /* Work around an incompatibility in flex (at least versions
8520 2.5.31 through 2.5.33): it generates code that does
8521 not conform to C89. See Debian bug 333231
8522 <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>. */
8526 /* By default yylex returns int, we use token_type.
8527 Unfortunately yyterminate by default returns 0, which is
8528 not of token_type. */
8529 #define yyterminate() return token::END
8534 Because there is no @code{#include}-like feature we don't need
8535 @code{yywrap}, we don't need @code{unput} either, and we parse an
8536 actual file, this is not an interactive session with the user.
8537 Finally we enable the scanner tracing features.
8539 @comment file: calc++-scanner.ll
8541 %option noyywrap nounput batch debug
8545 Abbreviations allow for more readable rules.
8547 @comment file: calc++-scanner.ll
8549 id [a-zA-Z][a-zA-Z_0-9]*
8555 The following paragraph suffices to track locations accurately. Each
8556 time @code{yylex} is invoked, the begin position is moved onto the end
8557 position. Then when a pattern is matched, the end position is
8558 advanced of its width. In case it matched ends of lines, the end
8559 cursor is adjusted, and each time blanks are matched, the begin cursor
8560 is moved onto the end cursor to effectively ignore the blanks
8561 preceding tokens. Comments would be treated equally.
8563 @comment file: calc++-scanner.ll
8566 # define YY_USER_ACTION yylloc->columns (yyleng);
8572 @{blank@}+ yylloc->step ();
8573 [\n]+ yylloc->lines (yyleng); yylloc->step ();
8577 The rules are simple, just note the use of the driver to report errors.
8578 It is convenient to use a typedef to shorten
8579 @code{yy::calcxx_parser::token::identifier} into
8580 @code{token::identifier} for instance.
8582 @comment file: calc++-scanner.ll
8585 typedef yy::calcxx_parser::token token;
8587 /* Convert ints to the actual type of tokens. */
8588 [-+*/] return yy::calcxx_parser::token_type (yytext[0]);
8589 ":=" return token::ASSIGN;
8592 long n = strtol (yytext, NULL, 10);
8593 if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
8594 driver.error (*yylloc, "integer is out of range");
8596 return token::NUMBER;
8598 @{id@} yylval->sval = new std::string (yytext); return token::IDENTIFIER;
8599 . driver.error (*yylloc, "invalid character");
8604 Finally, because the scanner related driver's member function depend
8605 on the scanner's data, it is simpler to implement them in this file.
8607 @comment file: calc++-scanner.ll
8610 calcxx_driver::scan_begin ()
8612 yy_flex_debug = trace_scanning;
8615 else if (!(yyin = fopen (file.c_str (), "r")))
8617 error (std::string ("cannot open ") + file);
8623 calcxx_driver::scan_end ()
8629 @node Calc++ Top Level
8630 @subsubsection Calc++ Top Level
8632 The top level file, @file{calc++.cc}, poses no problem.
8634 @comment file: calc++.cc
8637 #include "calc++-driver.hh"
8640 main (int argc, char *argv[])
8642 calcxx_driver driver;
8643 for (++argv; argv[0]; ++argv)
8644 if (*argv == std::string ("-p"))
8645 driver.trace_parsing = true;
8646 else if (*argv == std::string ("-s"))
8647 driver.trace_scanning = true;
8648 else if (!driver.parse (*argv))
8649 std::cout << driver.result << std::endl;
8654 @section Java Parsers
8657 * Java Bison Interface:: Asking for Java parser generation
8658 * Java Semantic Values:: %type and %token vs. Java
8659 * Java Location Values:: The position and location classes
8660 * Java Parser Interface:: Instantiating and running the parser
8661 * Java Scanner Interface:: Java scanners, and pure parsers
8662 * Java Differences:: Differences between C/C++ and Java Grammars
8665 @node Java Bison Interface
8666 @subsection Java Bison Interface
8667 @c - %language "Java"
8670 The Java parser skeletons are selected using a language directive,
8671 @samp{%language "Java"}, or the synonymous command-line option
8672 @option{--language=java}.
8674 When run, @command{bison} will create several entities whose name
8675 starts with @samp{YY}. Use the @samp{%name-prefix} directive to
8676 change the prefix, see @ref{Decl Summary}; classes can be placed
8677 in an arbitrary Java package using a @samp{%define package} section.
8679 The parser class defines an inner class, @code{Location}, that is used
8680 for location tracking. If the parser is pure, it also defines an
8681 inner interface, @code{Lexer}; see~@ref{Java Scanner Interface} for the
8682 meaning of pure parsers when the Java language is chosen. Other than
8683 these inner class/interface, and the members described in~@ref{Java
8684 Parser Interface}, all the other members and fields are preceded
8685 with a @code{yy} prefix to avoid clashes with user code.
8687 No header file can be generated for Java parsers; you must not pass
8688 @option{-d}/@option{--defines} to @command{bison}, nor use the
8689 @samp{%defines} directive.
8691 By default, the @samp{YYParser} class has package visibility. A
8692 declaration @samp{%define "public"} will change to public visibility.
8693 Remember that, according to the Java language specification, the name
8694 of the @file{.java} file should match the name of the class in this
8697 Similarly, a declaration @samp{%define "abstract"} will make your
8700 You can create documentation for generated parsers using Javadoc.
8702 @node Java Semantic Values
8703 @subsection Java Semantic Values
8704 @c - No %union, specify type in %type/%token.
8706 @c - Printer and destructor
8708 There is no @code{%union} directive in Java parsers. Instead, the
8709 semantic values' types (class names) should be specified in the
8710 @code{%type} or @code{%token} directive:
8713 %type <Expression> expr assignment_expr term factor
8714 %type <Integer> number
8717 By default, the semantic stack is declared to have @code{Object} members,
8718 which means that the class types you specify can be of any class.
8719 To improve the type safety of the parser, you can declare the common
8720 superclass of all the semantic values using the @samp{%define} directive.
8721 For example, after the following declaration:
8724 %define "stype" "ASTNode"
8728 any @code{%type} or @code{%token} specifying a semantic type which
8729 is not a subclass of ASTNode, will cause a compile-time error.
8731 Types used in the directives may be qualified with a package name.
8732 Primitive data types are accepted for Java version 1.5 or later. Note
8733 that in this case the autoboxing feature of Java 1.5 will be used.
8735 Java parsers do not support @code{%destructor}, since the language
8736 adopts garbage collection. The parser will try to hold references
8737 to semantic values for as little time as needed.
8739 Java parsers do not support @code{%printer}, as @code{toString()}
8740 can be used to print the semantic values. This however may change
8741 (in a backwards-compatible way) in future versions of Bison.
8744 @node Java Location Values
8745 @subsection Java Location Values
8750 When the directive @code{%locations} is used, the Java parser
8751 supports location tracking, see @ref{Locations, , Locations Overview}.
8752 An auxiliary user-defined class defines a @dfn{position}, a single point
8753 in a file; Bison itself defines a class representing a @dfn{location},
8754 a range composed of a pair of positions (possibly spanning several
8755 files). The location class is an inner class of the parser; the name
8756 is @code{Location} by default, may also be renamed using @code{%define
8757 "location_type" "@var{class-name}}.
8759 The location class treats the position as a completely opaque value.
8760 By default, the class name is @code{Position}, but this can be changed
8761 with @code{%define "position_type" "@var{class-name}"}.
8764 @deftypemethod {Location} {Position} begin
8765 @deftypemethodx {Location} {Position} end
8766 The first, inclusive, position of the range, and the first beyond.
8769 @deftypemethod {Location} {void} toString ()
8770 Prints the range represented by the location. For this to work
8771 properly, the position class should override the @code{equals} and
8772 @code{toString} methods appropriately.
8776 @node Java Parser Interface
8777 @subsection Java Parser Interface
8778 @c - define parser_class_name
8780 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
8782 @c - Reporting errors
8784 The output file defines the parser class in the package optionally
8785 indicated in the @code{%define package} section. The class name defaults
8786 to @code{YYParser}. The @code{YY} prefix may be changed using
8787 @samp{%name-prefix}; alternatively, you can use @samp{%define
8788 "parser_class_name" "@var{name}"} to give a custom name to the class.
8789 The interface of this class is detailed below. It can be extended using
8790 the @code{%parse-param} directive; each occurrence of the directive will
8791 add a field to the parser class, and an argument to its constructor.
8793 @deftypemethod {YYParser} {} YYParser (@var{type1} @var{arg1}, ...)
8794 Build a new parser object. There are no arguments by default, unless
8795 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
8798 @deftypemethod {YYParser} {boolean} parse ()
8799 Run the syntactic analysis, and return @code{true} on success,
8800 @code{false} otherwise.
8803 @deftypemethod {YYParser} {boolean} recovering ()
8804 During the syntactic analysis, return @code{true} if recovering
8805 from a syntax error. @xref{Error Recovery}.
8808 @deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
8809 @deftypemethodx {YYParser} {void} setDebugStream (java.io.printStream @var{o})
8810 Get or set the stream used for tracing the parsing. It defaults to
8814 @deftypemethod {YYParser} {int} getDebugLevel ()
8815 @deftypemethodx {YYParser} {void} setDebugLevel (int @var{l})
8816 Get or set the tracing level. Currently its value is either 0, no trace,
8817 or nonzero, full tracing.
8820 @deftypemethod {YYParser} {void} error (Location @var{l}, String @var{m})
8821 The definition for this member function must be supplied by the user
8822 in the same way as the scanner interface (@pxref{Java Scanner
8823 Interface}); the parser uses it to report a parser error occurring at
8824 @var{l}, described by @var{m}.
8828 @node Java Scanner Interface
8829 @subsection Java Scanner Interface
8832 @c - Lexer interface
8834 Contrary to C parsers, Java parsers do not use global variables; the
8835 state of the parser is always local to an instance of the parser class.
8836 Therefore, all Java parsers are ``pure'', and the @code{%pure-parser}
8837 directive does not do anything when used in Java.
8839 The scanner always resides in a separate class than the parser.
8840 Still, Java also two possible ways to interface a Bison-generated Java
8841 parser with a scanner, that is, the scanner may reside in a separate file
8842 than the Bison grammar, or in the same file. The interface
8843 to the scanner is similar in the two cases.
8845 In the first case, where the scanner in the same file as the grammar, the
8846 scanner code has to be placed in @code{%code lexer} blocks. If you want
8847 to pass parameters from the parser constructor to the scanner constructor,
8848 specify them with @code{%lex-param}; they are passed before
8849 @code{%parse-param}s to the constructor.
8851 In the second case, the scanner has to implement interface @code{Lexer},
8852 which is defined within the parser class (e.g., @code{YYParser.Lexer}).
8853 The constructor of the parser object will then accept an object
8854 implementing the interface; @code{%lex-param} is not used in this
8857 In both cases, the scanner has to implement the following methods.
8859 @deftypemethod {Lexer} {void} yyerror (Location @var{l}, String @var{m})
8860 As explained in @pxref{Java Parser Interface}, this method is defined
8861 by the user to emit an error message. The first parameter is omitted
8862 if location tracking is not active. Its type can be changed using
8863 @samp{%define "location_type" "@var{class-name}".}
8866 @deftypemethod {Lexer} {int} yylex (@var{type1} @var{arg1}, ...)
8867 Return the next token. Its type is the return value, its semantic
8868 value and location are saved and returned by the ther methods in the
8869 interface. Invocations of @samp{%lex-param @{@var{type1}
8870 @var{arg1}@}} yield additional arguments.
8873 @deftypemethod {Lexer} {Position} getStartPos ()
8874 @deftypemethodx {Lexer} {Position} getEndPos ()
8875 Return respectively the first position of the last token that
8876 @code{yylex} returned, and the first position beyond it. These
8877 methods are not needed unless location tracking is active.
8879 The return type can be changed using @samp{%define "position_type"
8880 "@var{class-name}".}
8883 @deftypemethod {Lexer} {Object} getLVal ()
8884 Return respectively the first position of the last token that yylex
8885 returned, and the first position beyond it.
8887 The return type can be changed using @samp{%define "stype"
8888 "@var{class-name}".}
8892 The lexer interface resides in the same class (@code{YYParser}) as the
8893 Bison-generated parser.
8894 The fields and methods that are provided to this end are as follows.
8896 @deftypemethod {YYParser} {void} error (Location @var{l}, String @var{m})
8897 As explained in @pxref{Java Parser Interface}, this method is defined
8898 by the user to emit an error message. The first parameter is not used
8899 unless location tracking is active. Its type can be changed using
8900 @samp{%define "location_type" "@var{class-name}".}
8903 @deftypemethod {YYParser} {int} yylex (@var{type1} @var{arg1}, ...)
8904 Return the next token. Its type is the return value, its semantic
8905 value and location are saved into @code{yylval}, @code{yystartpos},
8906 @code{yyendpos}. Invocations of @samp{%lex-param @{@var{type1}
8907 @var{arg1}@}} yield additional arguments.
8910 @deftypecv {Field} {YYParser} Position yystartpos
8911 @deftypecvx {Field} {YYParser} Position yyendpos
8912 Contain respectively the first position of the last token that yylex
8913 returned, and the first position beyond it. These methods are not
8914 needed unless location tracking is active.
8916 The field's type can be changed using @samp{%define "position_type"
8917 "@var{class-name}".}
8920 @deftypecv {Field} {YYParser} Object yylval
8921 Return respectively the first position of the last token that yylex
8922 returned, and the first position beyond it.
8924 The field's type can be changed using @samp{%define "stype"
8925 "@var{class-name}".}
8928 @node Java Differences
8929 @subsection Differences between C/C++ and Java Grammars
8931 The different structure of the Java language forces several differences
8932 between C/C++ grammars, and grammars designed for Java parsers. This
8933 section summarizes these differences.
8937 Java lacks a preprocessor, so the @code{YYERROR}, @code{YYACCEPT},
8938 @code{YYABORT} symbols (@pxref{Table of Symbols}) cannot obviously be
8939 macros. Instead, they should be preceded by @code{return} when they
8940 appear in an action. The actual definition of these symbols is
8941 opaque to the Bison grammar, and it might change in the future. The
8942 only meaningful operation that you can do, is to return them.
8944 Note that of these three symbols, only @code{YYACCEPT} and
8945 @code{YYABORT} will cause a return from the @code{yyparse}
8946 method@footnote{Java parsers include the actions in a separate
8947 method than @code{yyparse} in order to have an intuitive syntax that
8948 corresponds to these C macros.}.
8951 The prolog declarations have a different meaning than in C/C++ code.
8953 @item @code{%code imports}
8954 blocks are placed at the beginning of the Java source code. They may
8955 include copyright notices. For a @code{package} declarations, it is
8956 suggested to use @code{%define package} instead.
8958 @item unqualified @code{%code}
8959 blocks are placed inside the parser class.
8961 @item @code{%code lexer}
8962 blocks, if specified, should include the implementation of the
8963 scanner. If there is no such block, the scanner can be any class
8964 that implements the appropriate interface (see @pxref{Java Scanner
8968 Other @code{%code} blocks are not supported in Java parsers.
8969 The epilogue has the same meaning as in C/C++ code and it can
8970 be used to define other classes used by the parser.
8973 @c ================================================= FAQ
8976 @chapter Frequently Asked Questions
8977 @cindex frequently asked questions
8980 Several questions about Bison come up occasionally. Here some of them
8984 * Memory Exhausted:: Breaking the Stack Limits
8985 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
8986 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
8987 * Implementing Gotos/Loops:: Control Flow in the Calculator
8988 * Multiple start-symbols:: Factoring closely related grammars
8989 * Secure? Conform?:: Is Bison @acronym{POSIX} safe?
8990 * I can't build Bison:: Troubleshooting
8991 * Where can I find help?:: Troubleshouting
8992 * Bug Reports:: Troublereporting
8993 * More Languages:: Parsers in C++, Java, and so on
8994 * Beta Testing:: Experimenting development versions
8995 * Mailing Lists:: Meeting other Bison users
8998 @node Memory Exhausted
8999 @section Memory Exhausted
9002 My parser returns with error with a @samp{memory exhausted}
9003 message. What can I do?
9006 This question is already addressed elsewhere, @xref{Recursion,
9009 @node How Can I Reset the Parser
9010 @section How Can I Reset the Parser
9012 The following phenomenon has several symptoms, resulting in the
9013 following typical questions:
9016 I invoke @code{yyparse} several times, and on correct input it works
9017 properly; but when a parse error is found, all the other calls fail
9018 too. How can I reset the error flag of @code{yyparse}?
9025 My parser includes support for an @samp{#include}-like feature, in
9026 which case I run @code{yyparse} from @code{yyparse}. This fails
9027 although I did specify @code{%define api.pure}.
9030 These problems typically come not from Bison itself, but from
9031 Lex-generated scanners. Because these scanners use large buffers for
9032 speed, they might not notice a change of input file. As a
9033 demonstration, consider the following source file,
9034 @file{first-line.l}:
9042 .*\n ECHO; return 1;
9045 yyparse (char const *file)
9047 yyin = fopen (file, "r");
9050 /* One token only. */
9052 if (fclose (yyin) != 0)
9067 If the file @file{input} contains
9075 then instead of getting the first line twice, you get:
9078 $ @kbd{flex -ofirst-line.c first-line.l}
9079 $ @kbd{gcc -ofirst-line first-line.c -ll}
9080 $ @kbd{./first-line}
9085 Therefore, whenever you change @code{yyin}, you must tell the
9086 Lex-generated scanner to discard its current buffer and switch to the
9087 new one. This depends upon your implementation of Lex; see its
9088 documentation for more. For Flex, it suffices to call
9089 @samp{YY_FLUSH_BUFFER} after each change to @code{yyin}. If your
9090 Flex-generated scanner needs to read from several input streams to
9091 handle features like include files, you might consider using Flex
9092 functions like @samp{yy_switch_to_buffer} that manipulate multiple
9095 If your Flex-generated scanner uses start conditions (@pxref{Start
9096 conditions, , Start conditions, flex, The Flex Manual}), you might
9097 also want to reset the scanner's state, i.e., go back to the initial
9098 start condition, through a call to @samp{BEGIN (0)}.
9100 @node Strings are Destroyed
9101 @section Strings are Destroyed
9104 My parser seems to destroy old strings, or maybe it loses track of
9105 them. Instead of reporting @samp{"foo", "bar"}, it reports
9106 @samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
9109 This error is probably the single most frequent ``bug report'' sent to
9110 Bison lists, but is only concerned with a misunderstanding of the role
9111 of the scanner. Consider the following Lex code:
9116 char *yylval = NULL;
9119 .* yylval = yytext; return 1;
9125 /* Similar to using $1, $2 in a Bison action. */
9126 char *fst = (yylex (), yylval);
9127 char *snd = (yylex (), yylval);
9128 printf ("\"%s\", \"%s\"\n", fst, snd);
9133 If you compile and run this code, you get:
9136 $ @kbd{flex -osplit-lines.c split-lines.l}
9137 $ @kbd{gcc -osplit-lines split-lines.c -ll}
9138 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
9144 this is because @code{yytext} is a buffer provided for @emph{reading}
9145 in the action, but if you want to keep it, you have to duplicate it
9146 (e.g., using @code{strdup}). Note that the output may depend on how
9147 your implementation of Lex handles @code{yytext}. For instance, when
9148 given the Lex compatibility option @option{-l} (which triggers the
9149 option @samp{%array}) Flex generates a different behavior:
9152 $ @kbd{flex -l -osplit-lines.c split-lines.l}
9153 $ @kbd{gcc -osplit-lines split-lines.c -ll}
9154 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
9159 @node Implementing Gotos/Loops
9160 @section Implementing Gotos/Loops
9163 My simple calculator supports variables, assignments, and functions,
9164 but how can I implement gotos, or loops?
9167 Although very pedagogical, the examples included in the document blur
9168 the distinction to make between the parser---whose job is to recover
9169 the structure of a text and to transmit it to subsequent modules of
9170 the program---and the processing (such as the execution) of this
9171 structure. This works well with so called straight line programs,
9172 i.e., precisely those that have a straightforward execution model:
9173 execute simple instructions one after the others.
9175 @cindex abstract syntax tree
9176 @cindex @acronym{AST}
9177 If you want a richer model, you will probably need to use the parser
9178 to construct a tree that does represent the structure it has
9179 recovered; this tree is usually called the @dfn{abstract syntax tree},
9180 or @dfn{@acronym{AST}} for short. Then, walking through this tree,
9181 traversing it in various ways, will enable treatments such as its
9182 execution or its translation, which will result in an interpreter or a
9185 This topic is way beyond the scope of this manual, and the reader is
9186 invited to consult the dedicated literature.
9189 @node Multiple start-symbols
9190 @section Multiple start-symbols
9193 I have several closely related grammars, and I would like to share their
9194 implementations. In fact, I could use a single grammar but with
9195 multiple entry points.
9198 Bison does not support multiple start-symbols, but there is a very
9199 simple means to simulate them. If @code{foo} and @code{bar} are the two
9200 pseudo start-symbols, then introduce two new tokens, say
9201 @code{START_FOO} and @code{START_BAR}, and use them as switches from the
9205 %token START_FOO START_BAR;
9207 start: START_FOO foo
9211 These tokens prevents the introduction of new conflicts. As far as the
9212 parser goes, that is all that is needed.
9214 Now the difficult part is ensuring that the scanner will send these
9215 tokens first. If your scanner is hand-written, that should be
9216 straightforward. If your scanner is generated by Lex, them there is
9217 simple means to do it: recall that anything between @samp{%@{ ... %@}}
9218 after the first @code{%%} is copied verbatim in the top of the generated
9219 @code{yylex} function. Make sure a variable @code{start_token} is
9220 available in the scanner (e.g., a global variable or using
9221 @code{%lex-param} etc.), and use the following:
9229 int t = start_token;
9234 /* @r{The rules.} */
9238 @node Secure? Conform?
9239 @section Secure? Conform?
9242 Is Bison secure? Does it conform to POSIX?
9245 If you're looking for a guarantee or certification, we don't provide it.
9246 However, Bison is intended to be a reliable program that conforms to the
9247 @acronym{POSIX} specification for Yacc. If you run into problems,
9248 please send us a bug report.
9250 @node I can't build Bison
9251 @section I can't build Bison
9254 I can't build Bison because @command{make} complains that
9255 @code{msgfmt} is not found.
9259 Like most GNU packages with internationalization support, that feature
9260 is turned on by default. If you have problems building in the @file{po}
9261 subdirectory, it indicates that your system's internationalization
9262 support is lacking. You can re-configure Bison with
9263 @option{--disable-nls} to turn off this support, or you can install GNU
9264 gettext from @url{ftp://ftp.gnu.org/gnu/gettext/} and re-configure
9265 Bison. See the file @file{ABOUT-NLS} for more information.
9268 @node Where can I find help?
9269 @section Where can I find help?
9272 I'm having trouble using Bison. Where can I find help?
9275 First, read this fine manual. Beyond that, you can send mail to
9276 @email{help-bison@@gnu.org}. This mailing list is intended to be
9277 populated with people who are willing to answer questions about using
9278 and installing Bison. Please keep in mind that (most of) the people on
9279 the list have aspects of their lives which are not related to Bison (!),
9280 so you may not receive an answer to your question right away. This can
9281 be frustrating, but please try not to honk them off; remember that any
9282 help they provide is purely voluntary and out of the kindness of their
9286 @section Bug Reports
9289 I found a bug. What should I include in the bug report?
9292 Before you send a bug report, make sure you are using the latest
9293 version. Check @url{ftp://ftp.gnu.org/pub/gnu/bison/} or one of its
9294 mirrors. Be sure to include the version number in your bug report. If
9295 the bug is present in the latest version but not in a previous version,
9296 try to determine the most recent version which did not contain the bug.
9298 If the bug is parser-related, you should include the smallest grammar
9299 you can which demonstrates the bug. The grammar file should also be
9300 complete (i.e., I should be able to run it through Bison without having
9301 to edit or add anything). The smaller and simpler the grammar, the
9302 easier it will be to fix the bug.
9304 Include information about your compilation environment, including your
9305 operating system's name and version and your compiler's name and
9306 version. If you have trouble compiling, you should also include a
9307 transcript of the build session, starting with the invocation of
9308 `configure'. Depending on the nature of the bug, you may be asked to
9309 send additional files as well (such as `config.h' or `config.cache').
9311 Patches are most welcome, but not required. That is, do not hesitate to
9312 send a bug report just because you can not provide a fix.
9314 Send bug reports to @email{bug-bison@@gnu.org}.
9316 @node More Languages
9317 @section More Languages
9320 Will Bison ever have C++ and Java support? How about @var{insert your
9321 favorite language here}?
9324 C++ and Java support is there now, and is documented. We'd love to add other
9325 languages; contributions are welcome.
9328 @section Beta Testing
9331 What is involved in being a beta tester?
9334 It's not terribly involved. Basically, you would download a test
9335 release, compile it, and use it to build and run a parser or two. After
9336 that, you would submit either a bug report or a message saying that
9337 everything is okay. It is important to report successes as well as
9338 failures because test releases eventually become mainstream releases,
9339 but only if they are adequately tested. If no one tests, development is
9342 Beta testers are particularly needed for operating systems to which the
9343 developers do not have easy access. They currently have easy access to
9344 recent GNU/Linux and Solaris versions. Reports about other operating
9345 systems are especially welcome.
9348 @section Mailing Lists
9351 How do I join the help-bison and bug-bison mailing lists?
9354 See @url{http://lists.gnu.org/}.
9356 @c ================================================= Table of Symbols
9358 @node Table of Symbols
9359 @appendix Bison Symbols
9360 @cindex Bison symbols, table of
9361 @cindex symbols in Bison, table of
9363 @deffn {Variable} @@$
9364 In an action, the location of the left-hand side of the rule.
9365 @xref{Locations, , Locations Overview}.
9368 @deffn {Variable} @@@var{n}
9369 In an action, the location of the @var{n}-th symbol of the right-hand
9370 side of the rule. @xref{Locations, , Locations Overview}.
9373 @deffn {Variable} $$
9374 In an action, the semantic value of the left-hand side of the rule.
9378 @deffn {Variable} $@var{n}
9379 In an action, the semantic value of the @var{n}-th symbol of the
9380 right-hand side of the rule. @xref{Actions}.
9383 @deffn {Delimiter} %%
9384 Delimiter used to separate the grammar rule section from the
9385 Bison declarations section or the epilogue.
9386 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
9389 @c Don't insert spaces, or check the DVI output.
9390 @deffn {Delimiter} %@{@var{code}%@}
9391 All code listed between @samp{%@{} and @samp{%@}} is copied directly to
9392 the output file uninterpreted. Such code forms the prologue of the input
9393 file. @xref{Grammar Outline, ,Outline of a Bison
9397 @deffn {Construct} /*@dots{}*/
9398 Comment delimiters, as in C.
9401 @deffn {Delimiter} :
9402 Separates a rule's result from its components. @xref{Rules, ,Syntax of
9406 @deffn {Delimiter} ;
9407 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
9410 @deffn {Delimiter} |
9411 Separates alternate rules for the same result nonterminal.
9412 @xref{Rules, ,Syntax of Grammar Rules}.
9415 @deffn {Directive} <*>
9416 Used to define a default tagged @code{%destructor} or default tagged
9419 This feature is experimental.
9420 More user feedback will help to determine whether it should become a permanent
9423 @xref{Destructor Decl, , Freeing Discarded Symbols}.
9426 @deffn {Directive} <>
9427 Used to define a default tagless @code{%destructor} or default tagless
9430 This feature is experimental.
9431 More user feedback will help to determine whether it should become a permanent
9434 @xref{Destructor Decl, , Freeing Discarded Symbols}.
9437 @deffn {Symbol} $accept
9438 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
9439 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
9440 Start-Symbol}. It cannot be used in the grammar.
9443 @deffn {Directive} %code @{@var{code}@}
9444 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
9445 Insert @var{code} verbatim into output parser source.
9446 @xref{Decl Summary,,%code}.
9449 @deffn {Directive} %debug
9450 Equip the parser for debugging. @xref{Decl Summary}.
9453 @deffn {Directive} %debug
9454 Equip the parser for debugging. @xref{Decl Summary}.
9458 @deffn {Directive} %default-prec
9459 Assign a precedence to rules that lack an explicit @samp{%prec}
9460 modifier. @xref{Contextual Precedence, ,Context-Dependent
9465 @deffn {Directive} %define @var{define-variable}
9466 @deffnx {Directive} %define @var{define-variable} @var{value}
9467 Define a variable to adjust Bison's behavior.
9468 @xref{Decl Summary,,%define}.
9471 @deffn {Directive} %defines
9472 Bison declaration to create a header file meant for the scanner.
9473 @xref{Decl Summary}.
9476 @deffn {Directive} %defines @var{defines-file}
9477 Same as above, but save in the file @var{defines-file}.
9478 @xref{Decl Summary}.
9481 @deffn {Directive} %destructor
9482 Specify how the parser should reclaim the memory associated to
9483 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
9486 @deffn {Directive} %dprec
9487 Bison declaration to assign a precedence to a rule that is used at parse
9488 time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
9489 @acronym{GLR} Parsers}.
9492 @deffn {Symbol} $end
9493 The predefined token marking the end of the token stream. It cannot be
9494 used in the grammar.
9497 @deffn {Symbol} error
9498 A token name reserved for error recovery. This token may be used in
9499 grammar rules so as to allow the Bison parser to recognize an error in
9500 the grammar without halting the process. In effect, a sentence
9501 containing an error may be recognized as valid. On a syntax error, the
9502 token @code{error} becomes the current lookahead token. Actions
9503 corresponding to @code{error} are then executed, and the lookahead
9504 token is reset to the token that originally caused the violation.
9505 @xref{Error Recovery}.
9508 @deffn {Directive} %error-verbose
9509 Bison declaration to request verbose, specific error message strings
9510 when @code{yyerror} is called.
9513 @deffn {Directive} %file-prefix "@var{prefix}"
9514 Bison declaration to set the prefix of the output files. @xref{Decl
9518 @deffn {Directive} %glr-parser
9519 Bison declaration to produce a @acronym{GLR} parser. @xref{GLR
9520 Parsers, ,Writing @acronym{GLR} Parsers}.
9523 @deffn {Directive} %initial-action
9524 Run user code before parsing. @xref{Initial Action Decl, , Performing Actions before Parsing}.
9527 @deffn {Directive} %language
9528 Specify the programming language for the generated parser.
9529 @xref{Decl Summary}.
9532 @deffn {Directive} %left
9533 Bison declaration to assign left associativity to token(s).
9534 @xref{Precedence Decl, ,Operator Precedence}.
9537 @deffn {Directive} %lex-param @{@var{argument-declaration}@}
9538 Bison declaration to specifying an additional parameter that
9539 @code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
9543 @deffn {Directive} %merge
9544 Bison declaration to assign a merging function to a rule. If there is a
9545 reduce/reduce conflict with a rule having the same merging function, the
9546 function is applied to the two semantic values to get a single result.
9547 @xref{GLR Parsers, ,Writing @acronym{GLR} Parsers}.
9550 @deffn {Directive} %name-prefix "@var{prefix}"
9551 Bison declaration to rename the external symbols. @xref{Decl Summary}.
9555 @deffn {Directive} %no-default-prec
9556 Do not assign a precedence to rules that lack an explicit @samp{%prec}
9557 modifier. @xref{Contextual Precedence, ,Context-Dependent
9562 @deffn {Directive} %no-lines
9563 Bison declaration to avoid generating @code{#line} directives in the
9564 parser file. @xref{Decl Summary}.
9567 @deffn {Directive} %nonassoc
9568 Bison declaration to assign nonassociativity to token(s).
9569 @xref{Precedence Decl, ,Operator Precedence}.
9572 @deffn {Directive} %output "@var{file}"
9573 Bison declaration to set the name of the parser file. @xref{Decl
9577 @deffn {Directive} %parse-param @{@var{argument-declaration}@}
9578 Bison declaration to specifying an additional parameter that
9579 @code{yyparse} should accept. @xref{Parser Function,, The Parser
9580 Function @code{yyparse}}.
9583 @deffn {Directive} %prec
9584 Bison declaration to assign a precedence to a specific rule.
9585 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
9588 @deffn {Directive} %pure-parser
9589 Deprecated version of @code{%define api.pure} (@pxref{Decl Summary, ,%define}),
9590 for which Bison is more careful to warn about unreasonable usage.
9593 @deffn {Directive} %require "@var{version}"
9594 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
9595 Require a Version of Bison}.
9598 @deffn {Directive} %right
9599 Bison declaration to assign right associativity to token(s).
9600 @xref{Precedence Decl, ,Operator Precedence}.
9603 @deffn {Directive} %skeleton
9604 Specify the skeleton to use; usually for development.
9605 @xref{Decl Summary}.
9608 @deffn {Directive} %start
9609 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
9613 @deffn {Directive} %token
9614 Bison declaration to declare token(s) without specifying precedence.
9615 @xref{Token Decl, ,Token Type Names}.
9618 @deffn {Directive} %token-table
9619 Bison declaration to include a token name table in the parser file.
9620 @xref{Decl Summary}.
9623 @deffn {Directive} %type
9624 Bison declaration to declare nonterminals. @xref{Type Decl,
9625 ,Nonterminal Symbols}.
9628 @deffn {Symbol} $undefined
9629 The predefined token onto which all undefined values returned by
9630 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
9634 @deffn {Directive} %union
9635 Bison declaration to specify several possible data types for semantic
9636 values. @xref{Union Decl, ,The Collection of Value Types}.
9639 @deffn {Macro} YYABORT
9640 Macro to pretend that an unrecoverable syntax error has occurred, by
9641 making @code{yyparse} return 1 immediately. The error reporting
9642 function @code{yyerror} is not called. @xref{Parser Function, ,The
9643 Parser Function @code{yyparse}}.
9645 For Java parsers, this functionality is invoked using @code{return YYABORT;}
9649 @deffn {Macro} YYACCEPT
9650 Macro to pretend that a complete utterance of the language has been
9651 read, by making @code{yyparse} return 0 immediately.
9652 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
9654 For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
9658 @deffn {Macro} YYBACKUP
9659 Macro to discard a value from the parser stack and fake a lookahead
9660 token. @xref{Action Features, ,Special Features for Use in Actions}.
9663 @deffn {Variable} yychar
9664 External integer variable that contains the integer value of the
9665 lookahead token. (In a pure parser, it is a local variable within
9666 @code{yyparse}.) Error-recovery rule actions may examine this variable.
9667 @xref{Action Features, ,Special Features for Use in Actions}.
9670 @deffn {Variable} yyclearin
9671 Macro used in error-recovery rule actions. It clears the previous
9672 lookahead token. @xref{Error Recovery}.
9675 @deffn {Macro} YYDEBUG
9676 Macro to define to equip the parser with tracing code. @xref{Tracing,
9677 ,Tracing Your Parser}.
9680 @deffn {Variable} yydebug
9681 External integer variable set to zero by default. If @code{yydebug}
9682 is given a nonzero value, the parser will output information on input
9683 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
9686 @deffn {Macro} yyerrok
9687 Macro to cause parser to recover immediately to its normal mode
9688 after a syntax error. @xref{Error Recovery}.
9691 @deffn {Macro} YYERROR
9692 Macro to pretend that a syntax error has just been detected: call
9693 @code{yyerror} and then perform normal error recovery if possible
9694 (@pxref{Error Recovery}), or (if recovery is impossible) make
9695 @code{yyparse} return 1. @xref{Error Recovery}.
9697 For Java parsers, this functionality is invoked using @code{return YYERROR;}
9701 @deffn {Function} yyerror
9702 User-supplied function to be called by @code{yyparse} on error.
9703 @xref{Error Reporting, ,The Error
9704 Reporting Function @code{yyerror}}.
9707 @deffn {Macro} YYERROR_VERBOSE
9708 An obsolete macro that you define with @code{#define} in the prologue
9709 to request verbose, specific error message strings
9710 when @code{yyerror} is called. It doesn't matter what definition you
9711 use for @code{YYERROR_VERBOSE}, just whether you define it. Using
9712 @code{%error-verbose} is preferred.
9715 @deffn {Macro} YYINITDEPTH
9716 Macro for specifying the initial size of the parser stack.
9717 @xref{Memory Management}.
9720 @deffn {Function} yylex
9721 User-supplied lexical analyzer function, called with no arguments to get
9722 the next token. @xref{Lexical, ,The Lexical Analyzer Function
9726 @deffn {Macro} YYLEX_PARAM
9727 An obsolete macro for specifying an extra argument (or list of extra
9728 arguments) for @code{yyparse} to pass to @code{yylex}. The use of this
9729 macro is deprecated, and is supported only for Yacc like parsers.
9730 @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
9733 @deffn {Variable} yylloc
9734 External variable in which @code{yylex} should place the line and column
9735 numbers associated with a token. (In a pure parser, it is a local
9736 variable within @code{yyparse}, and its address is passed to
9738 You can ignore this variable if you don't use the @samp{@@} feature in the
9740 @xref{Token Locations, ,Textual Locations of Tokens}.
9741 In semantic actions, it stores the location of the lookahead token.
9742 @xref{Actions and Locations, ,Actions and Locations}.
9745 @deffn {Type} YYLTYPE
9746 Data type of @code{yylloc}; by default, a structure with four
9747 members. @xref{Location Type, , Data Types of Locations}.
9750 @deffn {Variable} yylval
9751 External variable in which @code{yylex} should place the semantic
9752 value associated with a token. (In a pure parser, it is a local
9753 variable within @code{yyparse}, and its address is passed to
9755 @xref{Token Values, ,Semantic Values of Tokens}.
9756 In semantic actions, it stores the semantic value of the lookahead token.
9757 @xref{Actions, ,Actions}.
9760 @deffn {Macro} YYMAXDEPTH
9761 Macro for specifying the maximum size of the parser stack. @xref{Memory
9765 @deffn {Variable} yynerrs
9766 Global variable which Bison increments each time it reports a syntax error.
9767 (In a pure parser, it is a local variable within @code{yyparse}. In a
9768 pure push parser, it is a member of yypstate.)
9769 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
9772 @deffn {Function} yyparse
9773 The parser function produced by Bison; call this function to start
9774 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
9777 @deffn {Function} yypstate_delete
9778 The function to delete a parser instance, produced by Bison in push mode;
9779 call this function to delete the memory associated with a parser.
9780 @xref{Parser Delete Function, ,The Parser Delete Function
9781 @code{yypstate_delete}}.
9784 @deffn {Function} yypstate_new
9785 The function to create a parser instance, produced by Bison in push mode;
9786 call this function to create a new parser.
9787 @xref{Parser Create Function, ,The Parser Create Function
9788 @code{yypstate_new}}.
9791 @deffn {Function} yypull_parse
9792 The parser function produced by Bison in push mode; call this function to
9793 parse the rest of the input stream.
9794 @xref{Pull Parser Function, ,The Pull Parser Function
9795 @code{yypull_parse}}.
9798 @deffn {Function} yypush_parse
9799 The parser function produced by Bison in push mode; call this function to
9800 parse a single token. @xref{Push Parser Function, ,The Push Parser Function
9801 @code{yypush_parse}}.
9804 @deffn {Macro} YYPARSE_PARAM
9805 An obsolete macro for specifying the name of a parameter that
9806 @code{yyparse} should accept. The use of this macro is deprecated, and
9807 is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
9808 Conventions for Pure Parsers}.
9811 @deffn {Macro} YYRECOVERING
9812 The expression @code{YYRECOVERING ()} yields 1 when the parser
9813 is recovering from a syntax error, and 0 otherwise.
9814 @xref{Action Features, ,Special Features for Use in Actions}.
9817 @deffn {Macro} YYSTACK_USE_ALLOCA
9818 Macro used to control the use of @code{alloca} when the C
9819 @acronym{LALR}(1) parser needs to extend its stacks. If defined to 0,
9820 the parser will use @code{malloc} to extend its stacks. If defined to
9821 1, the parser will use @code{alloca}. Values other than 0 and 1 are
9822 reserved for future Bison extensions. If not defined,
9823 @code{YYSTACK_USE_ALLOCA} defaults to 0.
9825 In the all-too-common case where your code may run on a host with a
9826 limited stack and with unreliable stack-overflow checking, you should
9827 set @code{YYMAXDEPTH} to a value that cannot possibly result in
9828 unchecked stack overflow on any of your target hosts when
9829 @code{alloca} is called. You can inspect the code that Bison
9830 generates in order to determine the proper numeric values. This will
9831 require some expertise in low-level implementation details.
9834 @deffn {Type} YYSTYPE
9835 Data type of semantic values; @code{int} by default.
9836 @xref{Value Type, ,Data Types of Semantic Values}.
9844 @item Backus-Naur Form (@acronym{BNF}; also called ``Backus Normal Form'')
9845 Formal method of specifying context-free grammars originally proposed
9846 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
9847 committee document contributing to what became the Algol 60 report.
9848 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9850 @item Context-free grammars
9851 Grammars specified as rules that can be applied regardless of context.
9852 Thus, if there is a rule which says that an integer can be used as an
9853 expression, integers are allowed @emph{anywhere} an expression is
9854 permitted. @xref{Language and Grammar, ,Languages and Context-Free
9857 @item Dynamic allocation
9858 Allocation of memory that occurs during execution, rather than at
9859 compile time or on entry to a function.
9862 Analogous to the empty set in set theory, the empty string is a
9863 character string of length zero.
9865 @item Finite-state stack machine
9866 A ``machine'' that has discrete states in which it is said to exist at
9867 each instant in time. As input to the machine is processed, the
9868 machine moves from state to state as specified by the logic of the
9869 machine. In the case of the parser, the input is the language being
9870 parsed, and the states correspond to various stages in the grammar
9871 rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
9873 @item Generalized @acronym{LR} (@acronym{GLR})
9874 A parsing algorithm that can handle all context-free grammars, including those
9875 that are not @acronym{LALR}(1). It resolves situations that Bison's
9876 usual @acronym{LALR}(1)
9877 algorithm cannot by effectively splitting off multiple parsers, trying all
9878 possible parsers, and discarding those that fail in the light of additional
9879 right context. @xref{Generalized LR Parsing, ,Generalized
9880 @acronym{LR} Parsing}.
9883 A language construct that is (in general) grammatically divisible;
9884 for example, `expression' or `declaration' in C@.
9885 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9887 @item Infix operator
9888 An arithmetic operator that is placed between the operands on which it
9889 performs some operation.
9892 A continuous flow of data between devices or programs.
9894 @item Language construct
9895 One of the typical usage schemas of the language. For example, one of
9896 the constructs of the C language is the @code{if} statement.
9897 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9899 @item Left associativity
9900 Operators having left associativity are analyzed from left to right:
9901 @samp{a+b+c} first computes @samp{a+b} and then combines with
9902 @samp{c}. @xref{Precedence, ,Operator Precedence}.
9904 @item Left recursion
9905 A rule whose result symbol is also its first component symbol; for
9906 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
9909 @item Left-to-right parsing
9910 Parsing a sentence of a language by analyzing it token by token from
9911 left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
9913 @item Lexical analyzer (scanner)
9914 A function that reads an input stream and returns tokens one by one.
9915 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
9917 @item Lexical tie-in
9918 A flag, set by actions in the grammar rules, which alters the way
9919 tokens are parsed. @xref{Lexical Tie-ins}.
9921 @item Literal string token
9922 A token which consists of two or more fixed characters. @xref{Symbols}.
9924 @item Lookahead token
9925 A token already read but not yet shifted. @xref{Lookahead, ,Lookahead
9928 @item @acronym{LALR}(1)
9929 The class of context-free grammars that Bison (like most other parser
9930 generators) can handle; a subset of @acronym{LR}(1). @xref{Mystery
9931 Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
9933 @item @acronym{LR}(1)
9934 The class of context-free grammars in which at most one token of
9935 lookahead is needed to disambiguate the parsing of any piece of input.
9937 @item Nonterminal symbol
9938 A grammar symbol standing for a grammatical construct that can
9939 be expressed through rules in terms of smaller constructs; in other
9940 words, a construct that is not a token. @xref{Symbols}.
9943 A function that recognizes valid sentences of a language by analyzing
9944 the syntax structure of a set of tokens passed to it from a lexical
9947 @item Postfix operator
9948 An arithmetic operator that is placed after the operands upon which it
9949 performs some operation.
9952 Replacing a string of nonterminals and/or terminals with a single
9953 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
9957 A reentrant subprogram is a subprogram which can be in invoked any
9958 number of times in parallel, without interference between the various
9959 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
9961 @item Reverse polish notation
9962 A language in which all operators are postfix operators.
9964 @item Right recursion
9965 A rule whose result symbol is also its last component symbol; for
9966 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
9970 In computer languages, the semantics are specified by the actions
9971 taken for each instance of the language, i.e., the meaning of
9972 each statement. @xref{Semantics, ,Defining Language Semantics}.
9975 A parser is said to shift when it makes the choice of analyzing
9976 further input from the stream rather than reducing immediately some
9977 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
9979 @item Single-character literal
9980 A single character that is recognized and interpreted as is.
9981 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
9984 The nonterminal symbol that stands for a complete valid utterance in
9985 the language being parsed. The start symbol is usually listed as the
9986 first nonterminal symbol in a language specification.
9987 @xref{Start Decl, ,The Start-Symbol}.
9990 A data structure where symbol names and associated data are stored
9991 during parsing to allow for recognition and use of existing
9992 information in repeated uses of a symbol. @xref{Multi-function Calc}.
9995 An error encountered during parsing of an input stream due to invalid
9996 syntax. @xref{Error Recovery}.
9999 A basic, grammatically indivisible unit of a language. The symbol
10000 that describes a token in the grammar is a terminal symbol.
10001 The input of the Bison parser is a stream of tokens which comes from
10002 the lexical analyzer. @xref{Symbols}.
10004 @item Terminal symbol
10005 A grammar symbol that has no rules in the grammar and therefore is
10006 grammatically indivisible. The piece of text it represents is a token.
10007 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
10010 @node Copying This Manual
10011 @appendix Copying This Manual
10021 @c LocalWords: texinfo setfilename settitle setchapternewpage finalout
10022 @c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex
10023 @c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry
10024 @c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa
10025 @c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc
10026 @c LocalWords: rpcalc Lexer Gen Comp Expr ltcalc mfcalc Decl Symtab yylex
10027 @c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref
10028 @c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex
10029 @c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init stmtMerge
10030 @c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG
10031 @c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit
10032 @c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok
10033 @c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln
10034 @c LocalWords: smallexample symrec val tptr FNCT fnctptr func struct sym
10035 @c LocalWords: fnct putsym getsym fname arith fncts atan ptr malloc sizeof
10036 @c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum
10037 @c LocalWords: ptypes itype YYPRINT trigraphs yytname expseq vindex dtype
10038 @c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs
10039 @c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES
10040 @c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param
10041 @c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP
10042 @c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword
10043 @c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH
10044 @c LocalWords: YYINITDEPTH stmnts ref stmnt initdcl maybeasm notype
10045 @c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args
10046 @c LocalWords: infile ypp yxx outfile itemx tex leaderfill
10047 @c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll
10048 @c LocalWords: nbar yytext fst snd osplit ntwo strdup AST
10049 @c LocalWords: YYSTACK DVI fdl printindex