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 have the new `shorttitlepage' command
16 @c @clear shorttitlepage-enabled
17 @c @set shorttitlepage-enabled
19 @c ISPELL CHECK: done, 14 Jan 1993 --bob
21 @c Check COPYRIGHT dates. should be updated in the titlepage, ifinfo
22 @c titlepage; should NOT be changed in the GPL. --mew
24 @c FIXME: I don't understand this `iftex'. Obsolete? --akim.
35 @comment %**end of header
39 This manual is for GNU Bison (version @value{VERSION}, @value{UPDATED}),
40 the GNU parser generator.
42 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
43 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
46 Permission is granted to copy, distribute and/or modify this document
47 under the terms of the GNU Free Documentation License, Version 1.1 or
48 any later version published by the Free Software Foundation; with no
49 Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
50 and with the Back-Cover Texts as in (a) below. A copy of the
51 license is included in the section entitled ``GNU Free Documentation
54 (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
55 this GNU Manual, like GNU software. Copies published by the Free
56 Software Foundation raise funds for GNU development.''
60 @dircategory GNU programming tools
62 * bison: (bison). GNU parser generator (yacc replacement).
65 @ifset shorttitlepage-enabled
70 @subtitle The YACC-compatible Parser Generator
71 @subtitle @value{UPDATED}, Bison Version @value{VERSION}
73 @author by Charles Donnelly and Richard Stallman
76 @vskip 0pt plus 1filll
79 Published by the Free Software Foundation @*
80 59 Temple Place, Suite 330 @*
81 Boston, MA 02111-1307 USA @*
82 Printed copies are available from the Free Software Foundation.@*
85 Cover art by Etienne Suvasa.
99 * Copying:: The GNU General Public License says
100 how you can copy and share Bison
103 * Concepts:: Basic concepts for understanding Bison.
104 * Examples:: Three simple explained examples of using Bison.
107 * Grammar File:: Writing Bison declarations and rules.
108 * Interface:: C-language interface to the parser function @code{yyparse}.
109 * Algorithm:: How the Bison parser works at run-time.
110 * Error Recovery:: Writing rules for error recovery.
111 * Context Dependency:: What to do if your language syntax is too
112 messy for Bison to handle straightforwardly.
113 * Debugging:: Understanding or debugging Bison parsers.
114 * Invocation:: How to run Bison (to produce the parser source file).
115 * Table of Symbols:: All the keywords of the Bison language are explained.
116 * Glossary:: Basic concepts are explained.
117 * Copying This Manual:: License for copying this manual.
118 * Index:: Cross-references to the text.
120 @detailmenu --- The Detailed Node Listing ---
122 The Concepts of Bison
124 * Language and Grammar:: Languages and context-free grammars,
125 as mathematical ideas.
126 * Grammar in Bison:: How we represent grammars for Bison's sake.
127 * Semantic Values:: Each token or syntactic grouping can have
128 a semantic value (the value of an integer,
129 the name of an identifier, etc.).
130 * Semantic Actions:: Each rule can have an action containing C code.
131 * Bison Parser:: What are Bison's input and output,
132 how is the output used?
133 * Stages:: Stages in writing and running Bison grammars.
134 * Grammar Layout:: Overall structure of a Bison grammar file.
138 * RPN Calc:: Reverse polish notation calculator;
139 a first example with no operator precedence.
140 * Infix Calc:: Infix (algebraic) notation calculator.
141 Operator precedence is introduced.
142 * Simple Error Recovery:: Continuing after syntax errors.
143 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
144 * Multi-function Calc:: Calculator with memory and trig functions.
145 It uses multiple data-types for semantic values.
146 * Exercises:: Ideas for improving the multi-function calculator.
148 Reverse Polish Notation Calculator
150 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
151 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
152 * Lexer: Rpcalc Lexer. The lexical analyzer.
153 * Main: Rpcalc Main. The controlling function.
154 * Error: Rpcalc Error. The error reporting function.
155 * Gen: Rpcalc Gen. Running Bison on the grammar file.
156 * Comp: Rpcalc Compile. Run the C compiler on the output code.
158 Grammar Rules for @code{rpcalc}
164 Location Tracking Calculator: @code{ltcalc}
166 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
167 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
168 * Lexer: Ltcalc Lexer. The lexical analyzer.
170 Multi-Function Calculator: @code{mfcalc}
172 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
173 * Rules: Mfcalc Rules. Grammar rules for the calculator.
174 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
178 * Grammar Outline:: Overall layout of the grammar file.
179 * Symbols:: Terminal and nonterminal symbols.
180 * Rules:: How to write grammar rules.
181 * Recursion:: Writing recursive rules.
182 * Semantics:: Semantic values and actions.
183 * Declarations:: All kinds of Bison declarations are described here.
184 * Multiple Parsers:: Putting more than one Bison parser in one program.
186 Outline of a Bison Grammar
188 * Prologue:: Syntax and usage of the prologue (declarations section).
189 * Bison Declarations:: Syntax and usage of the Bison declarations section.
190 * Grammar Rules:: Syntax and usage of the grammar rules section.
191 * Epilogue:: Syntax and usage of the epilogue (additional code section).
193 Defining Language Semantics
195 * Value Type:: Specifying one data type for all semantic values.
196 * Multiple Types:: Specifying several alternative data types.
197 * Actions:: An action is the semantic definition of a grammar rule.
198 * Action Types:: Specifying data types for actions to operate on.
199 * Mid-Rule Actions:: Most actions go at the end of a rule.
200 This says when, why and how to use the exceptional
201 action in the middle of a rule.
205 * Token Decl:: Declaring terminal symbols.
206 * Precedence Decl:: Declaring terminals with precedence and associativity.
207 * Union Decl:: Declaring the set of all semantic value types.
208 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
209 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
210 * Start Decl:: Specifying the start symbol.
211 * Pure Decl:: Requesting a reentrant parser.
212 * Decl Summary:: Table of all Bison declarations.
214 Parser C-Language Interface
216 * Parser Function:: How to call @code{yyparse} and what it returns.
217 * Lexical:: You must supply a function @code{yylex}
219 * Error Reporting:: You must supply a function @code{yyerror}.
220 * Action Features:: Special features for use in actions.
222 The Lexical Analyzer Function @code{yylex}
224 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
225 * Token Values:: How @code{yylex} must return the semantic value
226 of the token it has read.
227 * Token Positions:: How @code{yylex} must return the text position
228 (line number, etc.) of the token, if the
230 * Pure Calling:: How the calling convention differs
231 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
233 The Bison Parser Algorithm
235 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
236 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
237 * Precedence:: Operator precedence works by resolving conflicts.
238 * Contextual Precedence:: When an operator's precedence depends on context.
239 * Parser States:: The parser is a finite-state-machine with stack.
240 * Reduce/Reduce:: When two rules are applicable in the same situation.
241 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
242 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
243 * Stack Overflow:: What happens when stack gets full. How to avoid it.
247 * Why Precedence:: An example showing why precedence is needed.
248 * Using Precedence:: How to specify precedence in Bison grammars.
249 * Precedence Examples:: How these features are used in the previous example.
250 * How Precedence:: How they work.
252 Handling Context Dependencies
254 * Semantic Tokens:: Token parsing can depend on the semantic context.
255 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
256 * Tie-in Recovery:: Lexical tie-ins have implications for how
257 error recovery rules must be written.
259 Understanding or Debugging Your Parser
261 * Understanding:: Understanding the structure of your parser.
262 * Tracing:: Tracing the execution of your parser.
266 * Bison Options:: All the options described in detail,
267 in alphabetical order by short options.
268 * Option Cross Key:: Alphabetical list of long options.
269 * VMS Invocation:: Bison command syntax on VMS.
273 * GNU Free Documentation License:: License for copying this manual.
279 @unnumbered Introduction
282 @dfn{Bison} is a general-purpose parser generator that converts a
283 grammar description for an LALR(1) context-free grammar into a C
284 program to parse that grammar. Once you are proficient with Bison,
285 you may use it to develop a wide range of language parsers, from those
286 used in simple desk calculators to complex programming languages.
288 Bison is upward compatible with Yacc: all properly-written Yacc grammars
289 ought to work with Bison with no change. Anyone familiar with Yacc
290 should be able to use Bison with little trouble. You need to be fluent in
291 C programming in order to use Bison or to understand this manual.
293 We begin with tutorial chapters that explain the basic concepts of using
294 Bison and show three explained examples, each building on the last. If you
295 don't know Bison or Yacc, start by reading these chapters. Reference
296 chapters follow which describe specific aspects of Bison in detail.
298 Bison was written primarily by Robert Corbett; Richard Stallman made it
299 Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
300 multi-character string literals and other features.
302 This edition corresponds to version @value{VERSION} of Bison.
305 @unnumbered Conditions for Using Bison
307 As of Bison version 1.24, we have changed the distribution terms for
308 @code{yyparse} to permit using Bison's output in nonfree programs when
309 Bison is generating C code for LALR(1) parsers. Formerly, these
310 parsers could be used only in programs that were free software.
312 The other GNU programming tools, such as the GNU C compiler, have never
313 had such a requirement. They could always be used for nonfree
314 software. The reason Bison was different was not due to a special
315 policy decision; it resulted from applying the usual General Public
316 License to all of the Bison source code.
318 The output of the Bison utility---the Bison parser file---contains a
319 verbatim copy of a sizable piece of Bison, which is the code for the
320 @code{yyparse} function. (The actions from your grammar are inserted
321 into this function at one point, but the rest of the function is not
322 changed.) When we applied the GPL terms to the code for @code{yyparse},
323 the effect was to restrict the use of Bison output to free software.
325 We didn't change the terms because of sympathy for people who want to
326 make software proprietary. @strong{Software should be free.} But we
327 concluded that limiting Bison's use to free software was doing little to
328 encourage people to make other software free. So we decided to make the
329 practical conditions for using Bison match the practical conditions for
330 using the other GNU tools.
332 This exception applies only when Bison is generating C code for a
333 LALR(1) parser; otherwise, the GPL terms operate as usual. You can
334 tell whether the exception applies to your @samp{.c} output file by
335 inspecting it to see whether it says ``As a special exception, when
336 this file is copied by Bison into a Bison output file, you may use
337 that output file without restriction.''
342 @chapter The Concepts of Bison
344 This chapter introduces many of the basic concepts without which the
345 details of Bison will not make sense. If you do not already know how to
346 use Bison or Yacc, we suggest you start by reading this chapter carefully.
349 * Language and Grammar:: Languages and context-free grammars,
350 as mathematical ideas.
351 * Grammar in Bison:: How we represent grammars for Bison's sake.
352 * Semantic Values:: Each token or syntactic grouping can have
353 a semantic value (the value of an integer,
354 the name of an identifier, etc.).
355 * Semantic Actions:: Each rule can have an action containing C code.
356 * GLR Parsers:: Writing parsers for general context-free languages
357 * Locations Overview:: Tracking Locations.
358 * Bison Parser:: What are Bison's input and output,
359 how is the output used?
360 * Stages:: Stages in writing and running Bison grammars.
361 * Grammar Layout:: Overall structure of a Bison grammar file.
364 @node Language and Grammar
365 @section Languages and Context-Free Grammars
367 @cindex context-free grammar
368 @cindex grammar, context-free
369 In order for Bison to parse a language, it must be described by a
370 @dfn{context-free grammar}. This means that you specify one or more
371 @dfn{syntactic groupings} and give rules for constructing them from their
372 parts. For example, in the C language, one kind of grouping is called an
373 `expression'. One rule for making an expression might be, ``An expression
374 can be made of a minus sign and another expression''. Another would be,
375 ``An expression can be an integer''. As you can see, rules are often
376 recursive, but there must be at least one rule which leads out of the
380 @cindex Backus-Naur form
381 The most common formal system for presenting such rules for humans to read
382 is @dfn{Backus-Naur Form} or ``BNF'', which was developed in order to
383 specify the language Algol 60. Any grammar expressed in BNF is a
384 context-free grammar. The input to Bison is essentially machine-readable
387 @cindex LALR(1) grammars
388 @cindex LR(1) grammars
389 There are various important subclasses of context-free grammar. Although it
390 can handle almost all context-free grammars, Bison is optimized for what
391 are called LALR(1) grammars.
392 In brief, in these grammars, it must be possible to
393 tell how to parse any portion of an input string with just a single
394 token of look-ahead. Strictly speaking, that is a description of an
395 LR(1) grammar, and LALR(1) involves additional restrictions that are
396 hard to explain simply; but it is rare in actual practice to find an
397 LR(1) grammar that fails to be LALR(1). @xref{Mystery Conflicts, ,
398 Mysterious Reduce/Reduce Conflicts}, for more information on this.
401 @cindex generalized LR (GLR) parsing
402 @cindex ambiguous grammars
403 @cindex non-deterministic parsing
404 Parsers for LALR(1) grammars are @dfn{deterministic}, meaning roughly that
405 the next grammar rule to apply at any point in the input is uniquely
406 determined by the preceding input and a fixed, finite portion (called
407 a @dfn{look-ahead}) of the remaining input.
408 A context-free grammar can be @dfn{ambiguous}, meaning that
409 there are multiple ways to apply the grammar rules to get the some inputs.
410 Even unambiguous grammars can be @dfn{non-deterministic}, meaning that no
411 fixed look-ahead always suffices to determine the next grammar rule to apply.
412 With the proper declarations, Bison is also able to parse these more general
413 context-free grammars, using a technique known as GLR parsing (for
414 Generalized LR). Bison's GLR parsers are able to handle any context-free
415 grammar for which the number of possible parses of any given string
418 @cindex symbols (abstract)
420 @cindex syntactic grouping
421 @cindex grouping, syntactic
422 In the formal grammatical rules for a language, each kind of syntactic unit
423 or grouping is named by a @dfn{symbol}. Those which are built by grouping
424 smaller constructs according to grammatical rules are called
425 @dfn{nonterminal symbols}; those which can't be subdivided are called
426 @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
427 corresponding to a single terminal symbol a @dfn{token}, and a piece
428 corresponding to a single nonterminal symbol a @dfn{grouping}.
430 We can use the C language as an example of what symbols, terminal and
431 nonterminal, mean. The tokens of C are identifiers, constants (numeric and
432 string), and the various keywords, arithmetic operators and punctuation
433 marks. So the terminal symbols of a grammar for C include `identifier',
434 `number', `string', plus one symbol for each keyword, operator or
435 punctuation mark: `if', `return', `const', `static', `int', `char',
436 `plus-sign', `open-brace', `close-brace', `comma' and many more. (These
437 tokens can be subdivided into characters, but that is a matter of
438 lexicography, not grammar.)
440 Here is a simple C function subdivided into tokens:
444 int /* @r{keyword `int'} */
445 square (int x) /* @r{identifier, open-paren, identifier,}
446 @r{identifier, close-paren} */
447 @{ /* @r{open-brace} */
448 return x * x; /* @r{keyword `return', identifier, asterisk,
449 identifier, semicolon} */
450 @} /* @r{close-brace} */
455 int /* @r{keyword `int'} */
456 square (int x) /* @r{identifier, open-paren, identifier, identifier, close-paren} */
457 @{ /* @r{open-brace} */
458 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
459 @} /* @r{close-brace} */
463 The syntactic groupings of C include the expression, the statement, the
464 declaration, and the function definition. These are represented in the
465 grammar of C by nonterminal symbols `expression', `statement',
466 `declaration' and `function definition'. The full grammar uses dozens of
467 additional language constructs, each with its own nonterminal symbol, in
468 order to express the meanings of these four. The example above is a
469 function definition; it contains one declaration, and one statement. In
470 the statement, each @samp{x} is an expression and so is @samp{x * x}.
472 Each nonterminal symbol must have grammatical rules showing how it is made
473 out of simpler constructs. For example, one kind of C statement is the
474 @code{return} statement; this would be described with a grammar rule which
475 reads informally as follows:
478 A `statement' can be made of a `return' keyword, an `expression' and a
483 There would be many other rules for `statement', one for each kind of
487 One nonterminal symbol must be distinguished as the special one which
488 defines a complete utterance in the language. It is called the @dfn{start
489 symbol}. In a compiler, this means a complete input program. In the C
490 language, the nonterminal symbol `sequence of definitions and declarations'
493 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
494 program---but it is not valid as an @emph{entire} C program. In the
495 context-free grammar of C, this follows from the fact that `expression' is
496 not the start symbol.
498 The Bison parser reads a sequence of tokens as its input, and groups the
499 tokens using the grammar rules. If the input is valid, the end result is
500 that the entire token sequence reduces to a single grouping whose symbol is
501 the grammar's start symbol. If we use a grammar for C, the entire input
502 must be a `sequence of definitions and declarations'. If not, the parser
503 reports a syntax error.
505 @node Grammar in Bison
506 @section From Formal Rules to Bison Input
507 @cindex Bison grammar
508 @cindex grammar, Bison
509 @cindex formal grammar
511 A formal grammar is a mathematical construct. To define the language
512 for Bison, you must write a file expressing the grammar in Bison syntax:
513 a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
515 A nonterminal symbol in the formal grammar is represented in Bison input
516 as an identifier, like an identifier in C. By convention, it should be
517 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
519 The Bison representation for a terminal symbol is also called a @dfn{token
520 type}. Token types as well can be represented as C-like identifiers. By
521 convention, these identifiers should be upper case to distinguish them from
522 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
523 @code{RETURN}. A terminal symbol that stands for a particular keyword in
524 the language should be named after that keyword converted to upper case.
525 The terminal symbol @code{error} is reserved for error recovery.
528 A terminal symbol can also be represented as a character literal, just like
529 a C character constant. You should do this whenever a token is just a
530 single character (parenthesis, plus-sign, etc.): use that same character in
531 a literal as the terminal symbol for that token.
533 A third way to represent a terminal symbol is with a C string constant
534 containing several characters. @xref{Symbols}, for more information.
536 The grammar rules also have an expression in Bison syntax. For example,
537 here is the Bison rule for a C @code{return} statement. The semicolon in
538 quotes is a literal character token, representing part of the C syntax for
539 the statement; the naked semicolon, and the colon, are Bison punctuation
543 stmt: RETURN expr ';'
548 @xref{Rules, ,Syntax of Grammar Rules}.
550 @node Semantic Values
551 @section Semantic Values
552 @cindex semantic value
553 @cindex value, semantic
555 A formal grammar selects tokens only by their classifications: for example,
556 if a rule mentions the terminal symbol `integer constant', it means that
557 @emph{any} integer constant is grammatically valid in that position. The
558 precise value of the constant is irrelevant to how to parse the input: if
559 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
562 But the precise value is very important for what the input means once it is
563 parsed. A compiler is useless if it fails to distinguish between 4, 1 and
564 3989 as constants in the program! Therefore, each token in a Bison grammar
565 has both a token type and a @dfn{semantic value}. @xref{Semantics, ,Defining Language Semantics},
568 The token type is a terminal symbol defined in the grammar, such as
569 @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
570 you need to know to decide where the token may validly appear and how to
571 group it with other tokens. The grammar rules know nothing about tokens
574 The semantic value has all the rest of the information about the
575 meaning of the token, such as the value of an integer, or the name of an
576 identifier. (A token such as @code{','} which is just punctuation doesn't
577 need to have any semantic value.)
579 For example, an input token might be classified as token type
580 @code{INTEGER} and have the semantic value 4. Another input token might
581 have the same token type @code{INTEGER} but value 3989. When a grammar
582 rule says that @code{INTEGER} is allowed, either of these tokens is
583 acceptable because each is an @code{INTEGER}. When the parser accepts the
584 token, it keeps track of the token's semantic value.
586 Each grouping can also have a semantic value as well as its nonterminal
587 symbol. For example, in a calculator, an expression typically has a
588 semantic value that is a number. In a compiler for a programming
589 language, an expression typically has a semantic value that is a tree
590 structure describing the meaning of the expression.
592 @node Semantic Actions
593 @section Semantic Actions
594 @cindex semantic actions
595 @cindex actions, semantic
597 In order to be useful, a program must do more than parse input; it must
598 also produce some output based on the input. In a Bison grammar, a grammar
599 rule can have an @dfn{action} made up of C statements. Each time the
600 parser recognizes a match for that rule, the action is executed.
603 Most of the time, the purpose of an action is to compute the semantic value
604 of the whole construct from the semantic values of its parts. For example,
605 suppose we have a rule which says an expression can be the sum of two
606 expressions. When the parser recognizes such a sum, each of the
607 subexpressions has a semantic value which describes how it was built up.
608 The action for this rule should create a similar sort of value for the
609 newly recognized larger expression.
611 For example, here is a rule that says an expression can be the sum of
615 expr: expr '+' expr @{ $$ = $1 + $3; @}
620 The action says how to produce the semantic value of the sum expression
621 from the values of the two subexpressions.
624 @section Writing GLR Parsers
626 @cindex generalized LR (GLR) parsing
629 @cindex shift/reduce conflicts
631 In some grammars, there will be cases where Bison's standard LALR(1)
632 parsing algorithm cannot decide whether to apply a certain grammar rule
633 at a given point. That is, it may not be able to decide (on the basis
634 of the input read so far) which of two possible reductions (applications
635 of a grammar rule) applies, or whether to apply a reduction or read more
636 of the input and apply a reduction later in the input. These are known
637 respectively as @dfn{reduce/reduce} conflicts (@pxref{Reduce/Reduce}),
638 and @dfn{shift/reduce} conflicts (@pxref{Shift/Reduce}).
640 To use a grammar that is not easily modified to be LALR(1), a more
641 general parsing algorithm is sometimes necessary. If you include
642 @code{%glr-parser} among the Bison declarations in your file
643 (@pxref{Grammar Outline}), the result will be a Generalized LR (GLR)
644 parser. These parsers handle Bison grammars that contain no unresolved
645 conflicts (i.e., after applying precedence declarations) identically to
646 LALR(1) parsers. However, when faced with unresolved shift/reduce and
647 reduce/reduce conflicts, GLR parsers use the simple expedient of doing
648 both, effectively cloning the parser to follow both possibilities. Each
649 of the resulting parsers can again split, so that at any given time,
650 there can be any number of possible parses being explored. The parsers
651 proceed in lockstep; that is, all of them consume (shift) a given input
652 symbol before any of them proceed to the next. Each of the cloned
653 parsers eventually meets one of two possible fates: either it runs into
654 a parsing error, in which case it simply vanishes, or it merges with
655 another parser, because the two of them have reduced the input to an
656 identical set of symbols.
658 During the time that there are multiple parsers, semantic actions are
659 recorded, but not performed. When a parser disappears, its recorded
660 semantic actions disappear as well, and are never performed. When a
661 reduction makes two parsers identical, causing them to merge, Bison
662 records both sets of semantic actions. Whenever the last two parsers
663 merge, reverting to the single-parser case, Bison resolves all the
664 outstanding actions either by precedences given to the grammar rules
665 involved, or by performing both actions, and then calling a designated
666 user-defined function on the resulting values to produce an arbitrary
669 Let's consider an example, vastly simplified from C++.
673 #define YYSTYPE const char*
686 | prog stmt @{ printf ("\n"); @}
689 stmt : expr ';' %dprec 1
693 expr : ID @{ printf ("%s ", $$); @}
694 | TYPENAME '(' expr ')'
695 @{ printf ("%s <cast> ", $1); @}
696 | expr '+' expr @{ printf ("+ "); @}
697 | expr '=' expr @{ printf ("= "); @}
700 decl : TYPENAME declarator ';'
701 @{ printf ("%s <declare> ", $1); @}
702 | TYPENAME declarator '=' expr ';'
703 @{ printf ("%s <init-declare> ", $1); @}
706 declarator : ID @{ printf ("\"%s\" ", $1); @}
712 This models a problematic part of the C++ grammar---the ambiguity between
713 certain declarations and statements. For example,
720 parses as either an @code{expr} or a @code{stmt}
721 (assuming that @samp{T} is recognized as a TYPENAME and @samp{x} as an ID).
722 Bison detects this as a reduce/reduce conflict between the rules
723 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
724 time it encounters @code{x} in the example above. The two @code{%dprec}
725 declarations, however, give precedence to interpreting the example as a
726 @code{decl}, which implies that @code{x} is a declarator.
727 The parser therefore prints
730 "x" y z + T <init-declare>
733 Consider a different input string for this parser:
740 Here, there is no ambiguity (this cannot be parsed as a declaration).
741 However, at the time the Bison parser encounters @code{x}, it does not
742 have enough information to resolve the reduce/reduce conflict (again,
743 between @code{x} as an @code{expr} or a @code{declarator}). In this
744 case, no precedence declaration is used. Instead, the parser splits
745 into two, one assuming that @code{x} is an @code{expr}, and the other
746 assuming @code{x} is a @code{declarator}. The second of these parsers
747 then vanishes when it sees @code{+}, and the parser prints
753 Suppose that instead of resolving the ambiguity, you wanted to see all
754 the possibilities. For this purpose, we must @dfn{merge} the semantic
755 actions of the two possible parsers, rather than choosing one over the
756 other. To do so, you could change the declaration of @code{stmt} as
760 stmt : expr ';' %merge <stmtMerge>
761 | decl %merge <stmtMerge>
767 and define the @code{stmtMerge} function as:
770 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1)
778 with an accompanying forward declaration
779 in the C declarations at the beginning of the file:
783 #define YYSTYPE const char*
784 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
789 With these declarations, the resulting parser will parse the first example
790 as both an @code{expr} and a @code{decl}, and print
793 "x" y z + T <init-declare> x T <cast> y z + = <OR>
797 @node Locations Overview
800 @cindex textual position
801 @cindex position, textual
803 Many applications, like interpreters or compilers, have to produce verbose
804 and useful error messages. To achieve this, one must be able to keep track of
805 the @dfn{textual position}, or @dfn{location}, of each syntactic construct.
806 Bison provides a mechanism for handling these locations.
808 Each token has a semantic value. In a similar fashion, each token has an
809 associated location, but the type of locations is the same for all tokens and
810 groupings. Moreover, the output parser is equipped with a default data
811 structure for storing locations (@pxref{Locations}, for more details).
813 Like semantic values, locations can be reached in actions using a dedicated
814 set of constructs. In the example above, the location of the whole grouping
815 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
818 When a rule is matched, a default action is used to compute the semantic value
819 of its left hand side (@pxref{Actions}). In the same way, another default
820 action is used for locations. However, the action for locations is general
821 enough for most cases, meaning there is usually no need to describe for each
822 rule how @code{@@$} should be formed. When building a new location for a given
823 grouping, the default behavior of the output parser is to take the beginning
824 of the first symbol, and the end of the last symbol.
827 @section Bison Output: the Parser File
829 @cindex Bison utility
830 @cindex lexical analyzer, purpose
833 When you run Bison, you give it a Bison grammar file as input. The output
834 is a C source file that parses the language described by the grammar.
835 This file is called a @dfn{Bison parser}. Keep in mind that the Bison
836 utility and the Bison parser are two distinct programs: the Bison utility
837 is a program whose output is the Bison parser that becomes part of your
840 The job of the Bison parser is to group tokens into groupings according to
841 the grammar rules---for example, to build identifiers and operators into
842 expressions. As it does this, it runs the actions for the grammar rules it
845 The tokens come from a function called the @dfn{lexical analyzer} that
846 you must supply in some fashion (such as by writing it in C). The Bison
847 parser calls the lexical analyzer each time it wants a new token. It
848 doesn't know what is ``inside'' the tokens (though their semantic values
849 may reflect this). Typically the lexical analyzer makes the tokens by
850 parsing characters of text, but Bison does not depend on this.
851 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
853 The Bison parser file is C code which defines a function named
854 @code{yyparse} which implements that grammar. This function does not make
855 a complete C program: you must supply some additional functions. One is
856 the lexical analyzer. Another is an error-reporting function which the
857 parser calls to report an error. In addition, a complete C program must
858 start with a function called @code{main}; you have to provide this, and
859 arrange for it to call @code{yyparse} or the parser will never run.
860 @xref{Interface, ,Parser C-Language Interface}.
862 Aside from the token type names and the symbols in the actions you
863 write, all symbols defined in the Bison parser file itself
864 begin with @samp{yy} or @samp{YY}. This includes interface functions
865 such as the lexical analyzer function @code{yylex}, the error reporting
866 function @code{yyerror} and the parser function @code{yyparse} itself.
867 This also includes numerous identifiers used for internal purposes.
868 Therefore, you should avoid using C identifiers starting with @samp{yy}
869 or @samp{YY} in the Bison grammar file except for the ones defined in
872 In some cases the Bison parser file includes system headers, and in
873 those cases your code should respect the identifiers reserved by those
874 headers. On some non-@sc{gnu} hosts, @code{<alloca.h>},
875 @code{<stddef.h>}, and @code{<stdlib.h>} are included as needed to
876 declare memory allocators and related types. Other system headers may
877 be included if you define @code{YYDEBUG} to a nonzero value
878 (@pxref{Tracing, ,Tracing Your Parser}).
881 @section Stages in Using Bison
882 @cindex stages in using Bison
885 The actual language-design process using Bison, from grammar specification
886 to a working compiler or interpreter, has these parts:
890 Formally specify the grammar in a form recognized by Bison
891 (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
892 in the language, describe the action that is to be taken when an
893 instance of that rule is recognized. The action is described by a
894 sequence of C statements.
897 Write a lexical analyzer to process input and pass tokens to the parser.
898 The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
899 Lexical Analyzer Function @code{yylex}}). It could also be produced
900 using Lex, but the use of Lex is not discussed in this manual.
903 Write a controlling function that calls the Bison-produced parser.
906 Write error-reporting routines.
909 To turn this source code as written into a runnable program, you
910 must follow these steps:
914 Run Bison on the grammar to produce the parser.
917 Compile the code output by Bison, as well as any other source files.
920 Link the object files to produce the finished product.
924 @section The Overall Layout of a Bison Grammar
927 @cindex format of grammar file
928 @cindex layout of Bison grammar
930 The input file for the Bison utility is a @dfn{Bison grammar file}. The
931 general form of a Bison grammar file is as follows:
938 @var{Bison declarations}
947 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
948 in every Bison grammar file to separate the sections.
950 The prologue may define types and variables used in the actions. You can
951 also use preprocessor commands to define macros used there, and use
952 @code{#include} to include header files that do any of these things.
954 The Bison declarations declare the names of the terminal and nonterminal
955 symbols, and may also describe operator precedence and the data types of
956 semantic values of various symbols.
958 The grammar rules define how to construct each nonterminal symbol from its
961 The epilogue can contain any code you want to use. Often the definition of
962 the lexical analyzer @code{yylex} goes here, plus subroutines called by the
963 actions in the grammar rules. In a simple program, all the rest of the
968 @cindex simple examples
969 @cindex examples, simple
971 Now we show and explain three sample programs written using Bison: a
972 reverse polish notation calculator, an algebraic (infix) notation
973 calculator, and a multi-function calculator. All three have been tested
974 under BSD Unix 4.3; each produces a usable, though limited, interactive
977 These examples are simple, but Bison grammars for real programming
978 languages are written the same way.
980 You can copy these examples out of the Info file and into a source file
985 * RPN Calc:: Reverse polish notation calculator;
986 a first example with no operator precedence.
987 * Infix Calc:: Infix (algebraic) notation calculator.
988 Operator precedence is introduced.
989 * Simple Error Recovery:: Continuing after syntax errors.
990 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
991 * Multi-function Calc:: Calculator with memory and trig functions.
992 It uses multiple data-types for semantic values.
993 * Exercises:: Ideas for improving the multi-function calculator.
997 @section Reverse Polish Notation Calculator
998 @cindex reverse polish notation
999 @cindex polish notation calculator
1000 @cindex @code{rpcalc}
1001 @cindex calculator, simple
1003 The first example is that of a simple double-precision @dfn{reverse polish
1004 notation} calculator (a calculator using postfix operators). This example
1005 provides a good starting point, since operator precedence is not an issue.
1006 The second example will illustrate how operator precedence is handled.
1008 The source code for this calculator is named @file{rpcalc.y}. The
1009 @samp{.y} extension is a convention used for Bison input files.
1012 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
1013 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1014 * Lexer: Rpcalc Lexer. The lexical analyzer.
1015 * Main: Rpcalc Main. The controlling function.
1016 * Error: Rpcalc Error. The error reporting function.
1017 * Gen: Rpcalc Gen. Running Bison on the grammar file.
1018 * Comp: Rpcalc Compile. Run the C compiler on the output code.
1022 @subsection Declarations for @code{rpcalc}
1024 Here are the C and Bison declarations for the reverse polish notation
1025 calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1028 /* Reverse polish notation calculator. */
1031 #define YYSTYPE double
1037 %% /* Grammar rules and actions follow */
1040 The declarations section (@pxref{Prologue, , The prologue}) contains two
1041 preprocessor directives.
1043 The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1044 specifying the C data type for semantic values of both tokens and
1045 groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1046 Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1047 don't define it, @code{int} is the default. Because we specify
1048 @code{double}, each token and each expression has an associated value,
1049 which is a floating point number.
1051 The @code{#include} directive is used to declare the exponentiation
1052 function @code{pow}.
1054 The second section, Bison declarations, provides information to Bison
1055 about the token types (@pxref{Bison Declarations, ,The Bison
1056 Declarations Section}). Each terminal symbol that is not a
1057 single-character literal must be declared here. (Single-character
1058 literals normally don't need to be declared.) In this example, all the
1059 arithmetic operators are designated by single-character literals, so the
1060 only terminal symbol that needs to be declared is @code{NUM}, the token
1061 type for numeric constants.
1064 @subsection Grammar Rules for @code{rpcalc}
1066 Here are the grammar rules for the reverse polish notation calculator.
1074 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1077 exp: NUM @{ $$ = $1; @}
1078 | exp exp '+' @{ $$ = $1 + $2; @}
1079 | exp exp '-' @{ $$ = $1 - $2; @}
1080 | exp exp '*' @{ $$ = $1 * $2; @}
1081 | exp exp '/' @{ $$ = $1 / $2; @}
1082 /* Exponentiation */
1083 | exp exp '^' @{ $$ = pow ($1, $2); @}
1085 | exp 'n' @{ $$ = -$1; @}
1090 The groupings of the rpcalc ``language'' defined here are the expression
1091 (given the name @code{exp}), the line of input (@code{line}), and the
1092 complete input transcript (@code{input}). Each of these nonterminal
1093 symbols has several alternate rules, joined by the @samp{|} punctuator
1094 which is read as ``or''. The following sections explain what these rules
1097 The semantics of the language is determined by the actions taken when a
1098 grouping is recognized. The actions are the C code that appears inside
1099 braces. @xref{Actions}.
1101 You must specify these actions in C, but Bison provides the means for
1102 passing semantic values between the rules. In each action, the
1103 pseudo-variable @code{$$} stands for the semantic value for the grouping
1104 that the rule is going to construct. Assigning a value to @code{$$} is the
1105 main job of most actions. The semantic values of the components of the
1106 rule are referred to as @code{$1}, @code{$2}, and so on.
1115 @subsubsection Explanation of @code{input}
1117 Consider the definition of @code{input}:
1125 This definition reads as follows: ``A complete input is either an empty
1126 string, or a complete input followed by an input line''. Notice that
1127 ``complete input'' is defined in terms of itself. This definition is said
1128 to be @dfn{left recursive} since @code{input} appears always as the
1129 leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1131 The first alternative is empty because there are no symbols between the
1132 colon and the first @samp{|}; this means that @code{input} can match an
1133 empty string of input (no tokens). We write the rules this way because it
1134 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1135 It's conventional to put an empty alternative first and write the comment
1136 @samp{/* empty */} in it.
1138 The second alternate rule (@code{input line}) handles all nontrivial input.
1139 It means, ``After reading any number of lines, read one more line if
1140 possible.'' The left recursion makes this rule into a loop. Since the
1141 first alternative matches empty input, the loop can be executed zero or
1144 The parser function @code{yyparse} continues to process input until a
1145 grammatical error is seen or the lexical analyzer says there are no more
1146 input tokens; we will arrange for the latter to happen at end of file.
1149 @subsubsection Explanation of @code{line}
1151 Now consider the definition of @code{line}:
1155 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1159 The first alternative is a token which is a newline character; this means
1160 that rpcalc accepts a blank line (and ignores it, since there is no
1161 action). The second alternative is an expression followed by a newline.
1162 This is the alternative that makes rpcalc useful. The semantic value of
1163 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1164 question is the first symbol in the alternative. The action prints this
1165 value, which is the result of the computation the user asked for.
1167 This action is unusual because it does not assign a value to @code{$$}. As
1168 a consequence, the semantic value associated with the @code{line} is
1169 uninitialized (its value will be unpredictable). This would be a bug if
1170 that value were ever used, but we don't use it: once rpcalc has printed the
1171 value of the user's input line, that value is no longer needed.
1174 @subsubsection Explanation of @code{expr}
1176 The @code{exp} grouping has several rules, one for each kind of expression.
1177 The first rule handles the simplest expressions: those that are just numbers.
1178 The second handles an addition-expression, which looks like two expressions
1179 followed by a plus-sign. The third handles subtraction, and so on.
1183 | exp exp '+' @{ $$ = $1 + $2; @}
1184 | exp exp '-' @{ $$ = $1 - $2; @}
1189 We have used @samp{|} to join all the rules for @code{exp}, but we could
1190 equally well have written them separately:
1194 exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1195 exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1199 Most of the rules have actions that compute the value of the expression in
1200 terms of the value of its parts. For example, in the rule for addition,
1201 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1202 the second one. The third component, @code{'+'}, has no meaningful
1203 associated semantic value, but if it had one you could refer to it as
1204 @code{$3}. When @code{yyparse} recognizes a sum expression using this
1205 rule, the sum of the two subexpressions' values is produced as the value of
1206 the entire expression. @xref{Actions}.
1208 You don't have to give an action for every rule. When a rule has no
1209 action, Bison by default copies the value of @code{$1} into @code{$$}.
1210 This is what happens in the first rule (the one that uses @code{NUM}).
1212 The formatting shown here is the recommended convention, but Bison does
1213 not require it. You can add or change whitespace as much as you wish.
1217 exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{}
1221 means the same thing as this:
1225 | exp exp '+' @{ $$ = $1 + $2; @}
1230 The latter, however, is much more readable.
1233 @subsection The @code{rpcalc} Lexical Analyzer
1234 @cindex writing a lexical analyzer
1235 @cindex lexical analyzer, writing
1237 The lexical analyzer's job is low-level parsing: converting characters
1238 or sequences of characters into tokens. The Bison parser gets its
1239 tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1240 Analyzer Function @code{yylex}}.
1242 Only a simple lexical analyzer is needed for the RPN calculator. This
1243 lexical analyzer skips blanks and tabs, then reads in numbers as
1244 @code{double} and returns them as @code{NUM} tokens. Any other character
1245 that isn't part of a number is a separate token. Note that the token-code
1246 for such a single-character token is the character itself.
1248 The return value of the lexical analyzer function is a numeric code which
1249 represents a token type. The same text used in Bison rules to stand for
1250 this token type is also a C expression for the numeric code for the type.
1251 This works in two ways. If the token type is a character literal, then its
1252 numeric code is that of the character; you can use the same
1253 character literal in the lexical analyzer to express the number. If the
1254 token type is an identifier, that identifier is defined by Bison as a C
1255 macro whose definition is the appropriate number. In this example,
1256 therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1258 The semantic value of the token (if it has one) is stored into the
1259 global variable @code{yylval}, which is where the Bison parser will look
1260 for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1261 defined at the beginning of the grammar; @pxref{Rpcalc Decls,
1262 ,Declarations for @code{rpcalc}}.)
1264 A token type code of zero is returned if the end-of-file is encountered.
1265 (Bison recognizes any nonpositive value as indicating the end of the
1268 Here is the code for the lexical analyzer:
1272 /* Lexical analyzer returns a double floating point
1273 number on the stack and the token NUM, or the numeric code
1274 of the character read if not a number. Skips all blanks
1275 and tabs, returns 0 for EOF. */
1286 /* skip white space */
1287 while ((c = getchar ()) == ' ' || c == '\t')
1291 /* process numbers */
1292 if (c == '.' || isdigit (c))
1295 scanf ("%lf", &yylval);
1300 /* return end-of-file */
1303 /* return single chars */
1310 @subsection The Controlling Function
1311 @cindex controlling function
1312 @cindex main function in simple example
1314 In keeping with the spirit of this example, the controlling function is
1315 kept to the bare minimum. The only requirement is that it call
1316 @code{yyparse} to start the process of parsing.
1329 @subsection The Error Reporting Routine
1330 @cindex error reporting routine
1332 When @code{yyparse} detects a syntax error, it calls the error reporting
1333 function @code{yyerror} to print an error message (usually but not
1334 always @code{"parse error"}). It is up to the programmer to supply
1335 @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1336 here is the definition we will use:
1343 yyerror (const char *s) /* Called by yyparse on error */
1350 After @code{yyerror} returns, the Bison parser may recover from the error
1351 and continue parsing if the grammar contains a suitable error rule
1352 (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1353 have not written any error rules in this example, so any invalid input will
1354 cause the calculator program to exit. This is not clean behavior for a
1355 real calculator, but it is adequate for the first example.
1358 @subsection Running Bison to Make the Parser
1359 @cindex running Bison (introduction)
1361 Before running Bison to produce a parser, we need to decide how to
1362 arrange all the source code in one or more source files. For such a
1363 simple example, the easiest thing is to put everything in one file. The
1364 definitions of @code{yylex}, @code{yyerror} and @code{main} go at the
1365 end, in the epilogue of the file
1366 (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1368 For a large project, you would probably have several source files, and use
1369 @code{make} to arrange to recompile them.
1371 With all the source in a single file, you use the following command to
1372 convert it into a parser file:
1375 bison @var{file_name}.y
1379 In this example the file was called @file{rpcalc.y} (for ``Reverse Polish
1380 CALCulator''). Bison produces a file named @file{@var{file_name}.tab.c},
1381 removing the @samp{.y} from the original file name. The file output by
1382 Bison contains the source code for @code{yyparse}. The additional
1383 functions in the input file (@code{yylex}, @code{yyerror} and @code{main})
1384 are copied verbatim to the output.
1386 @node Rpcalc Compile
1387 @subsection Compiling the Parser File
1388 @cindex compiling the parser
1390 Here is how to compile and run the parser file:
1394 # @r{List files in current directory.}
1396 rpcalc.tab.c rpcalc.y
1400 # @r{Compile the Bison parser.}
1401 # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1402 $ @kbd{cc rpcalc.tab.c -lm -o rpcalc}
1406 # @r{List files again.}
1408 rpcalc rpcalc.tab.c rpcalc.y
1412 The file @file{rpcalc} now contains the executable code. Here is an
1413 example session using @code{rpcalc}.
1419 @kbd{3 7 + 3 4 5 *+-}
1421 @kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
1425 @kbd{3 4 ^} @r{Exponentiation}
1427 @kbd{^D} @r{End-of-file indicator}
1432 @section Infix Notation Calculator: @code{calc}
1433 @cindex infix notation calculator
1435 @cindex calculator, infix notation
1437 We now modify rpcalc to handle infix operators instead of postfix. Infix
1438 notation involves the concept of operator precedence and the need for
1439 parentheses nested to arbitrary depth. Here is the Bison code for
1440 @file{calc.y}, an infix desk-top calculator.
1443 /* Infix notation calculator--calc */
1446 #define YYSTYPE double
1450 /* BISON Declarations */
1454 %left NEG /* negation--unary minus */
1455 %right '^' /* exponentiation */
1457 /* Grammar follows */
1459 input: /* empty string */
1464 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1467 exp: NUM @{ $$ = $1; @}
1468 | exp '+' exp @{ $$ = $1 + $3; @}
1469 | exp '-' exp @{ $$ = $1 - $3; @}
1470 | exp '*' exp @{ $$ = $1 * $3; @}
1471 | exp '/' exp @{ $$ = $1 / $3; @}
1472 | '-' exp %prec NEG @{ $$ = -$2; @}
1473 | exp '^' exp @{ $$ = pow ($1, $3); @}
1474 | '(' exp ')' @{ $$ = $2; @}
1480 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1483 There are two important new features shown in this code.
1485 In the second section (Bison declarations), @code{%left} declares token
1486 types and says they are left-associative operators. The declarations
1487 @code{%left} and @code{%right} (right associativity) take the place of
1488 @code{%token} which is used to declare a token type name without
1489 associativity. (These tokens are single-character literals, which
1490 ordinarily don't need to be declared. We declare them here to specify
1493 Operator precedence is determined by the line ordering of the
1494 declarations; the higher the line number of the declaration (lower on
1495 the page or screen), the higher the precedence. Hence, exponentiation
1496 has the highest precedence, unary minus (@code{NEG}) is next, followed
1497 by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator
1500 The other important new feature is the @code{%prec} in the grammar
1501 section for the unary minus operator. The @code{%prec} simply instructs
1502 Bison that the rule @samp{| '-' exp} has the same precedence as
1503 @code{NEG}---in this case the next-to-highest. @xref{Contextual
1504 Precedence, ,Context-Dependent Precedence}.
1506 Here is a sample run of @file{calc.y}:
1511 @kbd{4 + 4.5 - (34/(8*3+-3))}
1519 @node Simple Error Recovery
1520 @section Simple Error Recovery
1521 @cindex error recovery, simple
1523 Up to this point, this manual has not addressed the issue of @dfn{error
1524 recovery}---how to continue parsing after the parser detects a syntax
1525 error. All we have handled is error reporting with @code{yyerror}.
1526 Recall that by default @code{yyparse} returns after calling
1527 @code{yyerror}. This means that an erroneous input line causes the
1528 calculator program to exit. Now we show how to rectify this deficiency.
1530 The Bison language itself includes the reserved word @code{error}, which
1531 may be included in the grammar rules. In the example below it has
1532 been added to one of the alternatives for @code{line}:
1537 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1538 | error '\n' @{ yyerrok; @}
1543 This addition to the grammar allows for simple error recovery in the
1544 event of a parse error. If an expression that cannot be evaluated is
1545 read, the error will be recognized by the third rule for @code{line},
1546 and parsing will continue. (The @code{yyerror} function is still called
1547 upon to print its message as well.) The action executes the statement
1548 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
1549 that error recovery is complete (@pxref{Error Recovery}). Note the
1550 difference between @code{yyerrok} and @code{yyerror}; neither one is a
1553 This form of error recovery deals with syntax errors. There are other
1554 kinds of errors; for example, division by zero, which raises an exception
1555 signal that is normally fatal. A real calculator program must handle this
1556 signal and use @code{longjmp} to return to @code{main} and resume parsing
1557 input lines; it would also have to discard the rest of the current line of
1558 input. We won't discuss this issue further because it is not specific to
1561 @node Location Tracking Calc
1562 @section Location Tracking Calculator: @code{ltcalc}
1563 @cindex location tracking calculator
1564 @cindex @code{ltcalc}
1565 @cindex calculator, location tracking
1567 This example extends the infix notation calculator with location
1568 tracking. This feature will be used to improve the error messages. For
1569 the sake of clarity, this example is a simple integer calculator, since
1570 most of the work needed to use locations will be done in the lexical
1574 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
1575 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
1576 * Lexer: Ltcalc Lexer. The lexical analyzer.
1580 @subsection Declarations for @code{ltcalc}
1582 The C and Bison declarations for the location tracking calculator are
1583 the same as the declarations for the infix notation calculator.
1586 /* Location tracking calculator. */
1593 /* Bison declarations. */
1601 %% /* Grammar follows */
1605 Note there are no declarations specific to locations. Defining a data
1606 type for storing locations is not needed: we will use the type provided
1607 by default (@pxref{Location Type, ,Data Types of Locations}), which is a
1608 four member structure with the following integer fields:
1609 @code{first_line}, @code{first_column}, @code{last_line} and
1613 @subsection Grammar Rules for @code{ltcalc}
1615 Whether handling locations or not has no effect on the syntax of your
1616 language. Therefore, grammar rules for this example will be very close
1617 to those of the previous example: we will only modify them to benefit
1618 from the new information.
1620 Here, we will use locations to report divisions by zero, and locate the
1621 wrong expressions or subexpressions.
1632 | exp '\n' @{ printf ("%d\n", $1); @}
1637 exp : NUM @{ $$ = $1; @}
1638 | exp '+' exp @{ $$ = $1 + $3; @}
1639 | exp '-' exp @{ $$ = $1 - $3; @}
1640 | exp '*' exp @{ $$ = $1 * $3; @}
1650 fprintf (stderr, "%d.%d-%d.%d: division by zero",
1651 @@3.first_line, @@3.first_column,
1652 @@3.last_line, @@3.last_column);
1657 | '-' exp %preg NEG @{ $$ = -$2; @}
1658 | exp '^' exp @{ $$ = pow ($1, $3); @}
1659 | '(' exp ')' @{ $$ = $2; @}
1663 This code shows how to reach locations inside of semantic actions, by
1664 using the pseudo-variables @code{@@@var{n}} for rule components, and the
1665 pseudo-variable @code{@@$} for groupings.
1667 We don't need to assign a value to @code{@@$}: the output parser does it
1668 automatically. By default, before executing the C code of each action,
1669 @code{@@$} is set to range from the beginning of @code{@@1} to the end
1670 of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
1671 can be redefined (@pxref{Location Default Action, , Default Action for
1672 Locations}), and for very specific rules, @code{@@$} can be computed by
1676 @subsection The @code{ltcalc} Lexical Analyzer.
1678 Until now, we relied on Bison's defaults to enable location
1679 tracking. The next step is to rewrite the lexical analyser, and make it
1680 able to feed the parser with the token locations, as it already does for
1683 To this end, we must take into account every single character of the
1684 input text, to avoid the computed locations of being fuzzy or wrong:
1693 /* skip white space */
1694 while ((c = getchar ()) == ' ' || c == '\t')
1695 ++yylloc.last_column;
1698 yylloc.first_line = yylloc.last_line;
1699 yylloc.first_column = yylloc.last_column;
1703 /* process numbers */
1707 ++yylloc.last_column;
1708 while (isdigit (c = getchar ()))
1710 ++yylloc.last_column;
1711 yylval = yylval * 10 + c - '0';
1718 /* return end-of-file */
1722 /* return single chars and update location */
1726 yylloc.last_column = 0;
1729 ++yylloc.last_column;
1734 Basically, the lexical analyzer performs the same processing as before:
1735 it skips blanks and tabs, and reads numbers or single-character tokens.
1736 In addition, it updates @code{yylloc}, the global variable (of type
1737 @code{YYLTYPE}) containing the token's location.
1739 Now, each time this function returns a token, the parser has its number
1740 as well as its semantic value, and its location in the text. The last
1741 needed change is to initialize @code{yylloc}, for example in the
1742 controlling function:
1749 yylloc.first_line = yylloc.last_line = 1;
1750 yylloc.first_column = yylloc.last_column = 0;
1756 Remember that computing locations is not a matter of syntax. Every
1757 character must be associated to a location update, whether it is in
1758 valid input, in comments, in literal strings, and so on.
1760 @node Multi-function Calc
1761 @section Multi-Function Calculator: @code{mfcalc}
1762 @cindex multi-function calculator
1763 @cindex @code{mfcalc}
1764 @cindex calculator, multi-function
1766 Now that the basics of Bison have been discussed, it is time to move on to
1767 a more advanced problem. The above calculators provided only five
1768 functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
1769 be nice to have a calculator that provides other mathematical functions such
1770 as @code{sin}, @code{cos}, etc.
1772 It is easy to add new operators to the infix calculator as long as they are
1773 only single-character literals. The lexical analyzer @code{yylex} passes
1774 back all nonnumber characters as tokens, so new grammar rules suffice for
1775 adding a new operator. But we want something more flexible: built-in
1776 functions whose syntax has this form:
1779 @var{function_name} (@var{argument})
1783 At the same time, we will add memory to the calculator, by allowing you
1784 to create named variables, store values in them, and use them later.
1785 Here is a sample session with the multi-function calculator:
1789 @kbd{pi = 3.141592653589}
1793 @kbd{alpha = beta1 = 2.3}
1799 @kbd{exp(ln(beta1))}
1804 Note that multiple assignment and nested function calls are permitted.
1807 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
1808 * Rules: Mfcalc Rules. Grammar rules for the calculator.
1809 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
1813 @subsection Declarations for @code{mfcalc}
1815 Here are the C and Bison declarations for the multi-function calculator.
1819 #include <math.h> /* For math functions, cos(), sin(), etc. */
1820 #include "calc.h" /* Contains definition of `symrec' */
1823 double val; /* For returning numbers. */
1824 symrec *tptr; /* For returning symbol-table pointers */
1827 %token <val> NUM /* Simple double precision number */
1828 %token <tptr> VAR FNCT /* Variable and Function */
1834 %left NEG /* Negation--unary minus */
1835 %right '^' /* Exponentiation */
1837 /* Grammar follows */
1842 The above grammar introduces only two new features of the Bison language.
1843 These features allow semantic values to have various data types
1844 (@pxref{Multiple Types, ,More Than One Value Type}).
1846 The @code{%union} declaration specifies the entire list of possible types;
1847 this is instead of defining @code{YYSTYPE}. The allowable types are now
1848 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
1849 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
1851 Since values can now have various types, it is necessary to associate a
1852 type with each grammar symbol whose semantic value is used. These symbols
1853 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
1854 declarations are augmented with information about their data type (placed
1855 between angle brackets).
1857 The Bison construct @code{%type} is used for declaring nonterminal
1858 symbols, just as @code{%token} is used for declaring token types. We
1859 have not used @code{%type} before because nonterminal symbols are
1860 normally declared implicitly by the rules that define them. But
1861 @code{exp} must be declared explicitly so we can specify its value type.
1862 @xref{Type Decl, ,Nonterminal Symbols}.
1865 @subsection Grammar Rules for @code{mfcalc}
1867 Here are the grammar rules for the multi-function calculator.
1868 Most of them are copied directly from @code{calc}; three rules,
1869 those which mention @code{VAR} or @code{FNCT}, are new.
1878 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1879 | error '\n' @{ yyerrok; @}
1882 exp: NUM @{ $$ = $1; @}
1883 | VAR @{ $$ = $1->value.var; @}
1884 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
1885 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
1886 | exp '+' exp @{ $$ = $1 + $3; @}
1887 | exp '-' exp @{ $$ = $1 - $3; @}
1888 | exp '*' exp @{ $$ = $1 * $3; @}
1889 | exp '/' exp @{ $$ = $1 / $3; @}
1890 | '-' exp %prec NEG @{ $$ = -$2; @}
1891 | exp '^' exp @{ $$ = pow ($1, $3); @}
1892 | '(' exp ')' @{ $$ = $2; @}
1894 /* End of grammar */
1899 @subsection The @code{mfcalc} Symbol Table
1900 @cindex symbol table example
1902 The multi-function calculator requires a symbol table to keep track of the
1903 names and meanings of variables and functions. This doesn't affect the
1904 grammar rules (except for the actions) or the Bison declarations, but it
1905 requires some additional C functions for support.
1907 The symbol table itself consists of a linked list of records. Its
1908 definition, which is kept in the header @file{calc.h}, is as follows. It
1909 provides for either functions or variables to be placed in the table.
1913 /* Fonctions type. */
1914 typedef double (*func_t) (double);
1916 /* Data type for links in the chain of symbols. */
1919 char *name; /* name of symbol */
1920 int type; /* type of symbol: either VAR or FNCT */
1923 double var; /* value of a VAR */
1924 func_t fnctptr; /* value of a FNCT */
1926 struct symrec *next; /* link field */
1931 typedef struct symrec symrec;
1933 /* The symbol table: a chain of `struct symrec'. */
1934 extern symrec *sym_table;
1936 symrec *putsym (const char *, func_t);
1937 symrec *getsym (const char *);
1941 The new version of @code{main} includes a call to @code{init_table}, a
1942 function that initializes the symbol table. Here it is, and
1943 @code{init_table} as well:
1959 yyerror (const char *s) /* Called by yyparse on error */
1967 double (*fnct)(double);
1972 struct init arith_fncts[] =
1983 /* The symbol table: a chain of `struct symrec'. */
1984 symrec *sym_table = (symrec *) 0;
1988 /* Put arithmetic functions in table. */
1994 for (i = 0; arith_fncts[i].fname != 0; i++)
1996 ptr = putsym (arith_fncts[i].fname, FNCT);
1997 ptr->value.fnctptr = arith_fncts[i].fnct;
2003 By simply editing the initialization list and adding the necessary include
2004 files, you can add additional functions to the calculator.
2006 Two important functions allow look-up and installation of symbols in the
2007 symbol table. The function @code{putsym} is passed a name and the type
2008 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2009 linked to the front of the list, and a pointer to the object is returned.
2010 The function @code{getsym} is passed the name of the symbol to look up. If
2011 found, a pointer to that symbol is returned; otherwise zero is returned.
2015 putsym (char *sym_name, int sym_type)
2018 ptr = (symrec *) malloc (sizeof (symrec));
2019 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2020 strcpy (ptr->name,sym_name);
2021 ptr->type = sym_type;
2022 ptr->value.var = 0; /* set value to 0 even if fctn. */
2023 ptr->next = (struct symrec *)sym_table;
2029 getsym (const char *sym_name)
2032 for (ptr = sym_table; ptr != (symrec *) 0;
2033 ptr = (symrec *)ptr->next)
2034 if (strcmp (ptr->name,sym_name) == 0)
2040 The function @code{yylex} must now recognize variables, numeric values, and
2041 the single-character arithmetic operators. Strings of alphanumeric
2042 characters with a leading non-digit are recognized as either variables or
2043 functions depending on what the symbol table says about them.
2045 The string is passed to @code{getsym} for look up in the symbol table. If
2046 the name appears in the table, a pointer to its location and its type
2047 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2048 already in the table, then it is installed as a @code{VAR} using
2049 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2050 returned to @code{yyparse}.
2052 No change is needed in the handling of numeric values and arithmetic
2053 operators in @code{yylex}.
2064 /* Ignore whitespace, get first nonwhite character. */
2065 while ((c = getchar ()) == ' ' || c == '\t');
2072 /* Char starts a number => parse the number. */
2073 if (c == '.' || isdigit (c))
2076 scanf ("%lf", &yylval.val);
2082 /* Char starts an identifier => read the name. */
2086 static char *symbuf = 0;
2087 static int length = 0;
2092 /* Initially make the buffer long enough
2093 for a 40-character symbol name. */
2095 length = 40, symbuf = (char *)malloc (length + 1);
2102 /* If buffer is full, make it bigger. */
2106 symbuf = (char *)realloc (symbuf, length + 1);
2108 /* Add this character to the buffer. */
2110 /* Get another character. */
2115 while (c != EOF && isalnum (c));
2122 s = getsym (symbuf);
2124 s = putsym (symbuf, VAR);
2129 /* Any other character is a token by itself. */
2135 This program is both powerful and flexible. You may easily add new
2136 functions, and it is a simple job to modify this code to install
2137 predefined variables such as @code{pi} or @code{e} as well.
2145 Add some new functions from @file{math.h} to the initialization list.
2148 Add another array that contains constants and their values. Then
2149 modify @code{init_table} to add these constants to the symbol table.
2150 It will be easiest to give the constants type @code{VAR}.
2153 Make the program report an error if the user refers to an
2154 uninitialized variable in any way except to store a value in it.
2158 @chapter Bison Grammar Files
2160 Bison takes as input a context-free grammar specification and produces a
2161 C-language function that recognizes correct instances of the grammar.
2163 The Bison grammar input file conventionally has a name ending in @samp{.y}.
2164 @xref{Invocation, ,Invoking Bison}.
2167 * Grammar Outline:: Overall layout of the grammar file.
2168 * Symbols:: Terminal and nonterminal symbols.
2169 * Rules:: How to write grammar rules.
2170 * Recursion:: Writing recursive rules.
2171 * Semantics:: Semantic values and actions.
2172 * Locations:: Locations and actions.
2173 * Declarations:: All kinds of Bison declarations are described here.
2174 * Multiple Parsers:: Putting more than one Bison parser in one program.
2177 @node Grammar Outline
2178 @section Outline of a Bison Grammar
2180 A Bison grammar file has four main sections, shown here with the
2181 appropriate delimiters:
2188 @var{Bison declarations}
2197 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2200 * Prologue:: Syntax and usage of the prologue.
2201 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2202 * Grammar Rules:: Syntax and usage of the grammar rules section.
2203 * Epilogue:: Syntax and usage of the epilogue.
2206 @node Prologue, Bison Declarations, , Grammar Outline
2207 @subsection The prologue
2208 @cindex declarations section
2210 @cindex declarations
2212 The @var{Prologue} section contains macro definitions and
2213 declarations of functions and variables that are used in the actions in the
2214 grammar rules. These are copied to the beginning of the parser file so
2215 that they precede the definition of @code{yyparse}. You can use
2216 @samp{#include} to get the declarations from a header file. If you don't
2217 need any C declarations, you may omit the @samp{%@{} and @samp{%@}}
2218 delimiters that bracket this section.
2220 You may have more than one @var{Prologue} section, intermixed with the
2221 @var{Bison declarations}. This allows you to have C and Bison
2222 declarations that refer to each other. For example, the @code{%union}
2223 declaration may use types defined in a header file, and you may wish to
2224 prototype functions that take arguments of type @code{YYSTYPE}. This
2225 can be done with two @var{Prologue} blocks, one before and one after the
2226 @code{%union} declaration.
2236 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2240 static void yyprint(FILE *, int, YYSTYPE);
2241 #define YYPRINT(F, N, L) yyprint(F, N, L)
2247 @node Bison Declarations
2248 @subsection The Bison Declarations Section
2249 @cindex Bison declarations (introduction)
2250 @cindex declarations, Bison (introduction)
2252 The @var{Bison declarations} section contains declarations that define
2253 terminal and nonterminal symbols, specify precedence, and so on.
2254 In some simple grammars you may not need any declarations.
2255 @xref{Declarations, ,Bison Declarations}.
2258 @subsection The Grammar Rules Section
2259 @cindex grammar rules section
2260 @cindex rules section for grammar
2262 The @dfn{grammar rules} section contains one or more Bison grammar
2263 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
2265 There must always be at least one grammar rule, and the first
2266 @samp{%%} (which precedes the grammar rules) may never be omitted even
2267 if it is the first thing in the file.
2269 @node Epilogue, , Grammar Rules, Grammar Outline
2270 @subsection The epilogue
2271 @cindex additional C code section
2273 @cindex C code, section for additional
2275 The @var{Epilogue} is copied verbatim to the end of the parser file, just as
2276 the @var{Prologue} is copied to the beginning. This is the most convenient
2277 place to put anything that you want to have in the parser file but which need
2278 not come before the definition of @code{yyparse}. For example, the
2279 definitions of @code{yylex} and @code{yyerror} often go here.
2280 @xref{Interface, ,Parser C-Language Interface}.
2282 If the last section is empty, you may omit the @samp{%%} that separates it
2283 from the grammar rules.
2285 The Bison parser itself contains many static variables whose names start
2286 with @samp{yy} and many macros whose names start with @samp{YY}. It is a
2287 good idea to avoid using any such names (except those documented in this
2288 manual) in the epilogue of the grammar file.
2291 @section Symbols, Terminal and Nonterminal
2292 @cindex nonterminal symbol
2293 @cindex terminal symbol
2297 @dfn{Symbols} in Bison grammars represent the grammatical classifications
2300 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
2301 class of syntactically equivalent tokens. You use the symbol in grammar
2302 rules to mean that a token in that class is allowed. The symbol is
2303 represented in the Bison parser by a numeric code, and the @code{yylex}
2304 function returns a token type code to indicate what kind of token has been
2305 read. You don't need to know what the code value is; you can use the
2306 symbol to stand for it.
2308 A @dfn{nonterminal symbol} stands for a class of syntactically equivalent
2309 groupings. The symbol name is used in writing grammar rules. By convention,
2310 it should be all lower case.
2312 Symbol names can contain letters, digits (not at the beginning),
2313 underscores and periods. Periods make sense only in nonterminals.
2315 There are three ways of writing terminal symbols in the grammar:
2319 A @dfn{named token type} is written with an identifier, like an
2320 identifier in C. By convention, it should be all upper case. Each
2321 such name must be defined with a Bison declaration such as
2322 @code{%token}. @xref{Token Decl, ,Token Type Names}.
2325 @cindex character token
2326 @cindex literal token
2327 @cindex single-character literal
2328 A @dfn{character token type} (or @dfn{literal character token}) is
2329 written in the grammar using the same syntax used in C for character
2330 constants; for example, @code{'+'} is a character token type. A
2331 character token type doesn't need to be declared unless you need to
2332 specify its semantic value data type (@pxref{Value Type, ,Data Types of
2333 Semantic Values}), associativity, or precedence (@pxref{Precedence,
2334 ,Operator Precedence}).
2336 By convention, a character token type is used only to represent a
2337 token that consists of that particular character. Thus, the token
2338 type @code{'+'} is used to represent the character @samp{+} as a
2339 token. Nothing enforces this convention, but if you depart from it,
2340 your program will confuse other readers.
2342 All the usual escape sequences used in character literals in C can be
2343 used in Bison as well, but you must not use the null character as a
2344 character literal because its numeric code, zero, is the code @code{yylex}
2345 returns for end-of-input (@pxref{Calling Convention, ,Calling Convention
2349 @cindex string token
2350 @cindex literal string token
2351 @cindex multicharacter literal
2352 A @dfn{literal string token} is written like a C string constant; for
2353 example, @code{"<="} is a literal string token. A literal string token
2354 doesn't need to be declared unless you need to specify its semantic
2355 value data type (@pxref{Value Type}), associativity, or precedence
2356 (@pxref{Precedence}).
2358 You can associate the literal string token with a symbolic name as an
2359 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
2360 Declarations}). If you don't do that, the lexical analyzer has to
2361 retrieve the token number for the literal string token from the
2362 @code{yytname} table (@pxref{Calling Convention}).
2364 @strong{WARNING}: literal string tokens do not work in Yacc.
2366 By convention, a literal string token is used only to represent a token
2367 that consists of that particular string. Thus, you should use the token
2368 type @code{"<="} to represent the string @samp{<=} as a token. Bison
2369 does not enforce this convention, but if you depart from it, people who
2370 read your program will be confused.
2372 All the escape sequences used in string literals in C can be used in
2373 Bison as well. A literal string token must contain two or more
2374 characters; for a token containing just one character, use a character
2378 How you choose to write a terminal symbol has no effect on its
2379 grammatical meaning. That depends only on where it appears in rules and
2380 on when the parser function returns that symbol.
2382 The value returned by @code{yylex} is always one of the terminal symbols
2383 (or 0 for end-of-input). Whichever way you write the token type in the
2384 grammar rules, you write it the same way in the definition of @code{yylex}.
2385 The numeric code for a character token type is simply the numeric code of
2386 the character, so @code{yylex} can use the identical character constant to
2387 generate the requisite code. Each named token type becomes a C macro in
2388 the parser file, so @code{yylex} can use the name to stand for the code.
2389 (This is why periods don't make sense in terminal symbols.)
2390 @xref{Calling Convention, ,Calling Convention for @code{yylex}}.
2392 If @code{yylex} is defined in a separate file, you need to arrange for the
2393 token-type macro definitions to be available there. Use the @samp{-d}
2394 option when you run Bison, so that it will write these macro definitions
2395 into a separate header file @file{@var{name}.tab.h} which you can include
2396 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
2398 The @code{yylex} function must use the same character set and encoding
2399 that was used by Bison. For example, if you run Bison in an
2400 @sc{ascii} environment, but then compile and run the resulting program
2401 in an environment that uses an incompatible character set like
2402 @sc{ebcdic}, the resulting program will probably not work because the
2403 tables generated by Bison will assume @sc{ascii} numeric values for
2404 character tokens. Portable grammars should avoid non-@sc{ascii}
2405 character tokens, as implementations in practice often use different
2406 and incompatible extensions in this area. However, it is standard
2407 practice for software distributions to contain C source files that
2408 were generated by Bison in an @sc{ascii} environment, so installers on
2409 platforms that are incompatible with @sc{ascii} must rebuild those
2410 files before compiling them.
2412 The symbol @code{error} is a terminal symbol reserved for error recovery
2413 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
2414 In particular, @code{yylex} should never return this value. The default
2415 value of the error token is 256, unless you explicitly assigned 256 to
2416 one of your tokens with a @code{%token} declaration.
2419 @section Syntax of Grammar Rules
2421 @cindex grammar rule syntax
2422 @cindex syntax of grammar rules
2424 A Bison grammar rule has the following general form:
2428 @var{result}: @var{components}@dots{}
2434 where @var{result} is the nonterminal symbol that this rule describes,
2435 and @var{components} are various terminal and nonterminal symbols that
2436 are put together by this rule (@pxref{Symbols}).
2448 says that two groupings of type @code{exp}, with a @samp{+} token in between,
2449 can be combined into a larger grouping of type @code{exp}.
2451 Whitespace in rules is significant only to separate symbols. You can add
2452 extra whitespace as you wish.
2454 Scattered among the components can be @var{actions} that determine
2455 the semantics of the rule. An action looks like this:
2458 @{@var{C statements}@}
2462 Usually there is only one action and it follows the components.
2466 Multiple rules for the same @var{result} can be written separately or can
2467 be joined with the vertical-bar character @samp{|} as follows:
2471 @var{result}: @var{rule1-components}@dots{}
2472 | @var{rule2-components}@dots{}
2480 @var{result}: @var{rule1-components}@dots{}
2481 | @var{rule2-components}@dots{}
2489 They are still considered distinct rules even when joined in this way.
2491 If @var{components} in a rule is empty, it means that @var{result} can
2492 match the empty string. For example, here is how to define a
2493 comma-separated sequence of zero or more @code{exp} groupings:
2510 It is customary to write a comment @samp{/* empty */} in each rule
2514 @section Recursive Rules
2515 @cindex recursive rule
2517 A rule is called @dfn{recursive} when its @var{result} nonterminal appears
2518 also on its right hand side. Nearly all Bison grammars need to use
2519 recursion, because that is the only way to define a sequence of any number
2520 of a particular thing. Consider this recursive definition of a
2521 comma-separated sequence of one or more expressions:
2531 @cindex left recursion
2532 @cindex right recursion
2534 Since the recursive use of @code{expseq1} is the leftmost symbol in the
2535 right hand side, we call this @dfn{left recursion}. By contrast, here
2536 the same construct is defined using @dfn{right recursion}:
2547 Any kind of sequence can be defined using either left recursion or right
2548 recursion, but you should always use left recursion, because it can
2549 parse a sequence of any number of elements with bounded stack space.
2550 Right recursion uses up space on the Bison stack in proportion to the
2551 number of elements in the sequence, because all the elements must be
2552 shifted onto the stack before the rule can be applied even once.
2553 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
2556 @cindex mutual recursion
2557 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
2558 rule does not appear directly on its right hand side, but does appear
2559 in rules for other nonterminals which do appear on its right hand
2567 | primary '+' primary
2579 defines two mutually-recursive nonterminals, since each refers to the
2583 @section Defining Language Semantics
2584 @cindex defining language semantics
2585 @cindex language semantics, defining
2587 The grammar rules for a language determine only the syntax. The semantics
2588 are determined by the semantic values associated with various tokens and
2589 groupings, and by the actions taken when various groupings are recognized.
2591 For example, the calculator calculates properly because the value
2592 associated with each expression is the proper number; it adds properly
2593 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
2594 the numbers associated with @var{x} and @var{y}.
2597 * Value Type:: Specifying one data type for all semantic values.
2598 * Multiple Types:: Specifying several alternative data types.
2599 * Actions:: An action is the semantic definition of a grammar rule.
2600 * Action Types:: Specifying data types for actions to operate on.
2601 * Mid-Rule Actions:: Most actions go at the end of a rule.
2602 This says when, why and how to use the exceptional
2603 action in the middle of a rule.
2607 @subsection Data Types of Semantic Values
2608 @cindex semantic value type
2609 @cindex value type, semantic
2610 @cindex data types of semantic values
2611 @cindex default data type
2613 In a simple program it may be sufficient to use the same data type for
2614 the semantic values of all language constructs. This was true in the
2615 RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
2616 Notation Calculator}).
2618 Bison's default is to use type @code{int} for all semantic values. To
2619 specify some other type, define @code{YYSTYPE} as a macro, like this:
2622 #define YYSTYPE double
2626 This macro definition must go in the prologue of the grammar file
2627 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
2629 @node Multiple Types
2630 @subsection More Than One Value Type
2632 In most programs, you will need different data types for different kinds
2633 of tokens and groupings. For example, a numeric constant may need type
2634 @code{int} or @code{long}, while a string constant needs type @code{char *},
2635 and an identifier might need a pointer to an entry in the symbol table.
2637 To use more than one data type for semantic values in one parser, Bison
2638 requires you to do two things:
2642 Specify the entire collection of possible data types, with the
2643 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
2647 Choose one of those types for each symbol (terminal or nonterminal) for
2648 which semantic values are used. This is done for tokens with the
2649 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
2650 and for groupings with the @code{%type} Bison declaration (@pxref{Type
2651 Decl, ,Nonterminal Symbols}).
2660 An action accompanies a syntactic rule and contains C code to be executed
2661 each time an instance of that rule is recognized. The task of most actions
2662 is to compute a semantic value for the grouping built by the rule from the
2663 semantic values associated with tokens or smaller groupings.
2665 An action consists of C statements surrounded by braces, much like a
2666 compound statement in C. It can be placed at any position in the rule;
2667 it is executed at that position. Most rules have just one action at the
2668 end of the rule, following all the components. Actions in the middle of
2669 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
2670 Actions, ,Actions in Mid-Rule}).
2672 The C code in an action can refer to the semantic values of the components
2673 matched by the rule with the construct @code{$@var{n}}, which stands for
2674 the value of the @var{n}th component. The semantic value for the grouping
2675 being constructed is @code{$$}. (Bison translates both of these constructs
2676 into array element references when it copies the actions into the parser
2679 Here is a typical example:
2690 This rule constructs an @code{exp} from two smaller @code{exp} groupings
2691 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
2692 refer to the semantic values of the two component @code{exp} groupings,
2693 which are the first and third symbols on the right hand side of the rule.
2694 The sum is stored into @code{$$} so that it becomes the semantic value of
2695 the addition-expression just recognized by the rule. If there were a
2696 useful semantic value associated with the @samp{+} token, it could be
2697 referred to as @code{$2}.
2699 Note that the vertical-bar character @samp{|} is really a rule
2700 separator, and actions are attached to a single rule. This is a
2701 difference with tools like Flex, for which @samp{|} stands for either
2702 ``or'', or ``the same action as that of the next rule''. In the
2703 following example, the action is triggered only when @samp{b} is found:
2707 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
2711 @cindex default action
2712 If you don't specify an action for a rule, Bison supplies a default:
2713 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule becomes
2714 the value of the whole rule. Of course, the default rule is valid only
2715 if the two data types match. There is no meaningful default action for
2716 an empty rule; every empty rule must have an explicit action unless the
2717 rule's value does not matter.
2719 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
2720 to tokens and groupings on the stack @emph{before} those that match the
2721 current rule. This is a very risky practice, and to use it reliably
2722 you must be certain of the context in which the rule is applied. Here
2723 is a case in which you can use this reliably:
2727 foo: expr bar '+' expr @{ @dots{} @}
2728 | expr bar '-' expr @{ @dots{} @}
2734 @{ previous_expr = $0; @}
2739 As long as @code{bar} is used only in the fashion shown here, @code{$0}
2740 always refers to the @code{expr} which precedes @code{bar} in the
2741 definition of @code{foo}.
2744 @subsection Data Types of Values in Actions
2745 @cindex action data types
2746 @cindex data types in actions
2748 If you have chosen a single data type for semantic values, the @code{$$}
2749 and @code{$@var{n}} constructs always have that data type.
2751 If you have used @code{%union} to specify a variety of data types, then you
2752 must declare a choice among these types for each terminal or nonterminal
2753 symbol that can have a semantic value. Then each time you use @code{$$} or
2754 @code{$@var{n}}, its data type is determined by which symbol it refers to
2755 in the rule. In this example,
2766 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
2767 have the data type declared for the nonterminal symbol @code{exp}. If
2768 @code{$2} were used, it would have the data type declared for the
2769 terminal symbol @code{'+'}, whatever that might be.
2771 Alternatively, you can specify the data type when you refer to the value,
2772 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
2773 reference. For example, if you have defined types as shown here:
2785 then you can write @code{$<itype>1} to refer to the first subunit of the
2786 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
2788 @node Mid-Rule Actions
2789 @subsection Actions in Mid-Rule
2790 @cindex actions in mid-rule
2791 @cindex mid-rule actions
2793 Occasionally it is useful to put an action in the middle of a rule.
2794 These actions are written just like usual end-of-rule actions, but they
2795 are executed before the parser even recognizes the following components.
2797 A mid-rule action may refer to the components preceding it using
2798 @code{$@var{n}}, but it may not refer to subsequent components because
2799 it is run before they are parsed.
2801 The mid-rule action itself counts as one of the components of the rule.
2802 This makes a difference when there is another action later in the same rule
2803 (and usually there is another at the end): you have to count the actions
2804 along with the symbols when working out which number @var{n} to use in
2807 The mid-rule action can also have a semantic value. The action can set
2808 its value with an assignment to @code{$$}, and actions later in the rule
2809 can refer to the value using @code{$@var{n}}. Since there is no symbol
2810 to name the action, there is no way to declare a data type for the value
2811 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
2812 specify a data type each time you refer to this value.
2814 There is no way to set the value of the entire rule with a mid-rule
2815 action, because assignments to @code{$$} do not have that effect. The
2816 only way to set the value for the entire rule is with an ordinary action
2817 at the end of the rule.
2819 Here is an example from a hypothetical compiler, handling a @code{let}
2820 statement that looks like @samp{let (@var{variable}) @var{statement}} and
2821 serves to create a variable named @var{variable} temporarily for the
2822 duration of @var{statement}. To parse this construct, we must put
2823 @var{variable} into the symbol table while @var{statement} is parsed, then
2824 remove it afterward. Here is how it is done:
2828 stmt: LET '(' var ')'
2829 @{ $<context>$ = push_context ();
2830 declare_variable ($3); @}
2832 pop_context ($<context>5); @}
2837 As soon as @samp{let (@var{variable})} has been recognized, the first
2838 action is run. It saves a copy of the current semantic context (the
2839 list of accessible variables) as its semantic value, using alternative
2840 @code{context} in the data-type union. Then it calls
2841 @code{declare_variable} to add the new variable to that list. Once the
2842 first action is finished, the embedded statement @code{stmt} can be
2843 parsed. Note that the mid-rule action is component number 5, so the
2844 @samp{stmt} is component number 6.
2846 After the embedded statement is parsed, its semantic value becomes the
2847 value of the entire @code{let}-statement. Then the semantic value from the
2848 earlier action is used to restore the prior list of variables. This
2849 removes the temporary @code{let}-variable from the list so that it won't
2850 appear to exist while the rest of the program is parsed.
2852 Taking action before a rule is completely recognized often leads to
2853 conflicts since the parser must commit to a parse in order to execute the
2854 action. For example, the following two rules, without mid-rule actions,
2855 can coexist in a working parser because the parser can shift the open-brace
2856 token and look at what follows before deciding whether there is a
2861 compound: '@{' declarations statements '@}'
2862 | '@{' statements '@}'
2868 But when we add a mid-rule action as follows, the rules become nonfunctional:
2872 compound: @{ prepare_for_local_variables (); @}
2873 '@{' declarations statements '@}'
2876 | '@{' statements '@}'
2882 Now the parser is forced to decide whether to run the mid-rule action
2883 when it has read no farther than the open-brace. In other words, it
2884 must commit to using one rule or the other, without sufficient
2885 information to do it correctly. (The open-brace token is what is called
2886 the @dfn{look-ahead} token at this time, since the parser is still
2887 deciding what to do about it. @xref{Look-Ahead, ,Look-Ahead Tokens}.)
2889 You might think that you could correct the problem by putting identical
2890 actions into the two rules, like this:
2894 compound: @{ prepare_for_local_variables (); @}
2895 '@{' declarations statements '@}'
2896 | @{ prepare_for_local_variables (); @}
2897 '@{' statements '@}'
2903 But this does not help, because Bison does not realize that the two actions
2904 are identical. (Bison never tries to understand the C code in an action.)
2906 If the grammar is such that a declaration can be distinguished from a
2907 statement by the first token (which is true in C), then one solution which
2908 does work is to put the action after the open-brace, like this:
2912 compound: '@{' @{ prepare_for_local_variables (); @}
2913 declarations statements '@}'
2914 | '@{' statements '@}'
2920 Now the first token of the following declaration or statement,
2921 which would in any case tell Bison which rule to use, can still do so.
2923 Another solution is to bury the action inside a nonterminal symbol which
2924 serves as a subroutine:
2928 subroutine: /* empty */
2929 @{ prepare_for_local_variables (); @}
2935 compound: subroutine
2936 '@{' declarations statements '@}'
2938 '@{' statements '@}'
2944 Now Bison can execute the action in the rule for @code{subroutine} without
2945 deciding which rule for @code{compound} it will eventually use. Note that
2946 the action is now at the end of its rule. Any mid-rule action can be
2947 converted to an end-of-rule action in this way, and this is what Bison
2948 actually does to implement mid-rule actions.
2951 @section Tracking Locations
2953 @cindex textual position
2954 @cindex position, textual
2956 Though grammar rules and semantic actions are enough to write a fully
2957 functional parser, it can be useful to process some additionnal informations,
2958 especially symbol locations.
2960 @c (terminal or not) ?
2962 The way locations are handled is defined by providing a data type, and
2963 actions to take when rules are matched.
2966 * Location Type:: Specifying a data type for locations.
2967 * Actions and Locations:: Using locations in actions.
2968 * Location Default Action:: Defining a general way to compute locations.
2972 @subsection Data Type of Locations
2973 @cindex data type of locations
2974 @cindex default location type
2976 Defining a data type for locations is much simpler than for semantic values,
2977 since all tokens and groupings always use the same type.
2979 The type of locations is specified by defining a macro called @code{YYLTYPE}.
2980 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
2993 @node Actions and Locations
2994 @subsection Actions and Locations
2995 @cindex location actions
2996 @cindex actions, location
3000 Actions are not only useful for defining language semantics, but also for
3001 describing the behavior of the output parser with locations.
3003 The most obvious way for building locations of syntactic groupings is very
3004 similar to the way semantic values are computed. In a given rule, several
3005 constructs can be used to access the locations of the elements being matched.
3006 The location of the @var{n}th component of the right hand side is
3007 @code{@@@var{n}}, while the location of the left hand side grouping is
3010 Here is a basic example using the default data type for locations:
3017 @@$.first_column = @@1.first_column;
3018 @@$.first_line = @@1.first_line;
3019 @@$.last_column = @@3.last_column;
3020 @@$.last_line = @@3.last_line;
3026 printf("Division by zero, l%d,c%d-l%d,c%d",
3027 @@3.first_line, @@3.first_column,
3028 @@3.last_line, @@3.last_column);
3034 As for semantic values, there is a default action for locations that is
3035 run each time a rule is matched. It sets the beginning of @code{@@$} to the
3036 beginning of the first symbol, and the end of @code{@@$} to the end of the
3039 With this default action, the location tracking can be fully automatic. The
3040 example above simply rewrites this way:
3052 printf("Division by zero, l%d,c%d-l%d,c%d",
3053 @@3.first_line, @@3.first_column,
3054 @@3.last_line, @@3.last_column);
3060 @node Location Default Action
3061 @subsection Default Action for Locations
3062 @vindex YYLLOC_DEFAULT
3064 Actually, actions are not the best place to compute locations. Since
3065 locations are much more general than semantic values, there is room in
3066 the output parser to redefine the default action to take for each
3067 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
3068 matched, before the associated action is run.
3070 Most of the time, this macro is general enough to suppress location
3071 dedicated code from semantic actions.
3073 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
3074 the location of the grouping (the result of the computation). The second one
3075 is an array holding locations of all right hand side elements of the rule
3076 being matched. The last one is the size of the right hand side rule.
3078 By default, it is defined this way for simple LALR(1) parsers:
3082 #define YYLLOC_DEFAULT(Current, Rhs, N) \
3083 Current.first_line = Rhs[1].first_line; \
3084 Current.first_column = Rhs[1].first_column; \
3085 Current.last_line = Rhs[N].last_line; \
3086 Current.last_column = Rhs[N].last_column;
3091 and like this for GLR parsers:
3095 #define YYLLOC_DEFAULT(Current, Rhs, N) \
3096 Current.first_line = YYRHSLOC(Rhs,1).first_line; \
3097 Current.first_column = YYRHSLOC(Rhs,1).first_column; \
3098 Current.last_line = YYRHSLOC(Rhs,N).last_line; \
3099 Current.last_column = YYRHSLOC(Rhs,N).last_column;
3103 When defining @code{YYLLOC_DEFAULT}, you should consider that:
3107 All arguments are free of side-effects. However, only the first one (the
3108 result) should be modified by @code{YYLLOC_DEFAULT}.
3111 For consistency with semantic actions, valid indexes for the location
3112 array range from 1 to @var{n}.
3116 @section Bison Declarations
3117 @cindex declarations, Bison
3118 @cindex Bison declarations
3120 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
3121 used in formulating the grammar and the data types of semantic values.
3124 All token type names (but not single-character literal tokens such as
3125 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
3126 declared if you need to specify which data type to use for the semantic
3127 value (@pxref{Multiple Types, ,More Than One Value Type}).
3129 The first rule in the file also specifies the start symbol, by default.
3130 If you want some other symbol to be the start symbol, you must declare
3131 it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free
3135 * Token Decl:: Declaring terminal symbols.
3136 * Precedence Decl:: Declaring terminals with precedence and associativity.
3137 * Union Decl:: Declaring the set of all semantic value types.
3138 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
3139 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
3140 * Start Decl:: Specifying the start symbol.
3141 * Pure Decl:: Requesting a reentrant parser.
3142 * Decl Summary:: Table of all Bison declarations.
3146 @subsection Token Type Names
3147 @cindex declaring token type names
3148 @cindex token type names, declaring
3149 @cindex declaring literal string tokens
3152 The basic way to declare a token type name (terminal symbol) is as follows:
3158 Bison will convert this into a @code{#define} directive in
3159 the parser, so that the function @code{yylex} (if it is in this file)
3160 can use the name @var{name} to stand for this token type's code.
3162 Alternatively, you can use @code{%left}, @code{%right}, or
3163 @code{%nonassoc} instead of @code{%token}, if you wish to specify
3164 associativity and precedence. @xref{Precedence Decl, ,Operator
3167 You can explicitly specify the numeric code for a token type by appending
3168 an integer value in the field immediately following the token name:
3175 It is generally best, however, to let Bison choose the numeric codes for
3176 all token types. Bison will automatically select codes that don't conflict
3177 with each other or with normal characters.
3179 In the event that the stack type is a union, you must augment the
3180 @code{%token} or other token declaration to include the data type
3181 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
3182 Than One Value Type}).
3188 %union @{ /* define stack type */
3192 %token <val> NUM /* define token NUM and its type */
3196 You can associate a literal string token with a token type name by
3197 writing the literal string at the end of a @code{%token}
3198 declaration which declares the name. For example:
3205 For example, a grammar for the C language might specify these names with
3206 equivalent literal string tokens:
3209 %token <operator> OR "||"
3210 %token <operator> LE 134 "<="
3215 Once you equate the literal string and the token name, you can use them
3216 interchangeably in further declarations or the grammar rules. The
3217 @code{yylex} function can use the token name or the literal string to
3218 obtain the token type code number (@pxref{Calling Convention}).
3220 @node Precedence Decl
3221 @subsection Operator Precedence
3222 @cindex precedence declarations
3223 @cindex declaring operator precedence
3224 @cindex operator precedence, declaring
3226 Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
3227 declare a token and specify its precedence and associativity, all at
3228 once. These are called @dfn{precedence declarations}.
3229 @xref{Precedence, ,Operator Precedence}, for general information on
3230 operator precedence.
3232 The syntax of a precedence declaration is the same as that of
3233 @code{%token}: either
3236 %left @var{symbols}@dots{}
3243 %left <@var{type}> @var{symbols}@dots{}
3246 And indeed any of these declarations serves the purposes of @code{%token}.
3247 But in addition, they specify the associativity and relative precedence for
3248 all the @var{symbols}:
3252 The associativity of an operator @var{op} determines how repeated uses
3253 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
3254 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
3255 grouping @var{y} with @var{z} first. @code{%left} specifies
3256 left-associativity (grouping @var{x} with @var{y} first) and
3257 @code{%right} specifies right-associativity (grouping @var{y} with
3258 @var{z} first). @code{%nonassoc} specifies no associativity, which
3259 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
3260 considered a syntax error.
3263 The precedence of an operator determines how it nests with other operators.
3264 All the tokens declared in a single precedence declaration have equal
3265 precedence and nest together according to their associativity.
3266 When two tokens declared in different precedence declarations associate,
3267 the one declared later has the higher precedence and is grouped first.
3271 @subsection The Collection of Value Types
3272 @cindex declaring value types
3273 @cindex value types, declaring
3276 The @code{%union} declaration specifies the entire collection of possible
3277 data types for semantic values. The keyword @code{%union} is followed by a
3278 pair of braces containing the same thing that goes inside a @code{union} in
3293 This says that the two alternative types are @code{double} and @code{symrec
3294 *}. They are given names @code{val} and @code{tptr}; these names are used
3295 in the @code{%token} and @code{%type} declarations to pick one of the types
3296 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
3298 Note that, unlike making a @code{union} declaration in C, you do not write
3299 a semicolon after the closing brace.
3302 @subsection Nonterminal Symbols
3303 @cindex declaring value types, nonterminals
3304 @cindex value types, nonterminals, declaring
3308 When you use @code{%union} to specify multiple value types, you must
3309 declare the value type of each nonterminal symbol for which values are
3310 used. This is done with a @code{%type} declaration, like this:
3313 %type <@var{type}> @var{nonterminal}@dots{}
3317 Here @var{nonterminal} is the name of a nonterminal symbol, and
3318 @var{type} is the name given in the @code{%union} to the alternative
3319 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
3320 can give any number of nonterminal symbols in the same @code{%type}
3321 declaration, if they have the same value type. Use spaces to separate
3324 You can also declare the value type of a terminal symbol. To do this,
3325 use the same @code{<@var{type}>} construction in a declaration for the
3326 terminal symbol. All kinds of token declarations allow
3327 @code{<@var{type}>}.
3330 @subsection Suppressing Conflict Warnings
3331 @cindex suppressing conflict warnings
3332 @cindex preventing warnings about conflicts
3333 @cindex warnings, preventing
3334 @cindex conflicts, suppressing warnings of
3337 Bison normally warns if there are any conflicts in the grammar
3338 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
3339 have harmless shift/reduce conflicts which are resolved in a predictable
3340 way and would be difficult to eliminate. It is desirable to suppress
3341 the warning about these conflicts unless the number of conflicts
3342 changes. You can do this with the @code{%expect} declaration.
3344 The declaration looks like this:
3350 Here @var{n} is a decimal integer. The declaration says there should be
3351 no warning if there are @var{n} shift/reduce conflicts and no
3352 reduce/reduce conflicts. An error, instead of the usual warning, is
3353 given if there are either more or fewer conflicts, or if there are any
3354 reduce/reduce conflicts.
3356 In general, using @code{%expect} involves these steps:
3360 Compile your grammar without @code{%expect}. Use the @samp{-v} option
3361 to get a verbose list of where the conflicts occur. Bison will also
3362 print the number of conflicts.
3365 Check each of the conflicts to make sure that Bison's default
3366 resolution is what you really want. If not, rewrite the grammar and
3367 go back to the beginning.
3370 Add an @code{%expect} declaration, copying the number @var{n} from the
3371 number which Bison printed.
3374 Now Bison will stop annoying you about the conflicts you have checked, but
3375 it will warn you again if changes in the grammar result in additional
3379 @subsection The Start-Symbol
3380 @cindex declaring the start symbol
3381 @cindex start symbol, declaring
3382 @cindex default start symbol
3385 Bison assumes by default that the start symbol for the grammar is the first
3386 nonterminal specified in the grammar specification section. The programmer
3387 may override this restriction with the @code{%start} declaration as follows:
3394 @subsection A Pure (Reentrant) Parser
3395 @cindex reentrant parser
3397 @findex %pure-parser
3399 A @dfn{reentrant} program is one which does not alter in the course of
3400 execution; in other words, it consists entirely of @dfn{pure} (read-only)
3401 code. Reentrancy is important whenever asynchronous execution is possible;
3402 for example, a non-reentrant program may not be safe to call from a signal
3403 handler. In systems with multiple threads of control, a non-reentrant
3404 program must be called only within interlocks.
3406 Normally, Bison generates a parser which is not reentrant. This is
3407 suitable for most uses, and it permits compatibility with YACC. (The
3408 standard YACC interfaces are inherently nonreentrant, because they use
3409 statically allocated variables for communication with @code{yylex},
3410 including @code{yylval} and @code{yylloc}.)
3412 Alternatively, you can generate a pure, reentrant parser. The Bison
3413 declaration @code{%pure-parser} says that you want the parser to be
3414 reentrant. It looks like this:
3420 The result is that the communication variables @code{yylval} and
3421 @code{yylloc} become local variables in @code{yyparse}, and a different
3422 calling convention is used for the lexical analyzer function
3423 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
3424 Parsers}, for the details of this. The variable @code{yynerrs} also
3425 becomes local in @code{yyparse} (@pxref{Error Reporting, ,The Error
3426 Reporting Function @code{yyerror}}). The convention for calling
3427 @code{yyparse} itself is unchanged.
3429 Whether the parser is pure has nothing to do with the grammar rules.
3430 You can generate either a pure parser or a nonreentrant parser from any
3434 @subsection Bison Declaration Summary
3435 @cindex Bison declaration summary
3436 @cindex declaration summary
3437 @cindex summary, Bison declaration
3439 Here is a summary of the declarations used to define a grammar:
3443 Declare the collection of data types that semantic values may have
3444 (@pxref{Union Decl, ,The Collection of Value Types}).
3447 Declare a terminal symbol (token type name) with no precedence
3448 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
3451 Declare a terminal symbol (token type name) that is right-associative
3452 (@pxref{Precedence Decl, ,Operator Precedence}).
3455 Declare a terminal symbol (token type name) that is left-associative
3456 (@pxref{Precedence Decl, ,Operator Precedence}).
3459 Declare a terminal symbol (token type name) that is nonassociative
3460 (using it in a way that would be associative is a syntax error)
3461 (@pxref{Precedence Decl, ,Operator Precedence}).
3464 Declare the type of semantic values for a nonterminal symbol
3465 (@pxref{Type Decl, ,Nonterminal Symbols}).
3468 Specify the grammar's start symbol (@pxref{Start Decl, ,The
3472 Declare the expected number of shift-reduce conflicts
3473 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
3478 In order to change the behavior of @command{bison}, use the following
3483 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
3484 already defined, so that the debugging facilities are compiled.
3485 @xref{Tracing, ,Tracing Your Parser}.
3488 Write an extra output file containing macro definitions for the token
3489 type names defined in the grammar and the semantic value type
3490 @code{YYSTYPE}, as well as a few @code{extern} variable declarations.
3492 If the parser output file is named @file{@var{name}.c} then this file
3493 is named @file{@var{name}.h}.
3495 This output file is essential if you wish to put the definition of
3496 @code{yylex} in a separate source file, because @code{yylex} needs to
3497 be able to refer to token type codes and the variable
3498 @code{yylval}. @xref{Token Values, ,Semantic Values of Tokens}.
3500 @item %file-prefix="@var{prefix}"
3501 Specify a prefix to use for all Bison output file names. The names are
3502 chosen as if the input file were named @file{@var{prefix}.y}.
3504 @c @item %header-extension
3505 @c Specify the extension of the parser header file generated when
3506 @c @code{%define} or @samp{-d} are used.
3508 @c For example, a grammar file named @file{foo.ypp} and containing a
3509 @c @code{%header-extension .hh} directive will produce a header file
3510 @c named @file{foo.tab.hh}
3513 Generate the code processing the locations (@pxref{Action Features,
3514 ,Special Features for Use in Actions}). This mode is enabled as soon as
3515 the grammar uses the special @samp{@@@var{n}} tokens, but if your
3516 grammar does not use it, using @samp{%locations} allows for more
3517 accurate parse error messages.
3519 @item %name-prefix="@var{prefix}"
3520 Rename the external symbols used in the parser so that they start with
3521 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
3522 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
3523 @code{yylval}, @code{yychar}, @code{yydebug}, and possible
3524 @code{yylloc}. For example, if you use @samp{%name-prefix="c_"}, the
3525 names become @code{c_parse}, @code{c_lex}, and so on. @xref{Multiple
3526 Parsers, ,Multiple Parsers in the Same Program}.
3529 Do not include any C code in the parser file; generate tables only. The
3530 parser file contains just @code{#define} directives and static variable
3533 This option also tells Bison to write the C code for the grammar actions
3534 into a file named @file{@var{filename}.act}, in the form of a
3535 brace-surrounded body fit for a @code{switch} statement.
3538 Don't generate any @code{#line} preprocessor commands in the parser
3539 file. Ordinarily Bison writes these commands in the parser file so that
3540 the C compiler and debuggers will associate errors and object code with
3541 your source file (the grammar file). This directive causes them to
3542 associate errors with the parser file, treating it an independent source
3543 file in its own right.
3545 @item %output="@var{filename}"
3546 Specify the @var{filename} for the parser file.
3549 Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure
3550 (Reentrant) Parser}).
3552 @c @item %source-extension
3553 @c Specify the extension of the parser output file.
3555 @c For example, a grammar file named @file{foo.yy} and containing a
3556 @c @code{%source-extension .cpp} directive will produce a parser file
3557 @c named @file{foo.tab.cpp}
3560 Generate an array of token names in the parser file. The name of the
3561 array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
3562 token whose internal Bison token code number is @var{i}. The first
3563 three elements of @code{yytname} are always @code{"$end"},
3564 @code{"error"}, and @code{"$undefined"}; after these come the symbols
3565 defined in the grammar file.
3567 For single-character literal tokens and literal string tokens, the name
3568 in the table includes the single-quote or double-quote characters: for
3569 example, @code{"'+'"} is a single-character literal and @code{"\"<=\""}
3570 is a literal string token. All the characters of the literal string
3571 token appear verbatim in the string found in the table; even
3572 double-quote characters are not escaped. For example, if the token
3573 consists of three characters @samp{*"*}, its string in @code{yytname}
3574 contains @samp{"*"*"}. (In C, that would be written as
3577 When you specify @code{%token-table}, Bison also generates macro
3578 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
3579 @code{YYNRULES}, and @code{YYNSTATES}:
3583 The highest token number, plus one.
3585 The number of nonterminal symbols.
3587 The number of grammar rules,
3589 The number of parser states (@pxref{Parser States}).
3593 Write an extra output file containing verbose descriptions of the
3594 parser states and what is done for each type of look-ahead token in
3595 that state. @xref{Understanding, , Understanding Your Parser}, for more
3601 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
3602 including its naming conventions. @xref{Bison Options}, for more.
3608 @node Multiple Parsers
3609 @section Multiple Parsers in the Same Program
3611 Most programs that use Bison parse only one language and therefore contain
3612 only one Bison parser. But what if you want to parse more than one
3613 language with the same program? Then you need to avoid a name conflict
3614 between different definitions of @code{yyparse}, @code{yylval}, and so on.
3616 The easy way to do this is to use the option @samp{-p @var{prefix}}
3617 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
3618 functions and variables of the Bison parser to start with @var{prefix}
3619 instead of @samp{yy}. You can use this to give each parser distinct
3620 names that do not conflict.
3622 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
3623 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yychar} and
3624 @code{yydebug}. For example, if you use @samp{-p c}, the names become
3625 @code{cparse}, @code{clex}, and so on.
3627 @strong{All the other variables and macros associated with Bison are not
3628 renamed.} These others are not global; there is no conflict if the same
3629 name is used in different parsers. For example, @code{YYSTYPE} is not
3630 renamed, but defining this in different ways in different parsers causes
3631 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
3633 The @samp{-p} option works by adding macro definitions to the beginning
3634 of the parser source file, defining @code{yyparse} as
3635 @code{@var{prefix}parse}, and so on. This effectively substitutes one
3636 name for the other in the entire parser file.
3639 @chapter Parser C-Language Interface
3640 @cindex C-language interface
3643 The Bison parser is actually a C function named @code{yyparse}. Here we
3644 describe the interface conventions of @code{yyparse} and the other
3645 functions that it needs to use.
3647 Keep in mind that the parser uses many C identifiers starting with
3648 @samp{yy} and @samp{YY} for internal purposes. If you use such an
3649 identifier (aside from those in this manual) in an action or in epilogue
3650 in the grammar file, you are likely to run into trouble.
3653 * Parser Function:: How to call @code{yyparse} and what it returns.
3654 * Lexical:: You must supply a function @code{yylex}
3656 * Error Reporting:: You must supply a function @code{yyerror}.
3657 * Action Features:: Special features for use in actions.
3660 @node Parser Function
3661 @section The Parser Function @code{yyparse}
3664 You call the function @code{yyparse} to cause parsing to occur. This
3665 function reads tokens, executes actions, and ultimately returns when it
3666 encounters end-of-input or an unrecoverable syntax error. You can also
3667 write an action which directs @code{yyparse} to return immediately
3668 without reading further.
3670 The value returned by @code{yyparse} is 0 if parsing was successful (return
3671 is due to end-of-input).
3673 The value is 1 if parsing failed (return is due to a syntax error).
3675 In an action, you can cause immediate return from @code{yyparse} by using
3681 Return immediately with value 0 (to report success).
3685 Return immediately with value 1 (to report failure).
3689 @section The Lexical Analyzer Function @code{yylex}
3691 @cindex lexical analyzer
3693 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
3694 the input stream and returns them to the parser. Bison does not create
3695 this function automatically; you must write it so that @code{yyparse} can
3696 call it. The function is sometimes referred to as a lexical scanner.
3698 In simple programs, @code{yylex} is often defined at the end of the Bison
3699 grammar file. If @code{yylex} is defined in a separate source file, you
3700 need to arrange for the token-type macro definitions to be available there.
3701 To do this, use the @samp{-d} option when you run Bison, so that it will
3702 write these macro definitions into a separate header file
3703 @file{@var{name}.tab.h} which you can include in the other source files
3704 that need it. @xref{Invocation, ,Invoking Bison}.
3707 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
3708 * Token Values:: How @code{yylex} must return the semantic value
3709 of the token it has read.
3710 * Token Positions:: How @code{yylex} must return the text position
3711 (line number, etc.) of the token, if the
3713 * Pure Calling:: How the calling convention differs
3714 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
3717 @node Calling Convention
3718 @subsection Calling Convention for @code{yylex}
3720 The value that @code{yylex} returns must be the numeric code for the type
3721 of token it has just found, or 0 for end-of-input.
3723 When a token is referred to in the grammar rules by a name, that name
3724 in the parser file becomes a C macro whose definition is the proper
3725 numeric code for that token type. So @code{yylex} can use the name
3726 to indicate that type. @xref{Symbols}.
3728 When a token is referred to in the grammar rules by a character literal,
3729 the numeric code for that character is also the code for the token type.
3730 So @code{yylex} can simply return that character code. The null character
3731 must not be used this way, because its code is zero and that is what
3732 signifies end-of-input.
3734 Here is an example showing these things:
3741 if (c == EOF) /* Detect end of file. */
3744 if (c == '+' || c == '-')
3745 return c; /* Assume token type for `+' is '+'. */
3747 return INT; /* Return the type of the token. */
3753 This interface has been designed so that the output from the @code{lex}
3754 utility can be used without change as the definition of @code{yylex}.
3756 If the grammar uses literal string tokens, there are two ways that
3757 @code{yylex} can determine the token type codes for them:
3761 If the grammar defines symbolic token names as aliases for the
3762 literal string tokens, @code{yylex} can use these symbolic names like
3763 all others. In this case, the use of the literal string tokens in
3764 the grammar file has no effect on @code{yylex}.
3767 @code{yylex} can find the multicharacter token in the @code{yytname}
3768 table. The index of the token in the table is the token type's code.
3769 The name of a multicharacter token is recorded in @code{yytname} with a
3770 double-quote, the token's characters, and another double-quote. The
3771 token's characters are not escaped in any way; they appear verbatim in
3772 the contents of the string in the table.
3774 Here's code for looking up a token in @code{yytname}, assuming that the
3775 characters of the token are stored in @code{token_buffer}.
3778 for (i = 0; i < YYNTOKENS; i++)
3781 && yytname[i][0] == '"'
3782 && strncmp (yytname[i] + 1, token_buffer,
3783 strlen (token_buffer))
3784 && yytname[i][strlen (token_buffer) + 1] == '"'
3785 && yytname[i][strlen (token_buffer) + 2] == 0)
3790 The @code{yytname} table is generated only if you use the
3791 @code{%token-table} declaration. @xref{Decl Summary}.
3795 @subsection Semantic Values of Tokens
3798 In an ordinary (non-reentrant) parser, the semantic value of the token must
3799 be stored into the global variable @code{yylval}. When you are using
3800 just one data type for semantic values, @code{yylval} has that type.
3801 Thus, if the type is @code{int} (the default), you might write this in
3807 yylval = value; /* Put value onto Bison stack. */
3808 return INT; /* Return the type of the token. */
3813 When you are using multiple data types, @code{yylval}'s type is a union
3814 made from the @code{%union} declaration (@pxref{Union Decl, ,The
3815 Collection of Value Types}). So when you store a token's value, you
3816 must use the proper member of the union. If the @code{%union}
3817 declaration looks like this:
3830 then the code in @code{yylex} might look like this:
3835 yylval.intval = value; /* Put value onto Bison stack. */
3836 return INT; /* Return the type of the token. */
3841 @node Token Positions
3842 @subsection Textual Positions of Tokens
3845 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
3846 Tracking Locations}) in actions to keep track of the
3847 textual locations of tokens and groupings, then you must provide this
3848 information in @code{yylex}. The function @code{yyparse} expects to
3849 find the textual location of a token just parsed in the global variable
3850 @code{yylloc}. So @code{yylex} must store the proper data in that
3853 By default, the value of @code{yylloc} is a structure and you need only
3854 initialize the members that are going to be used by the actions. The
3855 four members are called @code{first_line}, @code{first_column},
3856 @code{last_line} and @code{last_column}. Note that the use of this
3857 feature makes the parser noticeably slower.
3860 The data type of @code{yylloc} has the name @code{YYLTYPE}.
3863 @subsection Calling Conventions for Pure Parsers
3865 When you use the Bison declaration @code{%pure-parser} to request a
3866 pure, reentrant parser, the global communication variables @code{yylval}
3867 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
3868 Parser}.) In such parsers the two global variables are replaced by
3869 pointers passed as arguments to @code{yylex}. You must declare them as
3870 shown here, and pass the information back by storing it through those
3875 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
3878 *lvalp = value; /* Put value onto Bison stack. */
3879 return INT; /* Return the type of the token. */
3884 If the grammar file does not use the @samp{@@} constructs to refer to
3885 textual positions, then the type @code{YYLTYPE} will not be defined. In
3886 this case, omit the second argument; @code{yylex} will be called with
3889 @vindex YYPARSE_PARAM
3890 If you use a reentrant parser, you can optionally pass additional
3891 parameter information to it in a reentrant way. To do so, define the
3892 macro @code{YYPARSE_PARAM} as a variable name. This modifies the
3893 @code{yyparse} function to accept one argument, of type @code{void *},
3896 When you call @code{yyparse}, pass the address of an object, casting the
3897 address to @code{void *}. The grammar actions can refer to the contents
3898 of the object by casting the pointer value back to its proper type and
3899 then dereferencing it. Here's an example. Write this in the parser:
3903 struct parser_control
3909 #define YYPARSE_PARAM parm
3914 Then call the parser like this:
3917 struct parser_control
3926 struct parser_control foo;
3927 @dots{} /* @r{Store proper data in @code{foo}.} */
3928 value = yyparse ((void *) &foo);
3934 In the grammar actions, use expressions like this to refer to the data:
3937 ((struct parser_control *) parm)->randomness
3941 If you wish to pass the additional parameter data to @code{yylex},
3942 define the macro @code{YYLEX_PARAM} just like @code{YYPARSE_PARAM}, as
3947 struct parser_control
3953 #define YYPARSE_PARAM parm
3954 #define YYLEX_PARAM parm
3958 You should then define @code{yylex} to accept one additional
3959 argument---the value of @code{parm}. (This makes either two or three
3960 arguments in total, depending on whether an argument of type
3961 @code{YYLTYPE} is passed.) You can declare the argument as a pointer to
3962 the proper object type, or you can declare it as @code{void *} and
3963 access the contents as shown above.
3965 You can use @samp{%pure-parser} to request a reentrant parser without
3966 also using @code{YYPARSE_PARAM}. Then you should call @code{yyparse}
3967 with no arguments, as usual.
3969 @node Error Reporting
3970 @section The Error Reporting Function @code{yyerror}
3971 @cindex error reporting function
3974 @cindex syntax error
3976 The Bison parser detects a @dfn{parse error} or @dfn{syntax error}
3977 whenever it reads a token which cannot satisfy any syntax rule. An
3978 action in the grammar can also explicitly proclaim an error, using the
3979 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
3982 The Bison parser expects to report the error by calling an error
3983 reporting function named @code{yyerror}, which you must supply. It is
3984 called by @code{yyparse} whenever a syntax error is found, and it
3985 receives one argument. For a parse error, the string is normally
3986 @w{@code{"parse error"}}.
3988 @findex YYERROR_VERBOSE
3989 If you define the macro @code{YYERROR_VERBOSE} in the Bison declarations
3990 section (@pxref{Bison Declarations, ,The Bison Declarations Section}),
3991 then Bison provides a more verbose and specific error message string
3992 instead of just plain @w{@code{"parse error"}}. It doesn't matter what
3993 definition you use for @code{YYERROR_VERBOSE}, just whether you define
3996 The parser can detect one other kind of error: stack overflow. This
3997 happens when the input contains constructions that are very deeply
3998 nested. It isn't likely you will encounter this, since the Bison
3999 parser extends its stack automatically up to a very large limit. But
4000 if overflow happens, @code{yyparse} calls @code{yyerror} in the usual
4001 fashion, except that the argument string is @w{@code{"parser stack
4004 The following definition suffices in simple programs:
4013 fprintf (stderr, "%s\n", s);
4018 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
4019 error recovery if you have written suitable error recovery grammar rules
4020 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
4021 immediately return 1.
4024 The variable @code{yynerrs} contains the number of syntax errors
4025 encountered so far. Normally this variable is global; but if you
4026 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
4027 then it is a local variable which only the actions can access.
4029 @node Action Features
4030 @section Special Features for Use in Actions
4031 @cindex summary, action features
4032 @cindex action features summary
4034 Here is a table of Bison constructs, variables and macros that
4035 are useful in actions.
4039 Acts like a variable that contains the semantic value for the
4040 grouping made by the current rule. @xref{Actions}.
4043 Acts like a variable that contains the semantic value for the
4044 @var{n}th component of the current rule. @xref{Actions}.
4046 @item $<@var{typealt}>$
4047 Like @code{$$} but specifies alternative @var{typealt} in the union
4048 specified by the @code{%union} declaration. @xref{Action Types, ,Data
4049 Types of Values in Actions}.
4051 @item $<@var{typealt}>@var{n}
4052 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
4053 union specified by the @code{%union} declaration.
4054 @xref{Action Types, ,Data Types of Values in Actions}.
4057 Return immediately from @code{yyparse}, indicating failure.
4058 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
4061 Return immediately from @code{yyparse}, indicating success.
4062 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
4064 @item YYBACKUP (@var{token}, @var{value});
4066 Unshift a token. This macro is allowed only for rules that reduce
4067 a single value, and only when there is no look-ahead token.
4068 It is also disallowed in GLR parsers.
4069 It installs a look-ahead token with token type @var{token} and
4070 semantic value @var{value}; then it discards the value that was
4071 going to be reduced by this rule.
4073 If the macro is used when it is not valid, such as when there is
4074 a look-ahead token already, then it reports a syntax error with
4075 a message @samp{cannot back up} and performs ordinary error
4078 In either case, the rest of the action is not executed.
4082 Value stored in @code{yychar} when there is no look-ahead token.
4086 Cause an immediate syntax error. This statement initiates error
4087 recovery just as if the parser itself had detected an error; however, it
4088 does not call @code{yyerror}, and does not print any message. If you
4089 want to print an error message, call @code{yyerror} explicitly before
4090 the @samp{YYERROR;} statement. @xref{Error Recovery}.
4093 This macro stands for an expression that has the value 1 when the parser
4094 is recovering from a syntax error, and 0 the rest of the time.
4095 @xref{Error Recovery}.
4098 Variable containing the current look-ahead token. (In a pure parser,
4099 this is actually a local variable within @code{yyparse}.) When there is
4100 no look-ahead token, the value @code{YYEMPTY} is stored in the variable.
4101 @xref{Look-Ahead, ,Look-Ahead Tokens}.
4104 Discard the current look-ahead token. This is useful primarily in
4105 error rules. @xref{Error Recovery}.
4108 Resume generating error messages immediately for subsequent syntax
4109 errors. This is useful primarily in error rules.
4110 @xref{Error Recovery}.
4114 Acts like a structure variable containing information on the textual position
4115 of the grouping made by the current rule. @xref{Locations, ,
4116 Tracking Locations}.
4118 @c Check if those paragraphs are still useful or not.
4122 @c int first_line, last_line;
4123 @c int first_column, last_column;
4127 @c Thus, to get the starting line number of the third component, you would
4128 @c use @samp{@@3.first_line}.
4130 @c In order for the members of this structure to contain valid information,
4131 @c you must make @code{yylex} supply this information about each token.
4132 @c If you need only certain members, then @code{yylex} need only fill in
4135 @c The use of this feature makes the parser noticeably slower.
4139 Acts like a structure variable containing information on the textual position
4140 of the @var{n}th component of the current rule. @xref{Locations, ,
4141 Tracking Locations}.
4146 @chapter The Bison Parser Algorithm
4147 @cindex Bison parser algorithm
4148 @cindex algorithm of parser
4151 @cindex parser stack
4152 @cindex stack, parser
4154 As Bison reads tokens, it pushes them onto a stack along with their
4155 semantic values. The stack is called the @dfn{parser stack}. Pushing a
4156 token is traditionally called @dfn{shifting}.
4158 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
4159 @samp{3} to come. The stack will have four elements, one for each token
4162 But the stack does not always have an element for each token read. When
4163 the last @var{n} tokens and groupings shifted match the components of a
4164 grammar rule, they can be combined according to that rule. This is called
4165 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
4166 single grouping whose symbol is the result (left hand side) of that rule.
4167 Running the rule's action is part of the process of reduction, because this
4168 is what computes the semantic value of the resulting grouping.
4170 For example, if the infix calculator's parser stack contains this:
4177 and the next input token is a newline character, then the last three
4178 elements can be reduced to 15 via the rule:
4181 expr: expr '*' expr;
4185 Then the stack contains just these three elements:
4192 At this point, another reduction can be made, resulting in the single value
4193 16. Then the newline token can be shifted.
4195 The parser tries, by shifts and reductions, to reduce the entire input down
4196 to a single grouping whose symbol is the grammar's start-symbol
4197 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
4199 This kind of parser is known in the literature as a bottom-up parser.
4202 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
4203 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
4204 * Precedence:: Operator precedence works by resolving conflicts.
4205 * Contextual Precedence:: When an operator's precedence depends on context.
4206 * Parser States:: The parser is a finite-state-machine with stack.
4207 * Reduce/Reduce:: When two rules are applicable in the same situation.
4208 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
4209 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
4210 * Stack Overflow:: What happens when stack gets full. How to avoid it.
4214 @section Look-Ahead Tokens
4215 @cindex look-ahead token
4217 The Bison parser does @emph{not} always reduce immediately as soon as the
4218 last @var{n} tokens and groupings match a rule. This is because such a
4219 simple strategy is inadequate to handle most languages. Instead, when a
4220 reduction is possible, the parser sometimes ``looks ahead'' at the next
4221 token in order to decide what to do.
4223 When a token is read, it is not immediately shifted; first it becomes the
4224 @dfn{look-ahead token}, which is not on the stack. Now the parser can
4225 perform one or more reductions of tokens and groupings on the stack, while
4226 the look-ahead token remains off to the side. When no more reductions
4227 should take place, the look-ahead token is shifted onto the stack. This
4228 does not mean that all possible reductions have been done; depending on the
4229 token type of the look-ahead token, some rules may choose to delay their
4232 Here is a simple case where look-ahead is needed. These three rules define
4233 expressions which contain binary addition operators and postfix unary
4234 factorial operators (@samp{!}), and allow parentheses for grouping.
4251 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
4252 should be done? If the following token is @samp{)}, then the first three
4253 tokens must be reduced to form an @code{expr}. This is the only valid
4254 course, because shifting the @samp{)} would produce a sequence of symbols
4255 @w{@code{term ')'}}, and no rule allows this.
4257 If the following token is @samp{!}, then it must be shifted immediately so
4258 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
4259 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
4260 @code{expr}. It would then be impossible to shift the @samp{!} because
4261 doing so would produce on the stack the sequence of symbols @code{expr
4262 '!'}. No rule allows that sequence.
4265 The current look-ahead token is stored in the variable @code{yychar}.
4266 @xref{Action Features, ,Special Features for Use in Actions}.
4269 @section Shift/Reduce Conflicts
4271 @cindex shift/reduce conflicts
4272 @cindex dangling @code{else}
4273 @cindex @code{else}, dangling
4275 Suppose we are parsing a language which has if-then and if-then-else
4276 statements, with a pair of rules like this:
4282 | IF expr THEN stmt ELSE stmt
4288 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
4289 terminal symbols for specific keyword tokens.
4291 When the @code{ELSE} token is read and becomes the look-ahead token, the
4292 contents of the stack (assuming the input is valid) are just right for
4293 reduction by the first rule. But it is also legitimate to shift the
4294 @code{ELSE}, because that would lead to eventual reduction by the second
4297 This situation, where either a shift or a reduction would be valid, is
4298 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
4299 these conflicts by choosing to shift, unless otherwise directed by
4300 operator precedence declarations. To see the reason for this, let's
4301 contrast it with the other alternative.
4303 Since the parser prefers to shift the @code{ELSE}, the result is to attach
4304 the else-clause to the innermost if-statement, making these two inputs
4308 if x then if y then win (); else lose;
4310 if x then do; if y then win (); else lose; end;
4313 But if the parser chose to reduce when possible rather than shift, the
4314 result would be to attach the else-clause to the outermost if-statement,
4315 making these two inputs equivalent:
4318 if x then if y then win (); else lose;
4320 if x then do; if y then win (); end; else lose;
4323 The conflict exists because the grammar as written is ambiguous: either
4324 parsing of the simple nested if-statement is legitimate. The established
4325 convention is that these ambiguities are resolved by attaching the
4326 else-clause to the innermost if-statement; this is what Bison accomplishes
4327 by choosing to shift rather than reduce. (It would ideally be cleaner to
4328 write an unambiguous grammar, but that is very hard to do in this case.)
4329 This particular ambiguity was first encountered in the specifications of
4330 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
4332 To avoid warnings from Bison about predictable, legitimate shift/reduce
4333 conflicts, use the @code{%expect @var{n}} declaration. There will be no
4334 warning as long as the number of shift/reduce conflicts is exactly @var{n}.
4335 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
4337 The definition of @code{if_stmt} above is solely to blame for the
4338 conflict, but the conflict does not actually appear without additional
4339 rules. Here is a complete Bison input file that actually manifests the
4344 %token IF THEN ELSE variable
4356 | IF expr THEN stmt ELSE stmt
4365 @section Operator Precedence
4366 @cindex operator precedence
4367 @cindex precedence of operators
4369 Another situation where shift/reduce conflicts appear is in arithmetic
4370 expressions. Here shifting is not always the preferred resolution; the
4371 Bison declarations for operator precedence allow you to specify when to
4372 shift and when to reduce.
4375 * Why Precedence:: An example showing why precedence is needed.
4376 * Using Precedence:: How to specify precedence in Bison grammars.
4377 * Precedence Examples:: How these features are used in the previous example.
4378 * How Precedence:: How they work.
4381 @node Why Precedence
4382 @subsection When Precedence is Needed
4384 Consider the following ambiguous grammar fragment (ambiguous because the
4385 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
4399 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
4400 should it reduce them via the rule for the subtraction operator? It
4401 depends on the next token. Of course, if the next token is @samp{)}, we
4402 must reduce; shifting is invalid because no single rule can reduce the
4403 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
4404 the next token is @samp{*} or @samp{<}, we have a choice: either
4405 shifting or reduction would allow the parse to complete, but with
4408 To decide which one Bison should do, we must consider the results. If
4409 the next operator token @var{op} is shifted, then it must be reduced
4410 first in order to permit another opportunity to reduce the difference.
4411 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
4412 hand, if the subtraction is reduced before shifting @var{op}, the result
4413 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
4414 reduce should depend on the relative precedence of the operators
4415 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
4418 @cindex associativity
4419 What about input such as @w{@samp{1 - 2 - 5}}; should this be
4420 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
4421 operators we prefer the former, which is called @dfn{left association}.
4422 The latter alternative, @dfn{right association}, is desirable for
4423 assignment operators. The choice of left or right association is a
4424 matter of whether the parser chooses to shift or reduce when the stack
4425 contains @w{@samp{1 - 2}} and the look-ahead token is @samp{-}: shifting
4426 makes right-associativity.
4428 @node Using Precedence
4429 @subsection Specifying Operator Precedence
4434 Bison allows you to specify these choices with the operator precedence
4435 declarations @code{%left} and @code{%right}. Each such declaration
4436 contains a list of tokens, which are operators whose precedence and
4437 associativity is being declared. The @code{%left} declaration makes all
4438 those operators left-associative and the @code{%right} declaration makes
4439 them right-associative. A third alternative is @code{%nonassoc}, which
4440 declares that it is a syntax error to find the same operator twice ``in a
4443 The relative precedence of different operators is controlled by the
4444 order in which they are declared. The first @code{%left} or
4445 @code{%right} declaration in the file declares the operators whose
4446 precedence is lowest, the next such declaration declares the operators
4447 whose precedence is a little higher, and so on.
4449 @node Precedence Examples
4450 @subsection Precedence Examples
4452 In our example, we would want the following declarations:
4460 In a more complete example, which supports other operators as well, we
4461 would declare them in groups of equal precedence. For example, @code{'+'} is
4462 declared with @code{'-'}:
4465 %left '<' '>' '=' NE LE GE
4471 (Here @code{NE} and so on stand for the operators for ``not equal''
4472 and so on. We assume that these tokens are more than one character long
4473 and therefore are represented by names, not character literals.)
4475 @node How Precedence
4476 @subsection How Precedence Works
4478 The first effect of the precedence declarations is to assign precedence
4479 levels to the terminal symbols declared. The second effect is to assign
4480 precedence levels to certain rules: each rule gets its precedence from
4481 the last terminal symbol mentioned in the components. (You can also
4482 specify explicitly the precedence of a rule. @xref{Contextual
4483 Precedence, ,Context-Dependent Precedence}.)
4485 Finally, the resolution of conflicts works by comparing the precedence
4486 of the rule being considered with that of the look-ahead token. If the
4487 token's precedence is higher, the choice is to shift. If the rule's
4488 precedence is higher, the choice is to reduce. If they have equal
4489 precedence, the choice is made based on the associativity of that
4490 precedence level. The verbose output file made by @samp{-v}
4491 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
4494 Not all rules and not all tokens have precedence. If either the rule or
4495 the look-ahead token has no precedence, then the default is to shift.
4497 @node Contextual Precedence
4498 @section Context-Dependent Precedence
4499 @cindex context-dependent precedence
4500 @cindex unary operator precedence
4501 @cindex precedence, context-dependent
4502 @cindex precedence, unary operator
4505 Often the precedence of an operator depends on the context. This sounds
4506 outlandish at first, but it is really very common. For example, a minus
4507 sign typically has a very high precedence as a unary operator, and a
4508 somewhat lower precedence (lower than multiplication) as a binary operator.
4510 The Bison precedence declarations, @code{%left}, @code{%right} and
4511 @code{%nonassoc}, can only be used once for a given token; so a token has
4512 only one precedence declared in this way. For context-dependent
4513 precedence, you need to use an additional mechanism: the @code{%prec}
4516 The @code{%prec} modifier declares the precedence of a particular rule by
4517 specifying a terminal symbol whose precedence should be used for that rule.
4518 It's not necessary for that symbol to appear otherwise in the rule. The
4519 modifier's syntax is:
4522 %prec @var{terminal-symbol}
4526 and it is written after the components of the rule. Its effect is to
4527 assign the rule the precedence of @var{terminal-symbol}, overriding
4528 the precedence that would be deduced for it in the ordinary way. The
4529 altered rule precedence then affects how conflicts involving that rule
4530 are resolved (@pxref{Precedence, ,Operator Precedence}).
4532 Here is how @code{%prec} solves the problem of unary minus. First, declare
4533 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
4534 are no tokens of this type, but the symbol serves to stand for its
4544 Now the precedence of @code{UMINUS} can be used in specific rules:
4551 | '-' exp %prec UMINUS
4556 @section Parser States
4557 @cindex finite-state machine
4558 @cindex parser state
4559 @cindex state (of parser)
4561 The function @code{yyparse} is implemented using a finite-state machine.
4562 The values pushed on the parser stack are not simply token type codes; they
4563 represent the entire sequence of terminal and nonterminal symbols at or
4564 near the top of the stack. The current state collects all the information
4565 about previous input which is relevant to deciding what to do next.
4567 Each time a look-ahead token is read, the current parser state together
4568 with the type of look-ahead token are looked up in a table. This table
4569 entry can say, ``Shift the look-ahead token.'' In this case, it also
4570 specifies the new parser state, which is pushed onto the top of the
4571 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
4572 This means that a certain number of tokens or groupings are taken off
4573 the top of the stack, and replaced by one grouping. In other words,
4574 that number of states are popped from the stack, and one new state is
4577 There is one other alternative: the table can say that the look-ahead token
4578 is erroneous in the current state. This causes error processing to begin
4579 (@pxref{Error Recovery}).
4582 @section Reduce/Reduce Conflicts
4583 @cindex reduce/reduce conflict
4584 @cindex conflicts, reduce/reduce
4586 A reduce/reduce conflict occurs if there are two or more rules that apply
4587 to the same sequence of input. This usually indicates a serious error
4590 For example, here is an erroneous attempt to define a sequence
4591 of zero or more @code{word} groupings.
4594 sequence: /* empty */
4595 @{ printf ("empty sequence\n"); @}
4598 @{ printf ("added word %s\n", $2); @}
4601 maybeword: /* empty */
4602 @{ printf ("empty maybeword\n"); @}
4604 @{ printf ("single word %s\n", $1); @}
4609 The error is an ambiguity: there is more than one way to parse a single
4610 @code{word} into a @code{sequence}. It could be reduced to a
4611 @code{maybeword} and then into a @code{sequence} via the second rule.
4612 Alternatively, nothing-at-all could be reduced into a @code{sequence}
4613 via the first rule, and this could be combined with the @code{word}
4614 using the third rule for @code{sequence}.
4616 There is also more than one way to reduce nothing-at-all into a
4617 @code{sequence}. This can be done directly via the first rule,
4618 or indirectly via @code{maybeword} and then the second rule.
4620 You might think that this is a distinction without a difference, because it
4621 does not change whether any particular input is valid or not. But it does
4622 affect which actions are run. One parsing order runs the second rule's
4623 action; the other runs the first rule's action and the third rule's action.
4624 In this example, the output of the program changes.
4626 Bison resolves a reduce/reduce conflict by choosing to use the rule that
4627 appears first in the grammar, but it is very risky to rely on this. Every
4628 reduce/reduce conflict must be studied and usually eliminated. Here is the
4629 proper way to define @code{sequence}:
4632 sequence: /* empty */
4633 @{ printf ("empty sequence\n"); @}
4635 @{ printf ("added word %s\n", $2); @}
4639 Here is another common error that yields a reduce/reduce conflict:
4642 sequence: /* empty */
4644 | sequence redirects
4651 redirects:/* empty */
4652 | redirects redirect
4657 The intention here is to define a sequence which can contain either
4658 @code{word} or @code{redirect} groupings. The individual definitions of
4659 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
4660 three together make a subtle ambiguity: even an empty input can be parsed
4661 in infinitely many ways!
4663 Consider: nothing-at-all could be a @code{words}. Or it could be two
4664 @code{words} in a row, or three, or any number. It could equally well be a
4665 @code{redirects}, or two, or any number. Or it could be a @code{words}
4666 followed by three @code{redirects} and another @code{words}. And so on.
4668 Here are two ways to correct these rules. First, to make it a single level
4672 sequence: /* empty */
4678 Second, to prevent either a @code{words} or a @code{redirects}
4682 sequence: /* empty */
4684 | sequence redirects
4692 | redirects redirect
4696 @node Mystery Conflicts
4697 @section Mysterious Reduce/Reduce Conflicts
4699 Sometimes reduce/reduce conflicts can occur that don't look warranted.
4707 def: param_spec return_spec ','
4711 | name_list ':' type
4729 | name ',' name_list
4734 It would seem that this grammar can be parsed with only a single token
4735 of look-ahead: when a @code{param_spec} is being read, an @code{ID} is
4736 a @code{name} if a comma or colon follows, or a @code{type} if another
4737 @code{ID} follows. In other words, this grammar is LR(1).
4741 However, Bison, like most parser generators, cannot actually handle all
4742 LR(1) grammars. In this grammar, two contexts, that after an @code{ID}
4743 at the beginning of a @code{param_spec} and likewise at the beginning of
4744 a @code{return_spec}, are similar enough that Bison assumes they are the
4745 same. They appear similar because the same set of rules would be
4746 active---the rule for reducing to a @code{name} and that for reducing to
4747 a @code{type}. Bison is unable to determine at that stage of processing
4748 that the rules would require different look-ahead tokens in the two
4749 contexts, so it makes a single parser state for them both. Combining
4750 the two contexts causes a conflict later. In parser terminology, this
4751 occurrence means that the grammar is not LALR(1).
4753 In general, it is better to fix deficiencies than to document them. But
4754 this particular deficiency is intrinsically hard to fix; parser
4755 generators that can handle LR(1) grammars are hard to write and tend to
4756 produce parsers that are very large. In practice, Bison is more useful
4759 When the problem arises, you can often fix it by identifying the two
4760 parser states that are being confused, and adding something to make them
4761 look distinct. In the above example, adding one rule to
4762 @code{return_spec} as follows makes the problem go away:
4773 /* This rule is never used. */
4779 This corrects the problem because it introduces the possibility of an
4780 additional active rule in the context after the @code{ID} at the beginning of
4781 @code{return_spec}. This rule is not active in the corresponding context
4782 in a @code{param_spec}, so the two contexts receive distinct parser states.
4783 As long as the token @code{BOGUS} is never generated by @code{yylex},
4784 the added rule cannot alter the way actual input is parsed.
4786 In this particular example, there is another way to solve the problem:
4787 rewrite the rule for @code{return_spec} to use @code{ID} directly
4788 instead of via @code{name}. This also causes the two confusing
4789 contexts to have different sets of active rules, because the one for
4790 @code{return_spec} activates the altered rule for @code{return_spec}
4791 rather than the one for @code{name}.
4796 | name_list ':' type
4804 @node Generalized LR Parsing
4805 @section Generalized LR (GLR) Parsing
4807 @cindex generalized LR (GLR) parsing
4808 @cindex ambiguous grammars
4809 @cindex non-deterministic parsing
4811 Bison produces @emph{deterministic} parsers that choose uniquely
4812 when to reduce and which reduction to apply
4813 based on a summary of the preceding input and on one extra token of lookahead.
4814 As a result, normal Bison handles a proper subset of the family of
4815 context-free languages.
4816 Ambiguous grammars, since they have strings with more than one possible
4817 sequence of reductions cannot have deterministic parsers in this sense.
4818 The same is true of languages that require more than one symbol of
4819 lookahead, since the parser lacks the information necessary to make a
4820 decision at the point it must be made in a shift-reduce parser.
4821 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
4822 there are languages where Bison's particular choice of how to
4823 summarize the input seen so far loses necessary information.
4825 When you use the @samp{%glr-parser} declaration in your grammar file,
4826 Bison generates a parser that uses a different algorithm, called
4827 Generalized LR (or GLR). A Bison GLR parser uses the same basic
4828 algorithm for parsing as an ordinary Bison parser, but behaves
4829 differently in cases where there is a shift-reduce conflict that has not
4830 been resolved by precedence rules (@pxref{Precedence}) or a
4831 reduce-reduce conflict. When a GLR parser encounters such a situation, it
4832 effectively @emph{splits} into a several parsers, one for each possible
4833 shift or reduction. These parsers then proceed as usual, consuming
4834 tokens in lock-step. Some of the stacks may encounter other conflicts
4835 and split further, with the result that instead of a sequence of states,
4836 a Bison GLR parsing stack is what is in effect a tree of states.
4838 In effect, each stack represents a guess as to what the proper parse
4839 is. Additional input may indicate that a guess was wrong, in which case
4840 the appropriate stack silently disappears. Otherwise, the semantics
4841 actions generated in each stack are saved, rather than being executed
4842 immediately. When a stack disappears, its saved semantic actions never
4843 get executed. When a reduction causes two stacks to become equivalent,
4844 their sets of semantic actions are both saved with the state that
4845 results from the reduction. We say that two stacks are equivalent
4846 when they both represent the same sequence of states,
4847 and each pair of corresponding states represents a
4848 grammar symbol that produces the same segment of the input token
4851 Whenever the parser makes a transition from having multiple
4852 states to having one, it reverts to the normal LALR(1) parsing
4853 algorithm, after resolving and executing the saved-up actions.
4854 At this transition, some of the states on the stack will have semantic
4855 values that are sets (actually multisets) of possible actions. The
4856 parser tries to pick one of the actions by first finding one whose rule
4857 has the highest dynamic precedence, as set by the @samp{%dprec}
4858 declaration. Otherwise, if the alternative actions are not ordered by
4859 precedence, but there the same merging function is declared for both
4860 rules by the @samp{%merge} declaration,
4861 Bison resolves and evaluates both and then calls the merge function on
4862 the result. Otherwise, it reports an ambiguity.
4864 It is possible to use a data structure for the GLR parsing tree that
4865 permits the processing of any LALR(1) grammar in linear time (in the
4866 size of the input), any unambiguous (not necessarily LALR(1)) grammar in
4867 quadratic worst-case time, and any general (possibly ambiguous)
4868 context-free grammar in cubic worst-case time. However, Bison currently
4869 uses a simpler data structure that requires time proportional to the
4870 length of the input times the maximum number of stacks required for any
4871 prefix of the input. Thus, really ambiguous or non-deterministic
4872 grammars can require exponential time and space to process. Such badly
4873 behaving examples, however, are not generally of practical interest.
4874 Usually, non-determinism in a grammar is local---the parser is ``in
4875 doubt'' only for a few tokens at a time. Therefore, the current data
4876 structure should generally be adequate. On LALR(1) portions of a
4877 grammar, in particular, it is only slightly slower than with the default
4880 @node Stack Overflow
4881 @section Stack Overflow, and How to Avoid It
4882 @cindex stack overflow
4883 @cindex parser stack overflow
4884 @cindex overflow of parser stack
4886 The Bison parser stack can overflow if too many tokens are shifted and
4887 not reduced. When this happens, the parser function @code{yyparse}
4888 returns a nonzero value, pausing only to call @code{yyerror} to report
4892 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
4893 parser stack can become before a stack overflow occurs. Define the
4894 macro with a value that is an integer. This value is the maximum number
4895 of tokens that can be shifted (and not reduced) before overflow.
4896 It must be a constant expression whose value is known at compile time.
4898 The stack space allowed is not necessarily allocated. If you specify a
4899 large value for @code{YYMAXDEPTH}, the parser actually allocates a small
4900 stack at first, and then makes it bigger by stages as needed. This
4901 increasing allocation happens automatically and silently. Therefore,
4902 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
4903 space for ordinary inputs that do not need much stack.
4905 @cindex default stack limit
4906 The default value of @code{YYMAXDEPTH}, if you do not define it, is
4910 You can control how much stack is allocated initially by defining the
4911 macro @code{YYINITDEPTH}. This value too must be a compile-time
4912 constant integer. The default is 200.
4914 @node Error Recovery
4915 @chapter Error Recovery
4916 @cindex error recovery
4917 @cindex recovery from errors
4919 It is not usually acceptable to have a program terminate on a parse
4920 error. For example, a compiler should recover sufficiently to parse the
4921 rest of the input file and check it for errors; a calculator should accept
4924 In a simple interactive command parser where each input is one line, it may
4925 be sufficient to allow @code{yyparse} to return 1 on error and have the
4926 caller ignore the rest of the input line when that happens (and then call
4927 @code{yyparse} again). But this is inadequate for a compiler, because it
4928 forgets all the syntactic context leading up to the error. A syntax error
4929 deep within a function in the compiler input should not cause the compiler
4930 to treat the following line like the beginning of a source file.
4933 You can define how to recover from a syntax error by writing rules to
4934 recognize the special token @code{error}. This is a terminal symbol that
4935 is always defined (you need not declare it) and reserved for error
4936 handling. The Bison parser generates an @code{error} token whenever a
4937 syntax error happens; if you have provided a rule to recognize this token
4938 in the current context, the parse can continue.
4943 stmnts: /* empty string */
4949 The fourth rule in this example says that an error followed by a newline
4950 makes a valid addition to any @code{stmnts}.
4952 What happens if a syntax error occurs in the middle of an @code{exp}? The
4953 error recovery rule, interpreted strictly, applies to the precise sequence
4954 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
4955 the middle of an @code{exp}, there will probably be some additional tokens
4956 and subexpressions on the stack after the last @code{stmnts}, and there
4957 will be tokens to read before the next newline. So the rule is not
4958 applicable in the ordinary way.
4960 But Bison can force the situation to fit the rule, by discarding part of
4961 the semantic context and part of the input. First it discards states and
4962 objects from the stack until it gets back to a state in which the
4963 @code{error} token is acceptable. (This means that the subexpressions
4964 already parsed are discarded, back to the last complete @code{stmnts}.) At
4965 this point the @code{error} token can be shifted. Then, if the old
4966 look-ahead token is not acceptable to be shifted next, the parser reads
4967 tokens and discards them until it finds a token which is acceptable. In
4968 this example, Bison reads and discards input until the next newline
4969 so that the fourth rule can apply.
4971 The choice of error rules in the grammar is a choice of strategies for
4972 error recovery. A simple and useful strategy is simply to skip the rest of
4973 the current input line or current statement if an error is detected:
4976 stmnt: error ';' /* on error, skip until ';' is read */
4979 It is also useful to recover to the matching close-delimiter of an
4980 opening-delimiter that has already been parsed. Otherwise the
4981 close-delimiter will probably appear to be unmatched, and generate another,
4982 spurious error message:
4985 primary: '(' expr ')'
4991 Error recovery strategies are necessarily guesses. When they guess wrong,
4992 one syntax error often leads to another. In the above example, the error
4993 recovery rule guesses that an error is due to bad input within one
4994 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
4995 middle of a valid @code{stmnt}. After the error recovery rule recovers
4996 from the first error, another syntax error will be found straightaway,
4997 since the text following the spurious semicolon is also an invalid
5000 To prevent an outpouring of error messages, the parser will output no error
5001 message for another syntax error that happens shortly after the first; only
5002 after three consecutive input tokens have been successfully shifted will
5003 error messages resume.
5005 Note that rules which accept the @code{error} token may have actions, just
5006 as any other rules can.
5009 You can make error messages resume immediately by using the macro
5010 @code{yyerrok} in an action. If you do this in the error rule's action, no
5011 error messages will be suppressed. This macro requires no arguments;
5012 @samp{yyerrok;} is a valid C statement.
5015 The previous look-ahead token is reanalyzed immediately after an error. If
5016 this is unacceptable, then the macro @code{yyclearin} may be used to clear
5017 this token. Write the statement @samp{yyclearin;} in the error rule's
5020 For example, suppose that on a parse error, an error handling routine is
5021 called that advances the input stream to some point where parsing should
5022 once again commence. The next symbol returned by the lexical scanner is
5023 probably correct. The previous look-ahead token ought to be discarded
5024 with @samp{yyclearin;}.
5026 @vindex YYRECOVERING
5027 The macro @code{YYRECOVERING} stands for an expression that has the
5028 value 1 when the parser is recovering from a syntax error, and 0 the
5029 rest of the time. A value of 1 indicates that error messages are
5030 currently suppressed for new syntax errors.
5032 @node Context Dependency
5033 @chapter Handling Context Dependencies
5035 The Bison paradigm is to parse tokens first, then group them into larger
5036 syntactic units. In many languages, the meaning of a token is affected by
5037 its context. Although this violates the Bison paradigm, certain techniques
5038 (known as @dfn{kludges}) may enable you to write Bison parsers for such
5042 * Semantic Tokens:: Token parsing can depend on the semantic context.
5043 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
5044 * Tie-in Recovery:: Lexical tie-ins have implications for how
5045 error recovery rules must be written.
5048 (Actually, ``kludge'' means any technique that gets its job done but is
5049 neither clean nor robust.)
5051 @node Semantic Tokens
5052 @section Semantic Info in Token Types
5054 The C language has a context dependency: the way an identifier is used
5055 depends on what its current meaning is. For example, consider this:
5061 This looks like a function call statement, but if @code{foo} is a typedef
5062 name, then this is actually a declaration of @code{x}. How can a Bison
5063 parser for C decide how to parse this input?
5065 The method used in GNU C is to have two different token types,
5066 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
5067 identifier, it looks up the current declaration of the identifier in order
5068 to decide which token type to return: @code{TYPENAME} if the identifier is
5069 declared as a typedef, @code{IDENTIFIER} otherwise.
5071 The grammar rules can then express the context dependency by the choice of
5072 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
5073 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
5074 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
5075 is @emph{not} significant, such as in declarations that can shadow a
5076 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
5077 accepted---there is one rule for each of the two token types.
5079 This technique is simple to use if the decision of which kinds of
5080 identifiers to allow is made at a place close to where the identifier is
5081 parsed. But in C this is not always so: C allows a declaration to
5082 redeclare a typedef name provided an explicit type has been specified
5086 typedef int foo, bar, lose;
5087 static foo (bar); /* @r{redeclare @code{bar} as static variable} */
5088 static int foo (lose); /* @r{redeclare @code{foo} as function} */
5091 Unfortunately, the name being declared is separated from the declaration
5092 construct itself by a complicated syntactic structure---the ``declarator''.
5094 As a result, part of the Bison parser for C needs to be duplicated, with
5095 all the nonterminal names changed: once for parsing a declaration in
5096 which a typedef name can be redefined, and once for parsing a
5097 declaration in which that can't be done. Here is a part of the
5098 duplication, with actions omitted for brevity:
5102 declarator maybeasm '='
5104 | declarator maybeasm
5108 notype_declarator maybeasm '='
5110 | notype_declarator maybeasm
5115 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
5116 cannot. The distinction between @code{declarator} and
5117 @code{notype_declarator} is the same sort of thing.
5119 There is some similarity between this technique and a lexical tie-in
5120 (described next), in that information which alters the lexical analysis is
5121 changed during parsing by other parts of the program. The difference is
5122 here the information is global, and is used for other purposes in the
5123 program. A true lexical tie-in has a special-purpose flag controlled by
5124 the syntactic context.
5126 @node Lexical Tie-ins
5127 @section Lexical Tie-ins
5128 @cindex lexical tie-in
5130 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
5131 which is set by Bison actions, whose purpose is to alter the way tokens are
5134 For example, suppose we have a language vaguely like C, but with a special
5135 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
5136 an expression in parentheses in which all integers are hexadecimal. In
5137 particular, the token @samp{a1b} must be treated as an integer rather than
5138 as an identifier if it appears in that context. Here is how you can do it:
5157 @{ $$ = make_sum ($1, $3); @}
5171 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
5172 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
5173 with letters are parsed as integers if possible.
5175 The declaration of @code{hexflag} shown in the prologue of the parser file
5176 is needed to make it accessible to the actions (@pxref{Prologue, ,The Prologue}).
5177 You must also write the code in @code{yylex} to obey the flag.
5179 @node Tie-in Recovery
5180 @section Lexical Tie-ins and Error Recovery
5182 Lexical tie-ins make strict demands on any error recovery rules you have.
5183 @xref{Error Recovery}.
5185 The reason for this is that the purpose of an error recovery rule is to
5186 abort the parsing of one construct and resume in some larger construct.
5187 For example, in C-like languages, a typical error recovery rule is to skip
5188 tokens until the next semicolon, and then start a new statement, like this:
5192 | IF '(' expr ')' stmt @{ @dots{} @}
5199 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
5200 construct, this error rule will apply, and then the action for the
5201 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
5202 remain set for the entire rest of the input, or until the next @code{hex}
5203 keyword, causing identifiers to be misinterpreted as integers.
5205 To avoid this problem the error recovery rule itself clears @code{hexflag}.
5207 There may also be an error recovery rule that works within expressions.
5208 For example, there could be a rule which applies within parentheses
5209 and skips to the close-parenthesis:
5221 If this rule acts within the @code{hex} construct, it is not going to abort
5222 that construct (since it applies to an inner level of parentheses within
5223 the construct). Therefore, it should not clear the flag: the rest of
5224 the @code{hex} construct should be parsed with the flag still in effect.
5226 What if there is an error recovery rule which might abort out of the
5227 @code{hex} construct or might not, depending on circumstances? There is no
5228 way you can write the action to determine whether a @code{hex} construct is
5229 being aborted or not. So if you are using a lexical tie-in, you had better
5230 make sure your error recovery rules are not of this kind. Each rule must
5231 be such that you can be sure that it always will, or always won't, have to
5234 @c ================================================== Debugging Your Parser
5237 @chapter Debugging Your Parser
5239 Developing a parser can be a challenge, especially if you don't
5240 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
5241 Algorithm}). Even so, sometimes a detailed description of the automaton
5242 can help (@pxref{Understanding, , Understanding Your Parser}), or
5243 tracing the execution of the parser can give some insight on why it
5244 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
5247 * Understanding:: Understanding the structure of your parser.
5248 * Tracing:: Tracing the execution of your parser.
5252 @section Understanding Your Parser
5254 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
5255 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
5256 frequent than one would hope), looking at this automaton is required to
5257 tune or simply fix a parser. Bison provides two different
5258 representation of it, either textually or graphically (as a @sc{vcg}
5261 The textual file is generated when the options @option{--report} or
5262 @option{--verbose} are specified, see @xref{Invocation, , Invoking
5263 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
5264 the parser output file name, and adding @samp{.output} instead.
5265 Therefore, if the input file is @file{foo.y}, then the parser file is
5266 called @file{foo.tab.c} by default. As a consequence, the verbose
5267 output file is called @file{foo.output}.
5269 The following grammar file, @file{calc.y}, will be used in the sequel:
5286 @command{bison} reports:
5289 calc.y: warning: 1 useless nonterminal and 1 useless rule
5290 calc.y:11.1-7: warning: useless nonterminal: useless
5291 calc.y:11.8-12: warning: useless rule: useless: STR
5292 calc.y contains 7 shift/reduce conflicts.
5295 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
5296 creates a file @file{calc.output} with contents detailed below. The
5297 order of the output and the exact presentation might vary, but the
5298 interpretation is the same.
5300 The first section includes details on conflicts that were solved thanks
5301 to precedence and/or associativity:
5304 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
5305 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
5306 Conflict in state 8 between rule 2 and token '*' resolved as shift.
5311 The next section lists states that still have conflicts.
5314 State 8 contains 1 shift/reduce conflict.
5315 State 9 contains 1 shift/reduce conflict.
5316 State 10 contains 1 shift/reduce conflict.
5317 State 11 contains 4 shift/reduce conflicts.
5321 @cindex token, useless
5322 @cindex useless token
5323 @cindex nonterminal, useless
5324 @cindex useless nonterminal
5325 @cindex rule, useless
5326 @cindex useless rule
5327 The next section reports useless tokens, nonterminal and rules. Useless
5328 nonterminals and rules are removed in order to produce a smaller parser,
5329 but useless tokens are preserved, since they might be used by the
5330 scanner (note the difference between ``useless'' and ``not used''
5334 Useless nonterminals:
5337 Terminals which are not used:
5345 The next section reproduces the exact grammar that Bison used:
5351 0 5 $accept -> exp $end
5352 1 5 exp -> exp '+' exp
5353 2 6 exp -> exp '-' exp
5354 3 7 exp -> exp '*' exp
5355 4 8 exp -> exp '/' exp
5360 and reports the uses of the symbols:
5363 Terminals, with rules where they appear
5373 Nonterminals, with rules where they appear
5378 on left: 1 2 3 4 5, on right: 0 1 2 3 4
5383 @cindex pointed rule
5384 @cindex rule, pointed
5385 Bison then proceeds onto the automaton itself, describing each state
5386 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
5387 item is a production rule together with a point (marked by @samp{.})
5388 that the input cursor.
5393 $accept -> . exp $ (rule 0)
5395 NUM shift, and go to state 1
5400 This reads as follows: ``state 0 corresponds to being at the very
5401 beginning of the parsing, in the initial rule, right before the start
5402 symbol (here, @code{exp}). When the parser returns to this state right
5403 after having reduced a rule that produced an @code{exp}, the control
5404 flow jumps to state 2. If there is no such transition on a nonterminal
5405 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
5406 the parse stack, and the control flow jumps to state 1. Any other
5407 lookahead triggers a parse error.''
5409 @cindex core, item set
5410 @cindex item set core
5411 @cindex kernel, item set
5412 @cindex item set core
5413 Even though the only active rule in state 0 seems to be rule 0, the
5414 report lists @code{NUM} as a lookahead symbol because @code{NUM} can be
5415 at the beginning of any rule deriving an @code{exp}. By default Bison
5416 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
5417 you want to see more detail you can invoke @command{bison} with
5418 @option{--report=itemset} to list all the items, include those that can
5424 $accept -> . exp $ (rule 0)
5425 exp -> . exp '+' exp (rule 1)
5426 exp -> . exp '-' exp (rule 2)
5427 exp -> . exp '*' exp (rule 3)
5428 exp -> . exp '/' exp (rule 4)
5429 exp -> . NUM (rule 5)
5431 NUM shift, and go to state 1
5442 exp -> NUM . (rule 5)
5444 $default reduce using rule 5 (exp)
5448 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead
5449 (@samp{$default}), the parser will reduce it. If it was coming from
5450 state 0, then, after this reduction it will return to state 0, and will
5451 jump to state 2 (@samp{exp: go to state 2}).
5456 $accept -> exp . $ (rule 0)
5457 exp -> exp . '+' exp (rule 1)
5458 exp -> exp . '-' exp (rule 2)
5459 exp -> exp . '*' exp (rule 3)
5460 exp -> exp . '/' exp (rule 4)
5462 $ shift, and go to state 3
5463 '+' shift, and go to state 4
5464 '-' shift, and go to state 5
5465 '*' shift, and go to state 6
5466 '/' shift, and go to state 7
5470 In state 2, the automaton can only shift a symbol. For instance,
5471 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
5472 @samp{+}, it will be shifted on the parse stack, and the automaton
5473 control will jump to state 4, corresponding to the item @samp{exp -> exp
5474 '+' . exp}. Since there is no default action, any other token than
5475 those listed above will trigger a parse error.
5477 The state 3 is named the @dfn{final state}, or the @dfn{accepting
5483 $accept -> exp $ . (rule 0)
5489 the initial rule is completed (the start symbol and the end
5490 of input were read), the parsing exits successfully.
5492 The interpretation of states 4 to 7 is straightforward, and is left to
5498 exp -> exp '+' . exp (rule 1)
5500 NUM shift, and go to state 1
5506 exp -> exp '-' . exp (rule 2)
5508 NUM shift, and go to state 1
5514 exp -> exp '*' . exp (rule 3)
5516 NUM shift, and go to state 1
5522 exp -> exp '/' . exp (rule 4)
5524 NUM shift, and go to state 1
5529 As was announced in beginning of the report, @samp{State 8 contains 1
5530 shift/reduce conflict}:
5535 exp -> exp . '+' exp (rule 1)
5536 exp -> exp '+' exp . (rule 1)
5537 exp -> exp . '-' exp (rule 2)
5538 exp -> exp . '*' exp (rule 3)
5539 exp -> exp . '/' exp (rule 4)
5541 '*' shift, and go to state 6
5542 '/' shift, and go to state 7
5544 '/' [reduce using rule 1 (exp)]
5545 $default reduce using rule 1 (exp)
5548 Indeed, there are two actions associated to the lookahead @samp{/}:
5549 either shifting (and going to state 7), or reducing rule 1. The
5550 conflict means that either the grammar is ambiguous, or the parser lacks
5551 information to make the right decision. Indeed the grammar is
5552 ambiguous, as, since we did not specify the precedence of @samp{/}, the
5553 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
5554 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
5555 NUM}, which corresponds to reducing rule 1.
5557 Because in LALR(1) parsing a single decision can be made, Bison
5558 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
5559 Shift/Reduce Conflicts}. Discarded actions are reported in between
5562 Note that all the previous states had a single possible action: either
5563 shifting the next token and going to the corresponding state, or
5564 reducing a single rule. In the other cases, i.e., when shifting
5565 @emph{and} reducing is possible or when @emph{several} reductions are
5566 possible, the lookahead is required to select the action. State 8 is
5567 one such state: if the lookahead is @samp{*} or @samp{/} then the action
5568 is shifting, otherwise the action is reducing rule 1. In other words,
5569 the first two items, corresponding to rule 1, are not eligible when the
5570 lookahead is @samp{*}, since we specified that @samp{*} has higher
5571 precedence that @samp{+}. More generally, some items are eligible only
5572 with some set of possible lookaheads. When run with
5573 @option{--report=lookahead}, Bison specifies these lookaheads:
5578 exp -> exp . '+' exp [$, '+', '-', '/'] (rule 1)
5579 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
5580 exp -> exp . '-' exp (rule 2)
5581 exp -> exp . '*' exp (rule 3)
5582 exp -> exp . '/' exp (rule 4)
5584 '*' shift, and go to state 6
5585 '/' shift, and go to state 7
5587 '/' [reduce using rule 1 (exp)]
5588 $default reduce using rule 1 (exp)
5591 The remaining states are similar:
5596 exp -> exp . '+' exp (rule 1)
5597 exp -> exp . '-' exp (rule 2)
5598 exp -> exp '-' exp . (rule 2)
5599 exp -> exp . '*' exp (rule 3)
5600 exp -> exp . '/' exp (rule 4)
5602 '*' shift, and go to state 6
5603 '/' shift, and go to state 7
5605 '/' [reduce using rule 2 (exp)]
5606 $default reduce using rule 2 (exp)
5610 exp -> exp . '+' exp (rule 1)
5611 exp -> exp . '-' exp (rule 2)
5612 exp -> exp . '*' exp (rule 3)
5613 exp -> exp '*' exp . (rule 3)
5614 exp -> exp . '/' exp (rule 4)
5616 '/' shift, and go to state 7
5618 '/' [reduce using rule 3 (exp)]
5619 $default reduce using rule 3 (exp)
5623 exp -> exp . '+' exp (rule 1)
5624 exp -> exp . '-' exp (rule 2)
5625 exp -> exp . '*' exp (rule 3)
5626 exp -> exp . '/' exp (rule 4)
5627 exp -> exp '/' exp . (rule 4)
5629 '+' shift, and go to state 4
5630 '-' shift, and go to state 5
5631 '*' shift, and go to state 6
5632 '/' shift, and go to state 7
5634 '+' [reduce using rule 4 (exp)]
5635 '-' [reduce using rule 4 (exp)]
5636 '*' [reduce using rule 4 (exp)]
5637 '/' [reduce using rule 4 (exp)]
5638 $default reduce using rule 4 (exp)
5642 Observe that state 11 contains conflicts due to the lack of precedence
5643 of @samp{/} wrt @samp{+}, @samp{-}, and @samp{*}, but also because the
5644 associativity of @samp{/} is not specified.
5648 @section Tracing Your Parser
5651 @cindex tracing the parser
5653 If a Bison grammar compiles properly but doesn't do what you want when it
5654 runs, the @code{yydebug} parser-trace feature can help you figure out why.
5656 There are several means to enable compilation of trace facilities:
5659 @item the macro @code{YYDEBUG}
5661 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
5662 parser. This is compliant with POSIX Yacc. You could use
5663 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
5664 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
5667 @item the option @option{-t}, @option{--debug}
5668 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
5669 ,Invoking Bison}). This is POSIX compliant too.
5671 @item the directive @samp{%debug}
5673 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison
5674 Declaration Summary}). This is a Bison extension, which will prove
5675 useful when Bison will output parsers for languages that don't use a
5676 preprocessor. Useless POSIX and Yacc portability matter to you, this is
5677 the preferred solution.
5680 We suggest that you always enable the debug option so that debugging is
5683 The trace facility outputs messages with macro calls of the form
5684 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
5685 @var{format} and @var{args} are the usual @code{printf} format and
5686 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
5687 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
5688 and @code{YYPRINTF} is defined to @code{fprintf}.
5690 Once you have compiled the program with trace facilities, the way to
5691 request a trace is to store a nonzero value in the variable @code{yydebug}.
5692 You can do this by making the C code do it (in @code{main}, perhaps), or
5693 you can alter the value with a C debugger.
5695 Each step taken by the parser when @code{yydebug} is nonzero produces a
5696 line or two of trace information, written on @code{stderr}. The trace
5697 messages tell you these things:
5701 Each time the parser calls @code{yylex}, what kind of token was read.
5704 Each time a token is shifted, the depth and complete contents of the
5705 state stack (@pxref{Parser States}).
5708 Each time a rule is reduced, which rule it is, and the complete contents
5709 of the state stack afterward.
5712 To make sense of this information, it helps to refer to the listing file
5713 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
5714 Bison}). This file shows the meaning of each state in terms of
5715 positions in various rules, and also what each state will do with each
5716 possible input token. As you read the successive trace messages, you
5717 can see that the parser is functioning according to its specification in
5718 the listing file. Eventually you will arrive at the place where
5719 something undesirable happens, and you will see which parts of the
5720 grammar are to blame.
5722 The parser file is a C program and you can use C debuggers on it, but it's
5723 not easy to interpret what it is doing. The parser function is a
5724 finite-state machine interpreter, and aside from the actions it executes
5725 the same code over and over. Only the values of variables show where in
5726 the grammar it is working.
5729 The debugging information normally gives the token type of each token
5730 read, but not its semantic value. You can optionally define a macro
5731 named @code{YYPRINT} to provide a way to print the value. If you define
5732 @code{YYPRINT}, it should take three arguments. The parser will pass a
5733 standard I/O stream, the numeric code for the token type, and the token
5734 value (from @code{yylval}).
5736 Here is an example of @code{YYPRINT} suitable for the multi-function
5737 calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
5740 #define YYPRINT(file, type, value) yyprint (file, type, value)
5743 yyprint (FILE *file, int type, YYSTYPE value)
5746 fprintf (file, " %s", value.tptr->name);
5747 else if (type == NUM)
5748 fprintf (file, " %d", value.val);
5752 @c ================================================= Invoking Bison
5755 @chapter Invoking Bison
5756 @cindex invoking Bison
5757 @cindex Bison invocation
5758 @cindex options for invoking Bison
5760 The usual way to invoke Bison is as follows:
5766 Here @var{infile} is the grammar file name, which usually ends in
5767 @samp{.y}. The parser file's name is made by replacing the @samp{.y}
5768 with @samp{.tab.c}. Thus, the @samp{bison foo.y} filename yields
5769 @file{foo.tab.c}, and the @samp{bison hack/foo.y} filename yields
5770 @file{hack/foo.tab.c}. It's is also possible, in case you are writing
5771 C++ code instead of C in your grammar file, to name it @file{foo.ypp}
5772 or @file{foo.y++}. Then, the output files will take an extention like
5773 the given one as input (repectively @file{foo.tab.cpp} and @file{foo.tab.c++}).
5774 This feature takes effect with all options that manipulate filenames like
5775 @samp{-o} or @samp{-d}.
5780 bison -d @var{infile.yxx}
5783 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}. and
5786 bison -d @var{infile.y} -o @var{output.c++}
5789 will produce @file{output.c++} and @file{outfile.h++}.
5793 * Bison Options:: All the options described in detail,
5794 in alphabetical order by short options.
5795 * Option Cross Key:: Alphabetical list of long options.
5796 * VMS Invocation:: Bison command syntax on VMS.
5800 @section Bison Options
5802 Bison supports both traditional single-letter options and mnemonic long
5803 option names. Long option names are indicated with @samp{--} instead of
5804 @samp{-}. Abbreviations for option names are allowed as long as they
5805 are unique. When a long option takes an argument, like
5806 @samp{--file-prefix}, connect the option name and the argument with
5809 Here is a list of options that can be used with Bison, alphabetized by
5810 short option. It is followed by a cross key alphabetized by long
5813 @c Please, keep this ordered as in `bison --help'.
5819 Print a summary of the command-line options to Bison and exit.
5823 Print the version number of Bison and exit.
5828 Equivalent to @samp{-o y.tab.c}; the parser output file is called
5829 @file{y.tab.c}, and the other outputs are called @file{y.output} and
5830 @file{y.tab.h}. The purpose of this option is to imitate Yacc's output
5831 file name conventions. Thus, the following shell script can substitute
5844 @itemx --skeleton=@var{file}
5845 Specify the skeleton to use. You probably don't need this option unless
5846 you are developing Bison.
5850 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
5851 already defined, so that the debugging facilities are compiled.
5852 @xref{Tracing, ,Tracing Your Parser}.
5855 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
5857 @item -p @var{prefix}
5858 @itemx --name-prefix=@var{prefix}
5859 Pretend that @code{%name-prefix="@var{prefix}"} was specified.
5860 @xref{Decl Summary}.
5864 Don't put any @code{#line} preprocessor commands in the parser file.
5865 Ordinarily Bison puts them in the parser file so that the C compiler
5866 and debuggers will associate errors with your source file, the
5867 grammar file. This option causes them to associate errors with the
5868 parser file, treating it as an independent source file in its own right.
5872 Pretend that @code{%no-parser} was specified. @xref{Decl Summary}.
5875 @itemx --token-table
5876 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
5885 Pretend that @code{%defines} was specified, i.e., write an extra output
5886 file containing macro definitions for the token type names defined in
5887 the grammar and the semantic value type @code{YYSTYPE}, as well as a few
5888 @code{extern} variable declarations. @xref{Decl Summary}.
5890 @item --defines=@var{defines-file}
5891 Same as above, but save in the file @var{defines-file}.
5893 @item -b @var{file-prefix}
5894 @itemx --file-prefix=@var{prefix}
5895 Pretend that @code{%verbose} was specified, i.e, specify prefix to use
5896 for all Bison output file names. @xref{Decl Summary}.
5898 @item -r @var{things}
5899 @itemx --report=@var{things}
5900 Write an extra output file containing verbose description of the comma
5901 separated list of @var{things} among:
5905 Description of the grammar, conflicts (resolved and unresolved), and
5909 Implies @code{state} and augments the description of the automaton with
5910 each rule's lookahead set.
5913 Implies @code{state} and augments the description of the automaton with
5914 the full set of items for each state, instead of its core only.
5917 For instance, on the following grammar
5921 Pretend that @code{%verbose} was specified, i.e, write an extra output
5922 file containing verbose descriptions of the grammar and
5923 parser. @xref{Decl Summary}.
5925 @item -o @var{filename}
5926 @itemx --output=@var{filename}
5927 Specify the @var{filename} for the parser file.
5929 The other output files' names are constructed from @var{filename} as
5930 described under the @samp{-v} and @samp{-d} options.
5933 Output a VCG definition of the LALR(1) grammar automaton computed by
5934 Bison. If the grammar file is @file{foo.y}, the VCG output file will
5937 @item --graph=@var{graph-file}
5938 The behaviour of @var{--graph} is the same than @samp{-g}. The only
5939 difference is that it has an optionnal argument which is the name of
5940 the output graph filename.
5943 @node Option Cross Key
5944 @section Option Cross Key
5946 Here is a list of options, alphabetized by long option, to help you find
5947 the corresponding short option.
5950 \def\leaderfill{\leaders\hbox to 1em{\hss.\hss}\hfill}
5953 \line{ --debug \leaderfill -t}
5954 \line{ --defines \leaderfill -d}
5955 \line{ --file-prefix \leaderfill -b}
5956 \line{ --graph \leaderfill -g}
5957 \line{ --help \leaderfill -h}
5958 \line{ --name-prefix \leaderfill -p}
5959 \line{ --no-lines \leaderfill -l}
5960 \line{ --no-parser \leaderfill -n}
5961 \line{ --output \leaderfill -o}
5962 \line{ --token-table \leaderfill -k}
5963 \line{ --verbose \leaderfill -v}
5964 \line{ --version \leaderfill -V}
5965 \line{ --yacc \leaderfill -y}
5972 --defines=@var{defines-file} -d
5973 --file-prefix=@var{prefix} -b @var{file-prefix}
5974 --graph=@var{graph-file} -d
5976 --name-prefix=@var{prefix} -p @var{name-prefix}
5979 --output=@var{outfile} -o @var{outfile}
5987 @node VMS Invocation
5988 @section Invoking Bison under VMS
5989 @cindex invoking Bison under VMS
5992 The command line syntax for Bison on VMS is a variant of the usual
5993 Bison command syntax---adapted to fit VMS conventions.
5995 To find the VMS equivalent for any Bison option, start with the long
5996 option, and substitute a @samp{/} for the leading @samp{--}, and
5997 substitute a @samp{_} for each @samp{-} in the name of the long option.
5998 For example, the following invocation under VMS:
6001 bison /debug/name_prefix=bar foo.y
6005 is equivalent to the following command under POSIX.
6008 bison --debug --name-prefix=bar foo.y
6011 The VMS file system does not permit filenames such as
6012 @file{foo.tab.c}. In the above example, the output file
6013 would instead be named @file{foo_tab.c}.
6015 @node Table of Symbols
6016 @appendix Bison Symbols
6017 @cindex Bison symbols, table of
6018 @cindex symbols in Bison, table of
6022 In an action, the location of the left-hand side of the rule.
6023 @xref{Locations, , Locations Overview}.
6026 In an action, the location of the @var{n}-th symbol of the right-hand
6027 side of the rule. @xref{Locations, , Locations Overview}.
6030 In an action, the semantic value of the left-hand side of the rule.
6034 In an action, the semantic value of the @var{n}-th symbol of the
6035 right-hand side of the rule. @xref{Actions}.
6038 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
6039 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
6040 Start-Symbol}. It cannot be used in the grammar.
6043 The predefined token marking the end of the token stream. It cannot be
6044 used in the grammar.
6047 The predefined token onto which all undefined values returned by
6048 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
6052 A token name reserved for error recovery. This token may be used in
6053 grammar rules so as to allow the Bison parser to recognize an error in
6054 the grammar without halting the process. In effect, a sentence
6055 containing an error may be recognized as valid. On a parse error, the
6056 token @code{error} becomes the current look-ahead token. Actions
6057 corresponding to @code{error} are then executed, and the look-ahead
6058 token is reset to the token that originally caused the violation.
6059 @xref{Error Recovery}.
6062 Macro to pretend that an unrecoverable syntax error has occurred, by
6063 making @code{yyparse} return 1 immediately. The error reporting
6064 function @code{yyerror} is not called. @xref{Parser Function, ,The
6065 Parser Function @code{yyparse}}.
6068 Macro to pretend that a complete utterance of the language has been
6069 read, by making @code{yyparse} return 0 immediately.
6070 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6073 Macro to discard a value from the parser stack and fake a look-ahead
6074 token. @xref{Action Features, ,Special Features for Use in Actions}.
6077 Macro to define to equip the parser with tracing code. @xref{Tracing,
6078 ,Tracing Your Parser}.
6081 Macro to pretend that a syntax error has just been detected: call
6082 @code{yyerror} and then perform normal error recovery if possible
6083 (@pxref{Error Recovery}), or (if recovery is impossible) make
6084 @code{yyparse} return 1. @xref{Error Recovery}.
6086 @item YYERROR_VERBOSE
6087 Macro that you define with @code{#define} in the Bison declarations
6088 section to request verbose, specific error message strings when
6089 @code{yyerror} is called.
6092 Macro for specifying the initial size of the parser stack.
6093 @xref{Stack Overflow}.
6096 Macro for specifying an extra argument (or list of extra arguments) for
6097 @code{yyparse} to pass to @code{yylex}. @xref{Pure Calling,, Calling
6098 Conventions for Pure Parsers}.
6101 Macro for the data type of @code{yylloc}; a structure with four
6102 members. @xref{Location Type, , Data Types of Locations}.
6105 Default value for YYLTYPE.
6108 Macro for specifying the maximum size of the parser stack.
6109 @xref{Stack Overflow}.
6112 Macro for specifying the name of a parameter that @code{yyparse} should
6113 accept. @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
6116 Macro whose value indicates whether the parser is recovering from a
6117 syntax error. @xref{Action Features, ,Special Features for Use in Actions}.
6119 @item YYSTACK_USE_ALLOCA
6120 Macro used to control the use of @code{alloca}. If defined to @samp{0},
6121 the parser will not use @code{alloca} but @code{malloc} when trying to
6122 grow its internal stacks. Do @emph{not} define @code{YYSTACK_USE_ALLOCA}
6126 Macro for the data type of semantic values; @code{int} by default.
6127 @xref{Value Type, ,Data Types of Semantic Values}.
6130 External integer variable that contains the integer value of the current
6131 look-ahead token. (In a pure parser, it is a local variable within
6132 @code{yyparse}.) Error-recovery rule actions may examine this variable.
6133 @xref{Action Features, ,Special Features for Use in Actions}.
6136 Macro used in error-recovery rule actions. It clears the previous
6137 look-ahead token. @xref{Error Recovery}.
6140 External integer variable set to zero by default. If @code{yydebug}
6141 is given a nonzero value, the parser will output information on input
6142 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
6145 Macro to cause parser to recover immediately to its normal mode
6146 after a parse error. @xref{Error Recovery}.
6149 User-supplied function to be called by @code{yyparse} on error. The
6150 function receives one argument, a pointer to a character string
6151 containing an error message. @xref{Error Reporting, ,The Error
6152 Reporting Function @code{yyerror}}.
6155 User-supplied lexical analyzer function, called with no arguments to get
6156 the next token. @xref{Lexical, ,The Lexical Analyzer Function
6160 External variable in which @code{yylex} should place the semantic
6161 value associated with a token. (In a pure parser, it is a local
6162 variable within @code{yyparse}, and its address is passed to
6163 @code{yylex}.) @xref{Token Values, ,Semantic Values of Tokens}.
6166 External variable in which @code{yylex} should place the line and column
6167 numbers associated with a token. (In a pure parser, it is a local
6168 variable within @code{yyparse}, and its address is passed to
6169 @code{yylex}.) You can ignore this variable if you don't use the
6170 @samp{@@} feature in the grammar actions. @xref{Token Positions,
6171 ,Textual Positions of Tokens}.
6174 Global variable which Bison increments each time there is a parse error.
6175 (In a pure parser, it is a local variable within @code{yyparse}.)
6176 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
6179 The parser function produced by Bison; call this function to start
6180 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6183 Equip the parser for debugging. @xref{Decl Summary}.
6186 Bison declaration to create a header file meant for the scanner.
6187 @xref{Decl Summary}.
6190 Bison declaration to assign a precedence to a rule that is used at parse
6191 time to resolve reduce/reduce conflicts. @xref{GLR Parsers}.
6193 @item %file-prefix="@var{prefix}"
6194 Bison declaration to set the prefix of the output files. @xref{Decl
6198 Bison declaration to produce a GLR parser. @xref{GLR Parsers}.
6200 @c @item %source-extension
6201 @c Bison declaration to specify the generated parser output file extension.
6202 @c @xref{Decl Summary}.
6204 @c @item %header-extension
6205 @c Bison declaration to specify the generated parser header file extension
6206 @c if required. @xref{Decl Summary}.
6209 Bison declaration to assign left associativity to token(s).
6210 @xref{Precedence Decl, ,Operator Precedence}.
6213 Bison declaration to assign a merging function to a rule. If there is a
6214 reduce/reduce conflict with a rule having the same merging function, the
6215 function is applied to the two semantic values to get a single result.
6218 @item %name-prefix="@var{prefix}"
6219 Bison declaration to rename the external symbols. @xref{Decl Summary}.
6222 Bison declaration to avoid generating @code{#line} directives in the
6223 parser file. @xref{Decl Summary}.
6226 Bison declaration to assign non-associativity to token(s).
6227 @xref{Precedence Decl, ,Operator Precedence}.
6229 @item %output="@var{filename}"
6230 Bison declaration to set the name of the parser file. @xref{Decl
6234 Bison declaration to assign a precedence to a specific rule.
6235 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
6238 Bison declaration to request a pure (reentrant) parser.
6239 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6242 Bison declaration to assign right associativity to token(s).
6243 @xref{Precedence Decl, ,Operator Precedence}.
6246 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
6250 Bison declaration to declare token(s) without specifying precedence.
6251 @xref{Token Decl, ,Token Type Names}.
6254 Bison declaration to include a token name table in the parser file.
6255 @xref{Decl Summary}.
6258 Bison declaration to declare nonterminals. @xref{Type Decl,
6259 ,Nonterminal Symbols}.
6262 Bison declaration to specify several possible data types for semantic
6263 values. @xref{Union Decl, ,The Collection of Value Types}.
6268 These are the punctuation and delimiters used in Bison input:
6272 Delimiter used to separate the grammar rule section from the
6273 Bison declarations section or the epilogue.
6274 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
6277 All code listed between @samp{%@{} and @samp{%@}} is copied directly to
6278 the output file uninterpreted. Such code forms the prologue of the input
6279 file. @xref{Grammar Outline, ,Outline of a Bison
6283 Comment delimiters, as in C.
6286 Separates a rule's result from its components. @xref{Rules, ,Syntax of
6290 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
6293 Separates alternate rules for the same result nonterminal.
6294 @xref{Rules, ,Syntax of Grammar Rules}.
6302 @item Backus-Naur Form (BNF)
6303 Formal method of specifying context-free grammars. BNF was first used
6304 in the @cite{ALGOL-60} report, 1963. @xref{Language and Grammar,
6305 ,Languages and Context-Free Grammars}.
6307 @item Context-free grammars
6308 Grammars specified as rules that can be applied regardless of context.
6309 Thus, if there is a rule which says that an integer can be used as an
6310 expression, integers are allowed @emph{anywhere} an expression is
6311 permitted. @xref{Language and Grammar, ,Languages and Context-Free
6314 @item Dynamic allocation
6315 Allocation of memory that occurs during execution, rather than at
6316 compile time or on entry to a function.
6319 Analogous to the empty set in set theory, the empty string is a
6320 character string of length zero.
6322 @item Finite-state stack machine
6323 A ``machine'' that has discrete states in which it is said to exist at
6324 each instant in time. As input to the machine is processed, the
6325 machine moves from state to state as specified by the logic of the
6326 machine. In the case of the parser, the input is the language being
6327 parsed, and the states correspond to various stages in the grammar
6328 rules. @xref{Algorithm, ,The Bison Parser Algorithm }.
6330 @item Generalized LR (GLR)
6331 A parsing algorithm that can handle all context-free grammars, including those
6332 that are not LALR(1). It resolves situations that Bison's usual LALR(1)
6333 algorithm cannot by effectively splitting off multiple parsers, trying all
6334 possible parsers, and discarding those that fail in the light of additional
6335 right context. @xref{Generalized LR Parsing, ,Generalized LR Parsing}.
6338 A language construct that is (in general) grammatically divisible;
6339 for example, `expression' or `declaration' in C.
6340 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6342 @item Infix operator
6343 An arithmetic operator that is placed between the operands on which it
6344 performs some operation.
6347 A continuous flow of data between devices or programs.
6349 @item Language construct
6350 One of the typical usage schemas of the language. For example, one of
6351 the constructs of the C language is the @code{if} statement.
6352 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6354 @item Left associativity
6355 Operators having left associativity are analyzed from left to right:
6356 @samp{a+b+c} first computes @samp{a+b} and then combines with
6357 @samp{c}. @xref{Precedence, ,Operator Precedence}.
6359 @item Left recursion
6360 A rule whose result symbol is also its first component symbol; for
6361 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
6364 @item Left-to-right parsing
6365 Parsing a sentence of a language by analyzing it token by token from
6366 left to right. @xref{Algorithm, ,The Bison Parser Algorithm }.
6368 @item Lexical analyzer (scanner)
6369 A function that reads an input stream and returns tokens one by one.
6370 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
6372 @item Lexical tie-in
6373 A flag, set by actions in the grammar rules, which alters the way
6374 tokens are parsed. @xref{Lexical Tie-ins}.
6376 @item Literal string token
6377 A token which consists of two or more fixed characters. @xref{Symbols}.
6379 @item Look-ahead token
6380 A token already read but not yet shifted. @xref{Look-Ahead, ,Look-Ahead
6384 The class of context-free grammars that Bison (like most other parser
6385 generators) can handle; a subset of LR(1). @xref{Mystery Conflicts, ,
6386 Mysterious Reduce/Reduce Conflicts}.
6389 The class of context-free grammars in which at most one token of
6390 look-ahead is needed to disambiguate the parsing of any piece of input.
6392 @item Nonterminal symbol
6393 A grammar symbol standing for a grammatical construct that can
6394 be expressed through rules in terms of smaller constructs; in other
6395 words, a construct that is not a token. @xref{Symbols}.
6398 An error encountered during parsing of an input stream due to invalid
6399 syntax. @xref{Error Recovery}.
6402 A function that recognizes valid sentences of a language by analyzing
6403 the syntax structure of a set of tokens passed to it from a lexical
6406 @item Postfix operator
6407 An arithmetic operator that is placed after the operands upon which it
6408 performs some operation.
6411 Replacing a string of nonterminals and/or terminals with a single
6412 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
6416 A reentrant subprogram is a subprogram which can be in invoked any
6417 number of times in parallel, without interference between the various
6418 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6420 @item Reverse polish notation
6421 A language in which all operators are postfix operators.
6423 @item Right recursion
6424 A rule whose result symbol is also its last component symbol; for
6425 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
6429 In computer languages, the semantics are specified by the actions
6430 taken for each instance of the language, i.e., the meaning of
6431 each statement. @xref{Semantics, ,Defining Language Semantics}.
6434 A parser is said to shift when it makes the choice of analyzing
6435 further input from the stream rather than reducing immediately some
6436 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm }.
6438 @item Single-character literal
6439 A single character that is recognized and interpreted as is.
6440 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
6443 The nonterminal symbol that stands for a complete valid utterance in
6444 the language being parsed. The start symbol is usually listed as the
6445 first nonterminal symbol in a language specification.
6446 @xref{Start Decl, ,The Start-Symbol}.
6449 A data structure where symbol names and associated data are stored
6450 during parsing to allow for recognition and use of existing
6451 information in repeated uses of a symbol. @xref{Multi-function Calc}.
6454 A basic, grammatically indivisible unit of a language. The symbol
6455 that describes a token in the grammar is a terminal symbol.
6456 The input of the Bison parser is a stream of tokens which comes from
6457 the lexical analyzer. @xref{Symbols}.
6459 @item Terminal symbol
6460 A grammar symbol that has no rules in the grammar and therefore is
6461 grammatically indivisible. The piece of text it represents is a token.
6462 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6465 @node Copying This Manual
6466 @appendix Copying This Manual
6469 * GNU Free Documentation License:: License for copying this manual.