]> git.saurik.com Git - bison.git/blob - doc/bison.texinfo
* data/c.m4 (b4_identification, b4_user_args, b4_parse_param):
[bison.git] / doc / bison.texinfo
1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename bison.info
4 @include version.texi
5 @settitle Bison @value{VERSION}
6 @setchapternewpage odd
7
8 @finalout
9
10 @c SMALL BOOK version
11 @c This edition has been formatted so that you can format and print it in
12 @c the smallbook format.
13 @c @smallbook
14
15 @c Set following if you have the new `shorttitlepage' command
16 @c @clear shorttitlepage-enabled
17 @c @set shorttitlepage-enabled
18
19 @c ISPELL CHECK: done, 14 Jan 1993 --bob
20
21 @c Check COPYRIGHT dates. should be updated in the titlepage, ifinfo
22 @c titlepage; should NOT be changed in the GPL. --mew
23
24 @c FIXME: I don't understand this `iftex'. Obsolete? --akim.
25 @iftex
26 @syncodeindex fn cp
27 @syncodeindex vr cp
28 @syncodeindex tp cp
29 @end iftex
30 @ifinfo
31 @synindex fn cp
32 @synindex vr cp
33 @synindex tp cp
34 @end ifinfo
35 @comment %**end of header
36
37 @copying
38
39 This manual is for @acronym{GNU} Bison (version @value{VERSION},
40 @value{UPDATED}), the @acronym{GNU} parser generator.
41
42 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
43 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
44
45 @quotation
46 Permission is granted to copy, distribute and/or modify this document
47 under the terms of the @acronym{GNU} Free Documentation License,
48 Version 1.1 or any later version published by the Free Software
49 Foundation; with no Invariant Sections, with the Front-Cover texts
50 being ``A @acronym{GNU} Manual,'' and with the Back-Cover Texts as in
51 (a) below. A copy of the license is included in the section entitled
52 ``@acronym{GNU} Free Documentation License.''
53
54 (a) The @acronym{FSF}'s Back-Cover Text is: ``You have freedom to copy
55 and modify this @acronym{GNU} Manual, like @acronym{GNU} software.
56 Copies published by the Free Software Foundation raise funds for
57 @acronym{GNU} development.''
58 @end quotation
59 @end copying
60
61 @dircategory GNU programming tools
62 @direntry
63 * bison: (bison). @acronym{GNU} parser generator (Yacc replacement).
64 @end direntry
65
66 @ifset shorttitlepage-enabled
67 @shorttitlepage Bison
68 @end ifset
69 @titlepage
70 @title Bison
71 @subtitle The Yacc-compatible Parser Generator
72 @subtitle @value{UPDATED}, Bison Version @value{VERSION}
73
74 @author by Charles Donnelly and Richard Stallman
75
76 @page
77 @vskip 0pt plus 1filll
78 @insertcopying
79 @sp 2
80 Published by the Free Software Foundation @*
81 59 Temple Place, Suite 330 @*
82 Boston, MA 02111-1307 USA @*
83 Printed copies are available from the Free Software Foundation.@*
84 @acronym{ISBN} 1-882114-44-2
85 @sp 2
86 Cover art by Etienne Suvasa.
87 @end titlepage
88
89 @contents
90
91 @ifnottex
92 @node Top
93 @top Bison
94 @insertcopying
95 @end ifnottex
96
97 @menu
98 * Introduction::
99 * Conditions::
100 * Copying:: The @acronym{GNU} General Public License says
101 how you can copy and share Bison
102
103 Tutorial sections:
104 * Concepts:: Basic concepts for understanding Bison.
105 * Examples:: Three simple explained examples of using Bison.
106
107 Reference sections:
108 * Grammar File:: Writing Bison declarations and rules.
109 * Interface:: C-language interface to the parser function @code{yyparse}.
110 * Algorithm:: How the Bison parser works at run-time.
111 * Error Recovery:: Writing rules for error recovery.
112 * Context Dependency:: What to do if your language syntax is too
113 messy for Bison to handle straightforwardly.
114 * Debugging:: Understanding or debugging Bison parsers.
115 * Invocation:: How to run Bison (to produce the parser source file).
116 * Table of Symbols:: All the keywords of the Bison language are explained.
117 * Glossary:: Basic concepts are explained.
118 * FAQ:: Frequently Asked Questions
119 * Copying This Manual:: License for copying this manual.
120 * Index:: Cross-references to the text.
121
122 @detailmenu --- The Detailed Node Listing ---
123
124 The Concepts of Bison
125
126 * Language and Grammar:: Languages and context-free grammars,
127 as mathematical ideas.
128 * Grammar in Bison:: How we represent grammars for Bison's sake.
129 * Semantic Values:: Each token or syntactic grouping can have
130 a semantic value (the value of an integer,
131 the name of an identifier, etc.).
132 * Semantic Actions:: Each rule can have an action containing C code.
133 * Bison Parser:: What are Bison's input and output,
134 how is the output used?
135 * Stages:: Stages in writing and running Bison grammars.
136 * Grammar Layout:: Overall structure of a Bison grammar file.
137
138 Examples
139
140 * RPN Calc:: Reverse polish notation calculator;
141 a first example with no operator precedence.
142 * Infix Calc:: Infix (algebraic) notation calculator.
143 Operator precedence is introduced.
144 * Simple Error Recovery:: Continuing after syntax errors.
145 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
146 * Multi-function Calc:: Calculator with memory and trig functions.
147 It uses multiple data-types for semantic values.
148 * Exercises:: Ideas for improving the multi-function calculator.
149
150 Reverse Polish Notation Calculator
151
152 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
153 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
154 * Lexer: Rpcalc Lexer. The lexical analyzer.
155 * Main: Rpcalc Main. The controlling function.
156 * Error: Rpcalc Error. The error reporting function.
157 * Gen: Rpcalc Gen. Running Bison on the grammar file.
158 * Comp: Rpcalc Compile. Run the C compiler on the output code.
159
160 Grammar Rules for @code{rpcalc}
161
162 * Rpcalc Input::
163 * Rpcalc Line::
164 * Rpcalc Expr::
165
166 Location Tracking Calculator: @code{ltcalc}
167
168 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
169 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
170 * Lexer: Ltcalc Lexer. The lexical analyzer.
171
172 Multi-Function Calculator: @code{mfcalc}
173
174 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
175 * Rules: Mfcalc Rules. Grammar rules for the calculator.
176 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
177
178 Bison Grammar Files
179
180 * Grammar Outline:: Overall layout of the grammar file.
181 * Symbols:: Terminal and nonterminal symbols.
182 * Rules:: How to write grammar rules.
183 * Recursion:: Writing recursive rules.
184 * Semantics:: Semantic values and actions.
185 * Declarations:: All kinds of Bison declarations are described here.
186 * Multiple Parsers:: Putting more than one Bison parser in one program.
187
188 Outline of a Bison Grammar
189
190 * Prologue:: Syntax and usage of the prologue (declarations section).
191 * Bison Declarations:: Syntax and usage of the Bison declarations section.
192 * Grammar Rules:: Syntax and usage of the grammar rules section.
193 * Epilogue:: Syntax and usage of the epilogue (additional code section).
194
195 Defining Language Semantics
196
197 * Value Type:: Specifying one data type for all semantic values.
198 * Multiple Types:: Specifying several alternative data types.
199 * Actions:: An action is the semantic definition of a grammar rule.
200 * Action Types:: Specifying data types for actions to operate on.
201 * Mid-Rule Actions:: Most actions go at the end of a rule.
202 This says when, why and how to use the exceptional
203 action in the middle of a rule.
204
205 Bison Declarations
206
207 * Token Decl:: Declaring terminal symbols.
208 * Precedence Decl:: Declaring terminals with precedence and associativity.
209 * Union Decl:: Declaring the set of all semantic value types.
210 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
211 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
212 * Start Decl:: Specifying the start symbol.
213 * Pure Decl:: Requesting a reentrant parser.
214 * Decl Summary:: Table of all Bison declarations.
215
216 Parser C-Language Interface
217
218 * Parser Function:: How to call @code{yyparse} and what it returns.
219 * Lexical:: You must supply a function @code{yylex}
220 which reads tokens.
221 * Error Reporting:: You must supply a function @code{yyerror}.
222 * Action Features:: Special features for use in actions.
223
224 The Lexical Analyzer Function @code{yylex}
225
226 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
227 * Token Values:: How @code{yylex} must return the semantic value
228 of the token it has read.
229 * Token Positions:: How @code{yylex} must return the text position
230 (line number, etc.) of the token, if the
231 actions want that.
232 * Pure Calling:: How the calling convention differs
233 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
234
235 The Bison Parser Algorithm
236
237 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
238 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
239 * Precedence:: Operator precedence works by resolving conflicts.
240 * Contextual Precedence:: When an operator's precedence depends on context.
241 * Parser States:: The parser is a finite-state-machine with stack.
242 * Reduce/Reduce:: When two rules are applicable in the same situation.
243 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
244 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
245 * Stack Overflow:: What happens when stack gets full. How to avoid it.
246
247 Operator Precedence
248
249 * Why Precedence:: An example showing why precedence is needed.
250 * Using Precedence:: How to specify precedence in Bison grammars.
251 * Precedence Examples:: How these features are used in the previous example.
252 * How Precedence:: How they work.
253
254 Handling Context Dependencies
255
256 * Semantic Tokens:: Token parsing can depend on the semantic context.
257 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
258 * Tie-in Recovery:: Lexical tie-ins have implications for how
259 error recovery rules must be written.
260
261 Understanding or Debugging Your Parser
262
263 * Understanding:: Understanding the structure of your parser.
264 * Tracing:: Tracing the execution of your parser.
265
266 Invoking Bison
267
268 * Bison Options:: All the options described in detail,
269 in alphabetical order by short options.
270 * Option Cross Key:: Alphabetical list of long options.
271 * VMS Invocation:: Bison command syntax on @acronym{VMS}.
272
273 Frequently Asked Questions
274
275 * Parser Stack Overflow:: Breaking the Stack Limits
276
277 Copying This Manual
278
279 * GNU Free Documentation License:: License for copying this manual.
280
281 @end detailmenu
282 @end menu
283
284 @node Introduction
285 @unnumbered Introduction
286 @cindex introduction
287
288 @dfn{Bison} is a general-purpose parser generator that converts a
289 grammar description for an @acronym{LALR}(1) context-free grammar into a C
290 program to parse that grammar. Once you are proficient with Bison,
291 you may use it to develop a wide range of language parsers, from those
292 used in simple desk calculators to complex programming languages.
293
294 Bison is upward compatible with Yacc: all properly-written Yacc grammars
295 ought to work with Bison with no change. Anyone familiar with Yacc
296 should be able to use Bison with little trouble. You need to be fluent in
297 C programming in order to use Bison or to understand this manual.
298
299 We begin with tutorial chapters that explain the basic concepts of using
300 Bison and show three explained examples, each building on the last. If you
301 don't know Bison or Yacc, start by reading these chapters. Reference
302 chapters follow which describe specific aspects of Bison in detail.
303
304 Bison was written primarily by Robert Corbett; Richard Stallman made it
305 Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
306 multi-character string literals and other features.
307
308 This edition corresponds to version @value{VERSION} of Bison.
309
310 @node Conditions
311 @unnumbered Conditions for Using Bison
312
313 As of Bison version 1.24, we have changed the distribution terms for
314 @code{yyparse} to permit using Bison's output in nonfree programs when
315 Bison is generating C code for @acronym{LALR}(1) parsers. Formerly, these
316 parsers could be used only in programs that were free software.
317
318 The other @acronym{GNU} programming tools, such as the @acronym{GNU} C
319 compiler, have never
320 had such a requirement. They could always be used for nonfree
321 software. The reason Bison was different was not due to a special
322 policy decision; it resulted from applying the usual General Public
323 License to all of the Bison source code.
324
325 The output of the Bison utility---the Bison parser file---contains a
326 verbatim copy of a sizable piece of Bison, which is the code for the
327 @code{yyparse} function. (The actions from your grammar are inserted
328 into this function at one point, but the rest of the function is not
329 changed.) When we applied the @acronym{GPL} terms to the code for
330 @code{yyparse},
331 the effect was to restrict the use of Bison output to free software.
332
333 We didn't change the terms because of sympathy for people who want to
334 make software proprietary. @strong{Software should be free.} But we
335 concluded that limiting Bison's use to free software was doing little to
336 encourage people to make other software free. So we decided to make the
337 practical conditions for using Bison match the practical conditions for
338 using the other @acronym{GNU} tools.
339
340 This exception applies only when Bison is generating C code for a
341 @acronym{LALR}(1) parser; otherwise, the @acronym{GPL} terms operate
342 as usual. You can
343 tell whether the exception applies to your @samp{.c} output file by
344 inspecting it to see whether it says ``As a special exception, when
345 this file is copied by Bison into a Bison output file, you may use
346 that output file without restriction.''
347
348 @include gpl.texi
349
350 @node Concepts
351 @chapter The Concepts of Bison
352
353 This chapter introduces many of the basic concepts without which the
354 details of Bison will not make sense. If you do not already know how to
355 use Bison or Yacc, we suggest you start by reading this chapter carefully.
356
357 @menu
358 * Language and Grammar:: Languages and context-free grammars,
359 as mathematical ideas.
360 * Grammar in Bison:: How we represent grammars for Bison's sake.
361 * Semantic Values:: Each token or syntactic grouping can have
362 a semantic value (the value of an integer,
363 the name of an identifier, etc.).
364 * Semantic Actions:: Each rule can have an action containing C code.
365 * GLR Parsers:: Writing parsers for general context-free languages
366 * Locations Overview:: Tracking Locations.
367 * Bison Parser:: What are Bison's input and output,
368 how is the output used?
369 * Stages:: Stages in writing and running Bison grammars.
370 * Grammar Layout:: Overall structure of a Bison grammar file.
371 @end menu
372
373 @node Language and Grammar
374 @section Languages and Context-Free Grammars
375
376 @cindex context-free grammar
377 @cindex grammar, context-free
378 In order for Bison to parse a language, it must be described by a
379 @dfn{context-free grammar}. This means that you specify one or more
380 @dfn{syntactic groupings} and give rules for constructing them from their
381 parts. For example, in the C language, one kind of grouping is called an
382 `expression'. One rule for making an expression might be, ``An expression
383 can be made of a minus sign and another expression''. Another would be,
384 ``An expression can be an integer''. As you can see, rules are often
385 recursive, but there must be at least one rule which leads out of the
386 recursion.
387
388 @cindex @acronym{BNF}
389 @cindex Backus-Naur form
390 The most common formal system for presenting such rules for humans to read
391 is @dfn{Backus-Naur Form} or ``@acronym{BNF}'', which was developed in
392 order to specify the language Algol 60. Any grammar expressed in
393 @acronym{BNF} is a context-free grammar. The input to Bison is
394 essentially machine-readable @acronym{BNF}.
395
396 @cindex @acronym{LALR}(1) grammars
397 @cindex @acronym{LR}(1) grammars
398 There are various important subclasses of context-free grammar. Although it
399 can handle almost all context-free grammars, Bison is optimized for what
400 are called @acronym{LALR}(1) grammars.
401 In brief, in these grammars, it must be possible to
402 tell how to parse any portion of an input string with just a single
403 token of look-ahead. Strictly speaking, that is a description of an
404 @acronym{LR}(1) grammar, and @acronym{LALR}(1) involves additional
405 restrictions that are
406 hard to explain simply; but it is rare in actual practice to find an
407 @acronym{LR}(1) grammar that fails to be @acronym{LALR}(1).
408 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}, for
409 more information on this.
410
411 @cindex @acronym{GLR} parsing
412 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
413 @cindex ambiguous grammars
414 @cindex non-deterministic parsing
415 Parsers for @acronym{LALR}(1) grammars are @dfn{deterministic},
416 meaning roughly that
417 the next grammar rule to apply at any point in the input is uniquely
418 determined by the preceding input and a fixed, finite portion (called
419 a @dfn{look-ahead}) of the remaining input.
420 A context-free grammar can be @dfn{ambiguous}, meaning that
421 there are multiple ways to apply the grammar rules to get the some inputs.
422 Even unambiguous grammars can be @dfn{non-deterministic}, meaning that no
423 fixed look-ahead always suffices to determine the next grammar rule to apply.
424 With the proper declarations, Bison is also able to parse these more general
425 context-free grammars, using a technique known as @acronym{GLR} parsing (for
426 Generalized @acronym{LR}). Bison's @acronym{GLR} parsers are able to
427 handle any context-free
428 grammar for which the number of possible parses of any given string
429 is finite.
430
431 @cindex symbols (abstract)
432 @cindex token
433 @cindex syntactic grouping
434 @cindex grouping, syntactic
435 In the formal grammatical rules for a language, each kind of syntactic unit
436 or grouping is named by a @dfn{symbol}. Those which are built by grouping
437 smaller constructs according to grammatical rules are called
438 @dfn{nonterminal symbols}; those which can't be subdivided are called
439 @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
440 corresponding to a single terminal symbol a @dfn{token}, and a piece
441 corresponding to a single nonterminal symbol a @dfn{grouping}.
442
443 We can use the C language as an example of what symbols, terminal and
444 nonterminal, mean. The tokens of C are identifiers, constants (numeric and
445 string), and the various keywords, arithmetic operators and punctuation
446 marks. So the terminal symbols of a grammar for C include `identifier',
447 `number', `string', plus one symbol for each keyword, operator or
448 punctuation mark: `if', `return', `const', `static', `int', `char',
449 `plus-sign', `open-brace', `close-brace', `comma' and many more. (These
450 tokens can be subdivided into characters, but that is a matter of
451 lexicography, not grammar.)
452
453 Here is a simple C function subdivided into tokens:
454
455 @ifinfo
456 @example
457 int /* @r{keyword `int'} */
458 square (int x) /* @r{identifier, open-paren, identifier,}
459 @r{identifier, close-paren} */
460 @{ /* @r{open-brace} */
461 return x * x; /* @r{keyword `return', identifier, asterisk,
462 identifier, semicolon} */
463 @} /* @r{close-brace} */
464 @end example
465 @end ifinfo
466 @ifnotinfo
467 @example
468 int /* @r{keyword `int'} */
469 square (int x) /* @r{identifier, open-paren, identifier, identifier, close-paren} */
470 @{ /* @r{open-brace} */
471 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
472 @} /* @r{close-brace} */
473 @end example
474 @end ifnotinfo
475
476 The syntactic groupings of C include the expression, the statement, the
477 declaration, and the function definition. These are represented in the
478 grammar of C by nonterminal symbols `expression', `statement',
479 `declaration' and `function definition'. The full grammar uses dozens of
480 additional language constructs, each with its own nonterminal symbol, in
481 order to express the meanings of these four. The example above is a
482 function definition; it contains one declaration, and one statement. In
483 the statement, each @samp{x} is an expression and so is @samp{x * x}.
484
485 Each nonterminal symbol must have grammatical rules showing how it is made
486 out of simpler constructs. For example, one kind of C statement is the
487 @code{return} statement; this would be described with a grammar rule which
488 reads informally as follows:
489
490 @quotation
491 A `statement' can be made of a `return' keyword, an `expression' and a
492 `semicolon'.
493 @end quotation
494
495 @noindent
496 There would be many other rules for `statement', one for each kind of
497 statement in C.
498
499 @cindex start symbol
500 One nonterminal symbol must be distinguished as the special one which
501 defines a complete utterance in the language. It is called the @dfn{start
502 symbol}. In a compiler, this means a complete input program. In the C
503 language, the nonterminal symbol `sequence of definitions and declarations'
504 plays this role.
505
506 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
507 program---but it is not valid as an @emph{entire} C program. In the
508 context-free grammar of C, this follows from the fact that `expression' is
509 not the start symbol.
510
511 The Bison parser reads a sequence of tokens as its input, and groups the
512 tokens using the grammar rules. If the input is valid, the end result is
513 that the entire token sequence reduces to a single grouping whose symbol is
514 the grammar's start symbol. If we use a grammar for C, the entire input
515 must be a `sequence of definitions and declarations'. If not, the parser
516 reports a syntax error.
517
518 @node Grammar in Bison
519 @section From Formal Rules to Bison Input
520 @cindex Bison grammar
521 @cindex grammar, Bison
522 @cindex formal grammar
523
524 A formal grammar is a mathematical construct. To define the language
525 for Bison, you must write a file expressing the grammar in Bison syntax:
526 a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
527
528 A nonterminal symbol in the formal grammar is represented in Bison input
529 as an identifier, like an identifier in C@. By convention, it should be
530 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
531
532 The Bison representation for a terminal symbol is also called a @dfn{token
533 type}. Token types as well can be represented as C-like identifiers. By
534 convention, these identifiers should be upper case to distinguish them from
535 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
536 @code{RETURN}. A terminal symbol that stands for a particular keyword in
537 the language should be named after that keyword converted to upper case.
538 The terminal symbol @code{error} is reserved for error recovery.
539 @xref{Symbols}.
540
541 A terminal symbol can also be represented as a character literal, just like
542 a C character constant. You should do this whenever a token is just a
543 single character (parenthesis, plus-sign, etc.): use that same character in
544 a literal as the terminal symbol for that token.
545
546 A third way to represent a terminal symbol is with a C string constant
547 containing several characters. @xref{Symbols}, for more information.
548
549 The grammar rules also have an expression in Bison syntax. For example,
550 here is the Bison rule for a C @code{return} statement. The semicolon in
551 quotes is a literal character token, representing part of the C syntax for
552 the statement; the naked semicolon, and the colon, are Bison punctuation
553 used in every rule.
554
555 @example
556 stmt: RETURN expr ';'
557 ;
558 @end example
559
560 @noindent
561 @xref{Rules, ,Syntax of Grammar Rules}.
562
563 @node Semantic Values
564 @section Semantic Values
565 @cindex semantic value
566 @cindex value, semantic
567
568 A formal grammar selects tokens only by their classifications: for example,
569 if a rule mentions the terminal symbol `integer constant', it means that
570 @emph{any} integer constant is grammatically valid in that position. The
571 precise value of the constant is irrelevant to how to parse the input: if
572 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
573 grammatical.
574
575 But the precise value is very important for what the input means once it is
576 parsed. A compiler is useless if it fails to distinguish between 4, 1 and
577 3989 as constants in the program! Therefore, each token in a Bison grammar
578 has both a token type and a @dfn{semantic value}. @xref{Semantics,
579 ,Defining Language Semantics},
580 for details.
581
582 The token type is a terminal symbol defined in the grammar, such as
583 @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
584 you need to know to decide where the token may validly appear and how to
585 group it with other tokens. The grammar rules know nothing about tokens
586 except their types.
587
588 The semantic value has all the rest of the information about the
589 meaning of the token, such as the value of an integer, or the name of an
590 identifier. (A token such as @code{','} which is just punctuation doesn't
591 need to have any semantic value.)
592
593 For example, an input token might be classified as token type
594 @code{INTEGER} and have the semantic value 4. Another input token might
595 have the same token type @code{INTEGER} but value 3989. When a grammar
596 rule says that @code{INTEGER} is allowed, either of these tokens is
597 acceptable because each is an @code{INTEGER}. When the parser accepts the
598 token, it keeps track of the token's semantic value.
599
600 Each grouping can also have a semantic value as well as its nonterminal
601 symbol. For example, in a calculator, an expression typically has a
602 semantic value that is a number. In a compiler for a programming
603 language, an expression typically has a semantic value that is a tree
604 structure describing the meaning of the expression.
605
606 @node Semantic Actions
607 @section Semantic Actions
608 @cindex semantic actions
609 @cindex actions, semantic
610
611 In order to be useful, a program must do more than parse input; it must
612 also produce some output based on the input. In a Bison grammar, a grammar
613 rule can have an @dfn{action} made up of C statements. Each time the
614 parser recognizes a match for that rule, the action is executed.
615 @xref{Actions}.
616
617 Most of the time, the purpose of an action is to compute the semantic value
618 of the whole construct from the semantic values of its parts. For example,
619 suppose we have a rule which says an expression can be the sum of two
620 expressions. When the parser recognizes such a sum, each of the
621 subexpressions has a semantic value which describes how it was built up.
622 The action for this rule should create a similar sort of value for the
623 newly recognized larger expression.
624
625 For example, here is a rule that says an expression can be the sum of
626 two subexpressions:
627
628 @example
629 expr: expr '+' expr @{ $$ = $1 + $3; @}
630 ;
631 @end example
632
633 @noindent
634 The action says how to produce the semantic value of the sum expression
635 from the values of the two subexpressions.
636
637 @node GLR Parsers
638 @section Writing @acronym{GLR} Parsers
639 @cindex @acronym{GLR} parsing
640 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
641 @findex %glr-parser
642 @cindex conflicts
643 @cindex shift/reduce conflicts
644
645 In some grammars, there will be cases where Bison's standard @acronym{LALR}(1)
646 parsing algorithm cannot decide whether to apply a certain grammar rule
647 at a given point. That is, it may not be able to decide (on the basis
648 of the input read so far) which of two possible reductions (applications
649 of a grammar rule) applies, or whether to apply a reduction or read more
650 of the input and apply a reduction later in the input. These are known
651 respectively as @dfn{reduce/reduce} conflicts (@pxref{Reduce/Reduce}),
652 and @dfn{shift/reduce} conflicts (@pxref{Shift/Reduce}).
653
654 To use a grammar that is not easily modified to be @acronym{LALR}(1), a more
655 general parsing algorithm is sometimes necessary. If you include
656 @code{%glr-parser} among the Bison declarations in your file
657 (@pxref{Grammar Outline}), the result will be a Generalized
658 @acronym{LR} (@acronym{GLR})
659 parser. These parsers handle Bison grammars that contain no unresolved
660 conflicts (i.e., after applying precedence declarations) identically to
661 @acronym{LALR}(1) parsers. However, when faced with unresolved
662 shift/reduce and reduce/reduce conflicts, @acronym{GLR} parsers use
663 the simple expedient of doing
664 both, effectively cloning the parser to follow both possibilities. Each
665 of the resulting parsers can again split, so that at any given time,
666 there can be any number of possible parses being explored. The parsers
667 proceed in lockstep; that is, all of them consume (shift) a given input
668 symbol before any of them proceed to the next. Each of the cloned
669 parsers eventually meets one of two possible fates: either it runs into
670 a parsing error, in which case it simply vanishes, or it merges with
671 another parser, because the two of them have reduced the input to an
672 identical set of symbols.
673
674 During the time that there are multiple parsers, semantic actions are
675 recorded, but not performed. When a parser disappears, its recorded
676 semantic actions disappear as well, and are never performed. When a
677 reduction makes two parsers identical, causing them to merge, Bison
678 records both sets of semantic actions. Whenever the last two parsers
679 merge, reverting to the single-parser case, Bison resolves all the
680 outstanding actions either by precedences given to the grammar rules
681 involved, or by performing both actions, and then calling a designated
682 user-defined function on the resulting values to produce an arbitrary
683 merged result.
684
685 Let's consider an example, vastly simplified from a C++ grammar.
686
687 @example
688 %@{
689 #define YYSTYPE const char*
690 %@}
691
692 %token TYPENAME ID
693
694 %right '='
695 %left '+'
696
697 %glr-parser
698
699 %%
700
701 prog :
702 | prog stmt @{ printf ("\n"); @}
703 ;
704
705 stmt : expr ';' %dprec 1
706 | decl %dprec 2
707 ;
708
709 expr : ID @{ printf ("%s ", $$); @}
710 | TYPENAME '(' expr ')'
711 @{ printf ("%s <cast> ", $1); @}
712 | expr '+' expr @{ printf ("+ "); @}
713 | expr '=' expr @{ printf ("= "); @}
714 ;
715
716 decl : TYPENAME declarator ';'
717 @{ printf ("%s <declare> ", $1); @}
718 | TYPENAME declarator '=' expr ';'
719 @{ printf ("%s <init-declare> ", $1); @}
720 ;
721
722 declarator : ID @{ printf ("\"%s\" ", $1); @}
723 | '(' declarator ')'
724 ;
725 @end example
726
727 @noindent
728 This models a problematic part of the C++ grammar---the ambiguity between
729 certain declarations and statements. For example,
730
731 @example
732 T (x) = y+z;
733 @end example
734
735 @noindent
736 parses as either an @code{expr} or a @code{stmt}
737 (assuming that @samp{T} is recognized as a @code{TYPENAME} and
738 @samp{x} as an @code{ID}).
739 Bison detects this as a reduce/reduce conflict between the rules
740 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
741 time it encounters @code{x} in the example above. The two @code{%dprec}
742 declarations, however, give precedence to interpreting the example as a
743 @code{decl}, which implies that @code{x} is a declarator.
744 The parser therefore prints
745
746 @example
747 "x" y z + T <init-declare>
748 @end example
749
750 Consider a different input string for this parser:
751
752 @example
753 T (x) + y;
754 @end example
755
756 @noindent
757 Here, there is no ambiguity (this cannot be parsed as a declaration).
758 However, at the time the Bison parser encounters @code{x}, it does not
759 have enough information to resolve the reduce/reduce conflict (again,
760 between @code{x} as an @code{expr} or a @code{declarator}). In this
761 case, no precedence declaration is used. Instead, the parser splits
762 into two, one assuming that @code{x} is an @code{expr}, and the other
763 assuming @code{x} is a @code{declarator}. The second of these parsers
764 then vanishes when it sees @code{+}, and the parser prints
765
766 @example
767 x T <cast> y +
768 @end example
769
770 Suppose that instead of resolving the ambiguity, you wanted to see all
771 the possibilities. For this purpose, we must @dfn{merge} the semantic
772 actions of the two possible parsers, rather than choosing one over the
773 other. To do so, you could change the declaration of @code{stmt} as
774 follows:
775
776 @example
777 stmt : expr ';' %merge <stmtMerge>
778 | decl %merge <stmtMerge>
779 ;
780 @end example
781
782 @noindent
783
784 and define the @code{stmtMerge} function as:
785
786 @example
787 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1)
788 @{
789 printf ("<OR> ");
790 return "";
791 @}
792 @end example
793
794 @noindent
795 with an accompanying forward declaration
796 in the C declarations at the beginning of the file:
797
798 @example
799 %@{
800 #define YYSTYPE const char*
801 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
802 %@}
803 @end example
804
805 @noindent
806 With these declarations, the resulting parser will parse the first example
807 as both an @code{expr} and a @code{decl}, and print
808
809 @example
810 "x" y z + T <init-declare> x T <cast> y z + = <OR>
811 @end example
812
813
814 @node Locations Overview
815 @section Locations
816 @cindex location
817 @cindex textual position
818 @cindex position, textual
819
820 Many applications, like interpreters or compilers, have to produce verbose
821 and useful error messages. To achieve this, one must be able to keep track of
822 the @dfn{textual position}, or @dfn{location}, of each syntactic construct.
823 Bison provides a mechanism for handling these locations.
824
825 Each token has a semantic value. In a similar fashion, each token has an
826 associated location, but the type of locations is the same for all tokens and
827 groupings. Moreover, the output parser is equipped with a default data
828 structure for storing locations (@pxref{Locations}, for more details).
829
830 Like semantic values, locations can be reached in actions using a dedicated
831 set of constructs. In the example above, the location of the whole grouping
832 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
833 @code{@@3}.
834
835 When a rule is matched, a default action is used to compute the semantic value
836 of its left hand side (@pxref{Actions}). In the same way, another default
837 action is used for locations. However, the action for locations is general
838 enough for most cases, meaning there is usually no need to describe for each
839 rule how @code{@@$} should be formed. When building a new location for a given
840 grouping, the default behavior of the output parser is to take the beginning
841 of the first symbol, and the end of the last symbol.
842
843 @node Bison Parser
844 @section Bison Output: the Parser File
845 @cindex Bison parser
846 @cindex Bison utility
847 @cindex lexical analyzer, purpose
848 @cindex parser
849
850 When you run Bison, you give it a Bison grammar file as input. The output
851 is a C source file that parses the language described by the grammar.
852 This file is called a @dfn{Bison parser}. Keep in mind that the Bison
853 utility and the Bison parser are two distinct programs: the Bison utility
854 is a program whose output is the Bison parser that becomes part of your
855 program.
856
857 The job of the Bison parser is to group tokens into groupings according to
858 the grammar rules---for example, to build identifiers and operators into
859 expressions. As it does this, it runs the actions for the grammar rules it
860 uses.
861
862 The tokens come from a function called the @dfn{lexical analyzer} that
863 you must supply in some fashion (such as by writing it in C). The Bison
864 parser calls the lexical analyzer each time it wants a new token. It
865 doesn't know what is ``inside'' the tokens (though their semantic values
866 may reflect this). Typically the lexical analyzer makes the tokens by
867 parsing characters of text, but Bison does not depend on this.
868 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
869
870 The Bison parser file is C code which defines a function named
871 @code{yyparse} which implements that grammar. This function does not make
872 a complete C program: you must supply some additional functions. One is
873 the lexical analyzer. Another is an error-reporting function which the
874 parser calls to report an error. In addition, a complete C program must
875 start with a function called @code{main}; you have to provide this, and
876 arrange for it to call @code{yyparse} or the parser will never run.
877 @xref{Interface, ,Parser C-Language Interface}.
878
879 Aside from the token type names and the symbols in the actions you
880 write, all symbols defined in the Bison parser file itself
881 begin with @samp{yy} or @samp{YY}. This includes interface functions
882 such as the lexical analyzer function @code{yylex}, the error reporting
883 function @code{yyerror} and the parser function @code{yyparse} itself.
884 This also includes numerous identifiers used for internal purposes.
885 Therefore, you should avoid using C identifiers starting with @samp{yy}
886 or @samp{YY} in the Bison grammar file except for the ones defined in
887 this manual.
888
889 In some cases the Bison parser file includes system headers, and in
890 those cases your code should respect the identifiers reserved by those
891 headers. On some non-@acronym{GNU} hosts, @code{<alloca.h>},
892 @code{<stddef.h>}, and @code{<stdlib.h>} are included as needed to
893 declare memory allocators and related types. Other system headers may
894 be included if you define @code{YYDEBUG} to a nonzero value
895 (@pxref{Tracing, ,Tracing Your Parser}).
896
897 @node Stages
898 @section Stages in Using Bison
899 @cindex stages in using Bison
900 @cindex using Bison
901
902 The actual language-design process using Bison, from grammar specification
903 to a working compiler or interpreter, has these parts:
904
905 @enumerate
906 @item
907 Formally specify the grammar in a form recognized by Bison
908 (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
909 in the language, describe the action that is to be taken when an
910 instance of that rule is recognized. The action is described by a
911 sequence of C statements.
912
913 @item
914 Write a lexical analyzer to process input and pass tokens to the parser.
915 The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
916 Lexical Analyzer Function @code{yylex}}). It could also be produced
917 using Lex, but the use of Lex is not discussed in this manual.
918
919 @item
920 Write a controlling function that calls the Bison-produced parser.
921
922 @item
923 Write error-reporting routines.
924 @end enumerate
925
926 To turn this source code as written into a runnable program, you
927 must follow these steps:
928
929 @enumerate
930 @item
931 Run Bison on the grammar to produce the parser.
932
933 @item
934 Compile the code output by Bison, as well as any other source files.
935
936 @item
937 Link the object files to produce the finished product.
938 @end enumerate
939
940 @node Grammar Layout
941 @section The Overall Layout of a Bison Grammar
942 @cindex grammar file
943 @cindex file format
944 @cindex format of grammar file
945 @cindex layout of Bison grammar
946
947 The input file for the Bison utility is a @dfn{Bison grammar file}. The
948 general form of a Bison grammar file is as follows:
949
950 @example
951 %@{
952 @var{Prologue}
953 %@}
954
955 @var{Bison declarations}
956
957 %%
958 @var{Grammar rules}
959 %%
960 @var{Epilogue}
961 @end example
962
963 @noindent
964 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
965 in every Bison grammar file to separate the sections.
966
967 The prologue may define types and variables used in the actions. You can
968 also use preprocessor commands to define macros used there, and use
969 @code{#include} to include header files that do any of these things.
970
971 The Bison declarations declare the names of the terminal and nonterminal
972 symbols, and may also describe operator precedence and the data types of
973 semantic values of various symbols.
974
975 The grammar rules define how to construct each nonterminal symbol from its
976 parts.
977
978 The epilogue can contain any code you want to use. Often the definition of
979 the lexical analyzer @code{yylex} goes here, plus subroutines called by the
980 actions in the grammar rules. In a simple program, all the rest of the
981 program can go here.
982
983 @node Examples
984 @chapter Examples
985 @cindex simple examples
986 @cindex examples, simple
987
988 Now we show and explain three sample programs written using Bison: a
989 reverse polish notation calculator, an algebraic (infix) notation
990 calculator, and a multi-function calculator. All three have been tested
991 under BSD Unix 4.3; each produces a usable, though limited, interactive
992 desk-top calculator.
993
994 These examples are simple, but Bison grammars for real programming
995 languages are written the same way.
996 @ifinfo
997 You can copy these examples out of the Info file and into a source file
998 to try them.
999 @end ifinfo
1000
1001 @menu
1002 * RPN Calc:: Reverse polish notation calculator;
1003 a first example with no operator precedence.
1004 * Infix Calc:: Infix (algebraic) notation calculator.
1005 Operator precedence is introduced.
1006 * Simple Error Recovery:: Continuing after syntax errors.
1007 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1008 * Multi-function Calc:: Calculator with memory and trig functions.
1009 It uses multiple data-types for semantic values.
1010 * Exercises:: Ideas for improving the multi-function calculator.
1011 @end menu
1012
1013 @node RPN Calc
1014 @section Reverse Polish Notation Calculator
1015 @cindex reverse polish notation
1016 @cindex polish notation calculator
1017 @cindex @code{rpcalc}
1018 @cindex calculator, simple
1019
1020 The first example is that of a simple double-precision @dfn{reverse polish
1021 notation} calculator (a calculator using postfix operators). This example
1022 provides a good starting point, since operator precedence is not an issue.
1023 The second example will illustrate how operator precedence is handled.
1024
1025 The source code for this calculator is named @file{rpcalc.y}. The
1026 @samp{.y} extension is a convention used for Bison input files.
1027
1028 @menu
1029 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
1030 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1031 * Lexer: Rpcalc Lexer. The lexical analyzer.
1032 * Main: Rpcalc Main. The controlling function.
1033 * Error: Rpcalc Error. The error reporting function.
1034 * Gen: Rpcalc Gen. Running Bison on the grammar file.
1035 * Comp: Rpcalc Compile. Run the C compiler on the output code.
1036 @end menu
1037
1038 @node Rpcalc Decls
1039 @subsection Declarations for @code{rpcalc}
1040
1041 Here are the C and Bison declarations for the reverse polish notation
1042 calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1043
1044 @example
1045 /* Reverse polish notation calculator. */
1046
1047 %@{
1048 #define YYSTYPE double
1049 #include <math.h>
1050 %@}
1051
1052 %token NUM
1053
1054 %% /* Grammar rules and actions follow. */
1055 @end example
1056
1057 The declarations section (@pxref{Prologue, , The prologue}) contains two
1058 preprocessor directives.
1059
1060 The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1061 specifying the C data type for semantic values of both tokens and
1062 groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1063 Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1064 don't define it, @code{int} is the default. Because we specify
1065 @code{double}, each token and each expression has an associated value,
1066 which is a floating point number.
1067
1068 The @code{#include} directive is used to declare the exponentiation
1069 function @code{pow}.
1070
1071 The second section, Bison declarations, provides information to Bison
1072 about the token types (@pxref{Bison Declarations, ,The Bison
1073 Declarations Section}). Each terminal symbol that is not a
1074 single-character literal must be declared here. (Single-character
1075 literals normally don't need to be declared.) In this example, all the
1076 arithmetic operators are designated by single-character literals, so the
1077 only terminal symbol that needs to be declared is @code{NUM}, the token
1078 type for numeric constants.
1079
1080 @node Rpcalc Rules
1081 @subsection Grammar Rules for @code{rpcalc}
1082
1083 Here are the grammar rules for the reverse polish notation calculator.
1084
1085 @example
1086 input: /* empty */
1087 | input line
1088 ;
1089
1090 line: '\n'
1091 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1092 ;
1093
1094 exp: NUM @{ $$ = $1; @}
1095 | exp exp '+' @{ $$ = $1 + $2; @}
1096 | exp exp '-' @{ $$ = $1 - $2; @}
1097 | exp exp '*' @{ $$ = $1 * $2; @}
1098 | exp exp '/' @{ $$ = $1 / $2; @}
1099 /* Exponentiation */
1100 | exp exp '^' @{ $$ = pow ($1, $2); @}
1101 /* Unary minus */
1102 | exp 'n' @{ $$ = -$1; @}
1103 ;
1104 %%
1105 @end example
1106
1107 The groupings of the rpcalc ``language'' defined here are the expression
1108 (given the name @code{exp}), the line of input (@code{line}), and the
1109 complete input transcript (@code{input}). Each of these nonterminal
1110 symbols has several alternate rules, joined by the @samp{|} punctuator
1111 which is read as ``or''. The following sections explain what these rules
1112 mean.
1113
1114 The semantics of the language is determined by the actions taken when a
1115 grouping is recognized. The actions are the C code that appears inside
1116 braces. @xref{Actions}.
1117
1118 You must specify these actions in C, but Bison provides the means for
1119 passing semantic values between the rules. In each action, the
1120 pseudo-variable @code{$$} stands for the semantic value for the grouping
1121 that the rule is going to construct. Assigning a value to @code{$$} is the
1122 main job of most actions. The semantic values of the components of the
1123 rule are referred to as @code{$1}, @code{$2}, and so on.
1124
1125 @menu
1126 * Rpcalc Input::
1127 * Rpcalc Line::
1128 * Rpcalc Expr::
1129 @end menu
1130
1131 @node Rpcalc Input
1132 @subsubsection Explanation of @code{input}
1133
1134 Consider the definition of @code{input}:
1135
1136 @example
1137 input: /* empty */
1138 | input line
1139 ;
1140 @end example
1141
1142 This definition reads as follows: ``A complete input is either an empty
1143 string, or a complete input followed by an input line''. Notice that
1144 ``complete input'' is defined in terms of itself. This definition is said
1145 to be @dfn{left recursive} since @code{input} appears always as the
1146 leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1147
1148 The first alternative is empty because there are no symbols between the
1149 colon and the first @samp{|}; this means that @code{input} can match an
1150 empty string of input (no tokens). We write the rules this way because it
1151 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1152 It's conventional to put an empty alternative first and write the comment
1153 @samp{/* empty */} in it.
1154
1155 The second alternate rule (@code{input line}) handles all nontrivial input.
1156 It means, ``After reading any number of lines, read one more line if
1157 possible.'' The left recursion makes this rule into a loop. Since the
1158 first alternative matches empty input, the loop can be executed zero or
1159 more times.
1160
1161 The parser function @code{yyparse} continues to process input until a
1162 grammatical error is seen or the lexical analyzer says there are no more
1163 input tokens; we will arrange for the latter to happen at end-of-input.
1164
1165 @node Rpcalc Line
1166 @subsubsection Explanation of @code{line}
1167
1168 Now consider the definition of @code{line}:
1169
1170 @example
1171 line: '\n'
1172 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1173 ;
1174 @end example
1175
1176 The first alternative is a token which is a newline character; this means
1177 that rpcalc accepts a blank line (and ignores it, since there is no
1178 action). The second alternative is an expression followed by a newline.
1179 This is the alternative that makes rpcalc useful. The semantic value of
1180 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1181 question is the first symbol in the alternative. The action prints this
1182 value, which is the result of the computation the user asked for.
1183
1184 This action is unusual because it does not assign a value to @code{$$}. As
1185 a consequence, the semantic value associated with the @code{line} is
1186 uninitialized (its value will be unpredictable). This would be a bug if
1187 that value were ever used, but we don't use it: once rpcalc has printed the
1188 value of the user's input line, that value is no longer needed.
1189
1190 @node Rpcalc Expr
1191 @subsubsection Explanation of @code{expr}
1192
1193 The @code{exp} grouping has several rules, one for each kind of expression.
1194 The first rule handles the simplest expressions: those that are just numbers.
1195 The second handles an addition-expression, which looks like two expressions
1196 followed by a plus-sign. The third handles subtraction, and so on.
1197
1198 @example
1199 exp: NUM
1200 | exp exp '+' @{ $$ = $1 + $2; @}
1201 | exp exp '-' @{ $$ = $1 - $2; @}
1202 @dots{}
1203 ;
1204 @end example
1205
1206 We have used @samp{|} to join all the rules for @code{exp}, but we could
1207 equally well have written them separately:
1208
1209 @example
1210 exp: NUM ;
1211 exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1212 exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1213 @dots{}
1214 @end example
1215
1216 Most of the rules have actions that compute the value of the expression in
1217 terms of the value of its parts. For example, in the rule for addition,
1218 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1219 the second one. The third component, @code{'+'}, has no meaningful
1220 associated semantic value, but if it had one you could refer to it as
1221 @code{$3}. When @code{yyparse} recognizes a sum expression using this
1222 rule, the sum of the two subexpressions' values is produced as the value of
1223 the entire expression. @xref{Actions}.
1224
1225 You don't have to give an action for every rule. When a rule has no
1226 action, Bison by default copies the value of @code{$1} into @code{$$}.
1227 This is what happens in the first rule (the one that uses @code{NUM}).
1228
1229 The formatting shown here is the recommended convention, but Bison does
1230 not require it. You can add or change white space as much as you wish.
1231 For example, this:
1232
1233 @example
1234 exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{}
1235 @end example
1236
1237 @noindent
1238 means the same thing as this:
1239
1240 @example
1241 exp: NUM
1242 | exp exp '+' @{ $$ = $1 + $2; @}
1243 | @dots{}
1244 @end example
1245
1246 @noindent
1247 The latter, however, is much more readable.
1248
1249 @node Rpcalc Lexer
1250 @subsection The @code{rpcalc} Lexical Analyzer
1251 @cindex writing a lexical analyzer
1252 @cindex lexical analyzer, writing
1253
1254 The lexical analyzer's job is low-level parsing: converting characters
1255 or sequences of characters into tokens. The Bison parser gets its
1256 tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1257 Analyzer Function @code{yylex}}.
1258
1259 Only a simple lexical analyzer is needed for the @acronym{RPN}
1260 calculator. This
1261 lexical analyzer skips blanks and tabs, then reads in numbers as
1262 @code{double} and returns them as @code{NUM} tokens. Any other character
1263 that isn't part of a number is a separate token. Note that the token-code
1264 for such a single-character token is the character itself.
1265
1266 The return value of the lexical analyzer function is a numeric code which
1267 represents a token type. The same text used in Bison rules to stand for
1268 this token type is also a C expression for the numeric code for the type.
1269 This works in two ways. If the token type is a character literal, then its
1270 numeric code is that of the character; you can use the same
1271 character literal in the lexical analyzer to express the number. If the
1272 token type is an identifier, that identifier is defined by Bison as a C
1273 macro whose definition is the appropriate number. In this example,
1274 therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1275
1276 The semantic value of the token (if it has one) is stored into the
1277 global variable @code{yylval}, which is where the Bison parser will look
1278 for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1279 defined at the beginning of the grammar; @pxref{Rpcalc Decls,
1280 ,Declarations for @code{rpcalc}}.)
1281
1282 A token type code of zero is returned if the end-of-input is encountered.
1283 (Bison recognizes any nonpositive value as indicating end-of-input.)
1284
1285 Here is the code for the lexical analyzer:
1286
1287 @example
1288 @group
1289 /* The lexical analyzer returns a double floating point
1290 number on the stack and the token NUM, or the numeric code
1291 of the character read if not a number. It skips all blanks
1292 and tabs, and returns 0 for end-of-input. */
1293
1294 #include <ctype.h>
1295 @end group
1296
1297 @group
1298 int
1299 yylex (void)
1300 @{
1301 int c;
1302
1303 /* Skip white space. */
1304 while ((c = getchar ()) == ' ' || c == '\t')
1305 ;
1306 @end group
1307 @group
1308 /* Process numbers. */
1309 if (c == '.' || isdigit (c))
1310 @{
1311 ungetc (c, stdin);
1312 scanf ("%lf", &yylval);
1313 return NUM;
1314 @}
1315 @end group
1316 @group
1317 /* Return end-of-input. */
1318 if (c == EOF)
1319 return 0;
1320 /* Return a single char. */
1321 return c;
1322 @}
1323 @end group
1324 @end example
1325
1326 @node Rpcalc Main
1327 @subsection The Controlling Function
1328 @cindex controlling function
1329 @cindex main function in simple example
1330
1331 In keeping with the spirit of this example, the controlling function is
1332 kept to the bare minimum. The only requirement is that it call
1333 @code{yyparse} to start the process of parsing.
1334
1335 @example
1336 @group
1337 int
1338 main (void)
1339 @{
1340 return yyparse ();
1341 @}
1342 @end group
1343 @end example
1344
1345 @node Rpcalc Error
1346 @subsection The Error Reporting Routine
1347 @cindex error reporting routine
1348
1349 When @code{yyparse} detects a syntax error, it calls the error reporting
1350 function @code{yyerror} to print an error message (usually but not
1351 always @code{"parse error"}). It is up to the programmer to supply
1352 @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1353 here is the definition we will use:
1354
1355 @example
1356 @group
1357 #include <stdio.h>
1358
1359 void
1360 yyerror (const char *s) /* called by yyparse on error */
1361 @{
1362 printf ("%s\n", s);
1363 @}
1364 @end group
1365 @end example
1366
1367 After @code{yyerror} returns, the Bison parser may recover from the error
1368 and continue parsing if the grammar contains a suitable error rule
1369 (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1370 have not written any error rules in this example, so any invalid input will
1371 cause the calculator program to exit. This is not clean behavior for a
1372 real calculator, but it is adequate for the first example.
1373
1374 @node Rpcalc Gen
1375 @subsection Running Bison to Make the Parser
1376 @cindex running Bison (introduction)
1377
1378 Before running Bison to produce a parser, we need to decide how to
1379 arrange all the source code in one or more source files. For such a
1380 simple example, the easiest thing is to put everything in one file. The
1381 definitions of @code{yylex}, @code{yyerror} and @code{main} go at the
1382 end, in the epilogue of the file
1383 (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1384
1385 For a large project, you would probably have several source files, and use
1386 @code{make} to arrange to recompile them.
1387
1388 With all the source in a single file, you use the following command to
1389 convert it into a parser file:
1390
1391 @example
1392 bison @var{file_name}.y
1393 @end example
1394
1395 @noindent
1396 In this example the file was called @file{rpcalc.y} (for ``Reverse Polish
1397 @sc{calc}ulator''). Bison produces a file named @file{@var{file_name}.tab.c},
1398 removing the @samp{.y} from the original file name. The file output by
1399 Bison contains the source code for @code{yyparse}. The additional
1400 functions in the input file (@code{yylex}, @code{yyerror} and @code{main})
1401 are copied verbatim to the output.
1402
1403 @node Rpcalc Compile
1404 @subsection Compiling the Parser File
1405 @cindex compiling the parser
1406
1407 Here is how to compile and run the parser file:
1408
1409 @example
1410 @group
1411 # @r{List files in current directory.}
1412 $ @kbd{ls}
1413 rpcalc.tab.c rpcalc.y
1414 @end group
1415
1416 @group
1417 # @r{Compile the Bison parser.}
1418 # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1419 $ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
1420 @end group
1421
1422 @group
1423 # @r{List files again.}
1424 $ @kbd{ls}
1425 rpcalc rpcalc.tab.c rpcalc.y
1426 @end group
1427 @end example
1428
1429 The file @file{rpcalc} now contains the executable code. Here is an
1430 example session using @code{rpcalc}.
1431
1432 @example
1433 $ @kbd{rpcalc}
1434 @kbd{4 9 +}
1435 13
1436 @kbd{3 7 + 3 4 5 *+-}
1437 -13
1438 @kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
1439 13
1440 @kbd{5 6 / 4 n +}
1441 -3.166666667
1442 @kbd{3 4 ^} @r{Exponentiation}
1443 81
1444 @kbd{^D} @r{End-of-file indicator}
1445 $
1446 @end example
1447
1448 @node Infix Calc
1449 @section Infix Notation Calculator: @code{calc}
1450 @cindex infix notation calculator
1451 @cindex @code{calc}
1452 @cindex calculator, infix notation
1453
1454 We now modify rpcalc to handle infix operators instead of postfix. Infix
1455 notation involves the concept of operator precedence and the need for
1456 parentheses nested to arbitrary depth. Here is the Bison code for
1457 @file{calc.y}, an infix desk-top calculator.
1458
1459 @example
1460 /* Infix notation calculator--calc */
1461
1462 %@{
1463 #define YYSTYPE double
1464 #include <math.h>
1465 %@}
1466
1467 /* Bison Declarations */
1468 %token NUM
1469 %left '-' '+'
1470 %left '*' '/'
1471 %left NEG /* negation--unary minus */
1472 %right '^' /* exponentiation */
1473
1474 /* Grammar follows */
1475 %%
1476 input: /* empty string */
1477 | input line
1478 ;
1479
1480 line: '\n'
1481 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1482 ;
1483
1484 exp: NUM @{ $$ = $1; @}
1485 | exp '+' exp @{ $$ = $1 + $3; @}
1486 | exp '-' exp @{ $$ = $1 - $3; @}
1487 | exp '*' exp @{ $$ = $1 * $3; @}
1488 | exp '/' exp @{ $$ = $1 / $3; @}
1489 | '-' exp %prec NEG @{ $$ = -$2; @}
1490 | exp '^' exp @{ $$ = pow ($1, $3); @}
1491 | '(' exp ')' @{ $$ = $2; @}
1492 ;
1493 %%
1494 @end example
1495
1496 @noindent
1497 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1498 same as before.
1499
1500 There are two important new features shown in this code.
1501
1502 In the second section (Bison declarations), @code{%left} declares token
1503 types and says they are left-associative operators. The declarations
1504 @code{%left} and @code{%right} (right associativity) take the place of
1505 @code{%token} which is used to declare a token type name without
1506 associativity. (These tokens are single-character literals, which
1507 ordinarily don't need to be declared. We declare them here to specify
1508 the associativity.)
1509
1510 Operator precedence is determined by the line ordering of the
1511 declarations; the higher the line number of the declaration (lower on
1512 the page or screen), the higher the precedence. Hence, exponentiation
1513 has the highest precedence, unary minus (@code{NEG}) is next, followed
1514 by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator
1515 Precedence}.
1516
1517 The other important new feature is the @code{%prec} in the grammar
1518 section for the unary minus operator. The @code{%prec} simply instructs
1519 Bison that the rule @samp{| '-' exp} has the same precedence as
1520 @code{NEG}---in this case the next-to-highest. @xref{Contextual
1521 Precedence, ,Context-Dependent Precedence}.
1522
1523 Here is a sample run of @file{calc.y}:
1524
1525 @need 500
1526 @example
1527 $ @kbd{calc}
1528 @kbd{4 + 4.5 - (34/(8*3+-3))}
1529 6.880952381
1530 @kbd{-56 + 2}
1531 -54
1532 @kbd{3 ^ 2}
1533 9
1534 @end example
1535
1536 @node Simple Error Recovery
1537 @section Simple Error Recovery
1538 @cindex error recovery, simple
1539
1540 Up to this point, this manual has not addressed the issue of @dfn{error
1541 recovery}---how to continue parsing after the parser detects a syntax
1542 error. All we have handled is error reporting with @code{yyerror}.
1543 Recall that by default @code{yyparse} returns after calling
1544 @code{yyerror}. This means that an erroneous input line causes the
1545 calculator program to exit. Now we show how to rectify this deficiency.
1546
1547 The Bison language itself includes the reserved word @code{error}, which
1548 may be included in the grammar rules. In the example below it has
1549 been added to one of the alternatives for @code{line}:
1550
1551 @example
1552 @group
1553 line: '\n'
1554 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1555 | error '\n' @{ yyerrok; @}
1556 ;
1557 @end group
1558 @end example
1559
1560 This addition to the grammar allows for simple error recovery in the
1561 event of a parse error. If an expression that cannot be evaluated is
1562 read, the error will be recognized by the third rule for @code{line},
1563 and parsing will continue. (The @code{yyerror} function is still called
1564 upon to print its message as well.) The action executes the statement
1565 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
1566 that error recovery is complete (@pxref{Error Recovery}). Note the
1567 difference between @code{yyerrok} and @code{yyerror}; neither one is a
1568 misprint.
1569
1570 This form of error recovery deals with syntax errors. There are other
1571 kinds of errors; for example, division by zero, which raises an exception
1572 signal that is normally fatal. A real calculator program must handle this
1573 signal and use @code{longjmp} to return to @code{main} and resume parsing
1574 input lines; it would also have to discard the rest of the current line of
1575 input. We won't discuss this issue further because it is not specific to
1576 Bison programs.
1577
1578 @node Location Tracking Calc
1579 @section Location Tracking Calculator: @code{ltcalc}
1580 @cindex location tracking calculator
1581 @cindex @code{ltcalc}
1582 @cindex calculator, location tracking
1583
1584 This example extends the infix notation calculator with location
1585 tracking. This feature will be used to improve the error messages. For
1586 the sake of clarity, this example is a simple integer calculator, since
1587 most of the work needed to use locations will be done in the lexical
1588 analyzer.
1589
1590 @menu
1591 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
1592 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
1593 * Lexer: Ltcalc Lexer. The lexical analyzer.
1594 @end menu
1595
1596 @node Ltcalc Decls
1597 @subsection Declarations for @code{ltcalc}
1598
1599 The C and Bison declarations for the location tracking calculator are
1600 the same as the declarations for the infix notation calculator.
1601
1602 @example
1603 /* Location tracking calculator. */
1604
1605 %@{
1606 #define YYSTYPE int
1607 #include <math.h>
1608 %@}
1609
1610 /* Bison declarations. */
1611 %token NUM
1612
1613 %left '-' '+'
1614 %left '*' '/'
1615 %left NEG
1616 %right '^'
1617
1618 %% /* Grammar follows */
1619 @end example
1620
1621 @noindent
1622 Note there are no declarations specific to locations. Defining a data
1623 type for storing locations is not needed: we will use the type provided
1624 by default (@pxref{Location Type, ,Data Types of Locations}), which is a
1625 four member structure with the following integer fields:
1626 @code{first_line}, @code{first_column}, @code{last_line} and
1627 @code{last_column}.
1628
1629 @node Ltcalc Rules
1630 @subsection Grammar Rules for @code{ltcalc}
1631
1632 Whether handling locations or not has no effect on the syntax of your
1633 language. Therefore, grammar rules for this example will be very close
1634 to those of the previous example: we will only modify them to benefit
1635 from the new information.
1636
1637 Here, we will use locations to report divisions by zero, and locate the
1638 wrong expressions or subexpressions.
1639
1640 @example
1641 @group
1642 input : /* empty */
1643 | input line
1644 ;
1645 @end group
1646
1647 @group
1648 line : '\n'
1649 | exp '\n' @{ printf ("%d\n", $1); @}
1650 ;
1651 @end group
1652
1653 @group
1654 exp : NUM @{ $$ = $1; @}
1655 | exp '+' exp @{ $$ = $1 + $3; @}
1656 | exp '-' exp @{ $$ = $1 - $3; @}
1657 | exp '*' exp @{ $$ = $1 * $3; @}
1658 @end group
1659 @group
1660 | exp '/' exp
1661 @{
1662 if ($3)
1663 $$ = $1 / $3;
1664 else
1665 @{
1666 $$ = 1;
1667 fprintf (stderr, "%d.%d-%d.%d: division by zero",
1668 @@3.first_line, @@3.first_column,
1669 @@3.last_line, @@3.last_column);
1670 @}
1671 @}
1672 @end group
1673 @group
1674 | '-' exp %preg NEG @{ $$ = -$2; @}
1675 | exp '^' exp @{ $$ = pow ($1, $3); @}
1676 | '(' exp ')' @{ $$ = $2; @}
1677 @end group
1678 @end example
1679
1680 This code shows how to reach locations inside of semantic actions, by
1681 using the pseudo-variables @code{@@@var{n}} for rule components, and the
1682 pseudo-variable @code{@@$} for groupings.
1683
1684 We don't need to assign a value to @code{@@$}: the output parser does it
1685 automatically. By default, before executing the C code of each action,
1686 @code{@@$} is set to range from the beginning of @code{@@1} to the end
1687 of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
1688 can be redefined (@pxref{Location Default Action, , Default Action for
1689 Locations}), and for very specific rules, @code{@@$} can be computed by
1690 hand.
1691
1692 @node Ltcalc Lexer
1693 @subsection The @code{ltcalc} Lexical Analyzer.
1694
1695 Until now, we relied on Bison's defaults to enable location
1696 tracking. The next step is to rewrite the lexical analyzer, and make it
1697 able to feed the parser with the token locations, as it already does for
1698 semantic values.
1699
1700 To this end, we must take into account every single character of the
1701 input text, to avoid the computed locations of being fuzzy or wrong:
1702
1703 @example
1704 @group
1705 int
1706 yylex (void)
1707 @{
1708 int c;
1709
1710 /* Skip white space. */
1711 while ((c = getchar ()) == ' ' || c == '\t')
1712 ++yylloc.last_column;
1713
1714 /* Step. */
1715 yylloc.first_line = yylloc.last_line;
1716 yylloc.first_column = yylloc.last_column;
1717 @end group
1718
1719 @group
1720 /* Process numbers. */
1721 if (isdigit (c))
1722 @{
1723 yylval = c - '0';
1724 ++yylloc.last_column;
1725 while (isdigit (c = getchar ()))
1726 @{
1727 ++yylloc.last_column;
1728 yylval = yylval * 10 + c - '0';
1729 @}
1730 ungetc (c, stdin);
1731 return NUM;
1732 @}
1733 @end group
1734
1735 /* Return end-of-input. */
1736 if (c == EOF)
1737 return 0;
1738
1739 /* Return a single char, and update location. */
1740 if (c == '\n')
1741 @{
1742 ++yylloc.last_line;
1743 yylloc.last_column = 0;
1744 @}
1745 else
1746 ++yylloc.last_column;
1747 return c;
1748 @}
1749 @end example
1750
1751 Basically, the lexical analyzer performs the same processing as before:
1752 it skips blanks and tabs, and reads numbers or single-character tokens.
1753 In addition, it updates @code{yylloc}, the global variable (of type
1754 @code{YYLTYPE}) containing the token's location.
1755
1756 Now, each time this function returns a token, the parser has its number
1757 as well as its semantic value, and its location in the text. The last
1758 needed change is to initialize @code{yylloc}, for example in the
1759 controlling function:
1760
1761 @example
1762 @group
1763 int
1764 main (void)
1765 @{
1766 yylloc.first_line = yylloc.last_line = 1;
1767 yylloc.first_column = yylloc.last_column = 0;
1768 return yyparse ();
1769 @}
1770 @end group
1771 @end example
1772
1773 Remember that computing locations is not a matter of syntax. Every
1774 character must be associated to a location update, whether it is in
1775 valid input, in comments, in literal strings, and so on.
1776
1777 @node Multi-function Calc
1778 @section Multi-Function Calculator: @code{mfcalc}
1779 @cindex multi-function calculator
1780 @cindex @code{mfcalc}
1781 @cindex calculator, multi-function
1782
1783 Now that the basics of Bison have been discussed, it is time to move on to
1784 a more advanced problem. The above calculators provided only five
1785 functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
1786 be nice to have a calculator that provides other mathematical functions such
1787 as @code{sin}, @code{cos}, etc.
1788
1789 It is easy to add new operators to the infix calculator as long as they are
1790 only single-character literals. The lexical analyzer @code{yylex} passes
1791 back all nonnumber characters as tokens, so new grammar rules suffice for
1792 adding a new operator. But we want something more flexible: built-in
1793 functions whose syntax has this form:
1794
1795 @example
1796 @var{function_name} (@var{argument})
1797 @end example
1798
1799 @noindent
1800 At the same time, we will add memory to the calculator, by allowing you
1801 to create named variables, store values in them, and use them later.
1802 Here is a sample session with the multi-function calculator:
1803
1804 @example
1805 $ @kbd{mfcalc}
1806 @kbd{pi = 3.141592653589}
1807 3.1415926536
1808 @kbd{sin(pi)}
1809 0.0000000000
1810 @kbd{alpha = beta1 = 2.3}
1811 2.3000000000
1812 @kbd{alpha}
1813 2.3000000000
1814 @kbd{ln(alpha)}
1815 0.8329091229
1816 @kbd{exp(ln(beta1))}
1817 2.3000000000
1818 $
1819 @end example
1820
1821 Note that multiple assignment and nested function calls are permitted.
1822
1823 @menu
1824 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
1825 * Rules: Mfcalc Rules. Grammar rules for the calculator.
1826 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
1827 @end menu
1828
1829 @node Mfcalc Decl
1830 @subsection Declarations for @code{mfcalc}
1831
1832 Here are the C and Bison declarations for the multi-function calculator.
1833
1834 @smallexample
1835 %@{
1836 #include <math.h> /* For math functions, cos(), sin(), etc. */
1837 #include "calc.h" /* Contains definition of `symrec' */
1838 %@}
1839 %union @{
1840 double val; /* For returning numbers. */
1841 symrec *tptr; /* For returning symbol-table pointers */
1842 @}
1843
1844 %token <val> NUM /* Simple double precision number */
1845 %token <tptr> VAR FNCT /* Variable and Function */
1846 %type <val> exp
1847
1848 %right '='
1849 %left '-' '+'
1850 %left '*' '/'
1851 %left NEG /* Negation--unary minus */
1852 %right '^' /* Exponentiation */
1853
1854 /* Grammar follows */
1855
1856 %%
1857 @end smallexample
1858
1859 The above grammar introduces only two new features of the Bison language.
1860 These features allow semantic values to have various data types
1861 (@pxref{Multiple Types, ,More Than One Value Type}).
1862
1863 The @code{%union} declaration specifies the entire list of possible types;
1864 this is instead of defining @code{YYSTYPE}. The allowable types are now
1865 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
1866 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
1867
1868 Since values can now have various types, it is necessary to associate a
1869 type with each grammar symbol whose semantic value is used. These symbols
1870 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
1871 declarations are augmented with information about their data type (placed
1872 between angle brackets).
1873
1874 The Bison construct @code{%type} is used for declaring nonterminal
1875 symbols, just as @code{%token} is used for declaring token types. We
1876 have not used @code{%type} before because nonterminal symbols are
1877 normally declared implicitly by the rules that define them. But
1878 @code{exp} must be declared explicitly so we can specify its value type.
1879 @xref{Type Decl, ,Nonterminal Symbols}.
1880
1881 @node Mfcalc Rules
1882 @subsection Grammar Rules for @code{mfcalc}
1883
1884 Here are the grammar rules for the multi-function calculator.
1885 Most of them are copied directly from @code{calc}; three rules,
1886 those which mention @code{VAR} or @code{FNCT}, are new.
1887
1888 @smallexample
1889 input: /* empty */
1890 | input line
1891 ;
1892
1893 line:
1894 '\n'
1895 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1896 | error '\n' @{ yyerrok; @}
1897 ;
1898
1899 exp: NUM @{ $$ = $1; @}
1900 | VAR @{ $$ = $1->value.var; @}
1901 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
1902 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
1903 | exp '+' exp @{ $$ = $1 + $3; @}
1904 | exp '-' exp @{ $$ = $1 - $3; @}
1905 | exp '*' exp @{ $$ = $1 * $3; @}
1906 | exp '/' exp @{ $$ = $1 / $3; @}
1907 | '-' exp %prec NEG @{ $$ = -$2; @}
1908 | exp '^' exp @{ $$ = pow ($1, $3); @}
1909 | '(' exp ')' @{ $$ = $2; @}
1910 ;
1911 /* End of grammar */
1912 %%
1913 @end smallexample
1914
1915 @node Mfcalc Symtab
1916 @subsection The @code{mfcalc} Symbol Table
1917 @cindex symbol table example
1918
1919 The multi-function calculator requires a symbol table to keep track of the
1920 names and meanings of variables and functions. This doesn't affect the
1921 grammar rules (except for the actions) or the Bison declarations, but it
1922 requires some additional C functions for support.
1923
1924 The symbol table itself consists of a linked list of records. Its
1925 definition, which is kept in the header @file{calc.h}, is as follows. It
1926 provides for either functions or variables to be placed in the table.
1927
1928 @smallexample
1929 @group
1930 /* Function type. */
1931 typedef double (*func_t) (double);
1932
1933 /* Data type for links in the chain of symbols. */
1934 struct symrec
1935 @{
1936 char *name; /* name of symbol */
1937 int type; /* type of symbol: either VAR or FNCT */
1938 union
1939 @{
1940 double var; /* value of a VAR */
1941 func_t fnctptr; /* value of a FNCT */
1942 @} value;
1943 struct symrec *next; /* link field */
1944 @};
1945 @end group
1946
1947 @group
1948 typedef struct symrec symrec;
1949
1950 /* The symbol table: a chain of `struct symrec'. */
1951 extern symrec *sym_table;
1952
1953 symrec *putsym (const char *, func_t);
1954 symrec *getsym (const char *);
1955 @end group
1956 @end smallexample
1957
1958 The new version of @code{main} includes a call to @code{init_table}, a
1959 function that initializes the symbol table. Here it is, and
1960 @code{init_table} as well:
1961
1962 @smallexample
1963 @group
1964 #include <stdio.h>
1965
1966 int
1967 main (void)
1968 @{
1969 init_table ();
1970 return yyparse ();
1971 @}
1972 @end group
1973
1974 @group
1975 void
1976 yyerror (const char *s) /* Called by yyparse on error */
1977 @{
1978 printf ("%s\n", s);
1979 @}
1980
1981 struct init
1982 @{
1983 char *fname;
1984 double (*fnct)(double);
1985 @};
1986 @end group
1987
1988 @group
1989 struct init arith_fncts[] =
1990 @{
1991 "sin", sin,
1992 "cos", cos,
1993 "atan", atan,
1994 "ln", log,
1995 "exp", exp,
1996 "sqrt", sqrt,
1997 0, 0
1998 @};
1999
2000 /* The symbol table: a chain of `struct symrec'. */
2001 symrec *sym_table = (symrec *) 0;
2002 @end group
2003
2004 @group
2005 /* Put arithmetic functions in table. */
2006 void
2007 init_table (void)
2008 @{
2009 int i;
2010 symrec *ptr;
2011 for (i = 0; arith_fncts[i].fname != 0; i++)
2012 @{
2013 ptr = putsym (arith_fncts[i].fname, FNCT);
2014 ptr->value.fnctptr = arith_fncts[i].fnct;
2015 @}
2016 @}
2017 @end group
2018 @end smallexample
2019
2020 By simply editing the initialization list and adding the necessary include
2021 files, you can add additional functions to the calculator.
2022
2023 Two important functions allow look-up and installation of symbols in the
2024 symbol table. The function @code{putsym} is passed a name and the type
2025 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2026 linked to the front of the list, and a pointer to the object is returned.
2027 The function @code{getsym} is passed the name of the symbol to look up. If
2028 found, a pointer to that symbol is returned; otherwise zero is returned.
2029
2030 @smallexample
2031 symrec *
2032 putsym (char *sym_name, int sym_type)
2033 @{
2034 symrec *ptr;
2035 ptr = (symrec *) malloc (sizeof (symrec));
2036 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2037 strcpy (ptr->name,sym_name);
2038 ptr->type = sym_type;
2039 ptr->value.var = 0; /* Set value to 0 even if fctn. */
2040 ptr->next = (struct symrec *)sym_table;
2041 sym_table = ptr;
2042 return ptr;
2043 @}
2044
2045 symrec *
2046 getsym (const char *sym_name)
2047 @{
2048 symrec *ptr;
2049 for (ptr = sym_table; ptr != (symrec *) 0;
2050 ptr = (symrec *)ptr->next)
2051 if (strcmp (ptr->name,sym_name) == 0)
2052 return ptr;
2053 return 0;
2054 @}
2055 @end smallexample
2056
2057 The function @code{yylex} must now recognize variables, numeric values, and
2058 the single-character arithmetic operators. Strings of alphanumeric
2059 characters with a leading non-digit are recognized as either variables or
2060 functions depending on what the symbol table says about them.
2061
2062 The string is passed to @code{getsym} for look up in the symbol table. If
2063 the name appears in the table, a pointer to its location and its type
2064 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2065 already in the table, then it is installed as a @code{VAR} using
2066 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2067 returned to @code{yyparse}.
2068
2069 No change is needed in the handling of numeric values and arithmetic
2070 operators in @code{yylex}.
2071
2072 @smallexample
2073 @group
2074 #include <ctype.h>
2075
2076 int
2077 yylex (void)
2078 @{
2079 int c;
2080
2081 /* Ignore white space, get first nonwhite character. */
2082 while ((c = getchar ()) == ' ' || c == '\t');
2083
2084 if (c == EOF)
2085 return 0;
2086 @end group
2087
2088 @group
2089 /* Char starts a number => parse the number. */
2090 if (c == '.' || isdigit (c))
2091 @{
2092 ungetc (c, stdin);
2093 scanf ("%lf", &yylval.val);
2094 return NUM;
2095 @}
2096 @end group
2097
2098 @group
2099 /* Char starts an identifier => read the name. */
2100 if (isalpha (c))
2101 @{
2102 symrec *s;
2103 static char *symbuf = 0;
2104 static int length = 0;
2105 int i;
2106 @end group
2107
2108 @group
2109 /* Initially make the buffer long enough
2110 for a 40-character symbol name. */
2111 if (length == 0)
2112 length = 40, symbuf = (char *)malloc (length + 1);
2113
2114 i = 0;
2115 do
2116 @end group
2117 @group
2118 @{
2119 /* If buffer is full, make it bigger. */
2120 if (i == length)
2121 @{
2122 length *= 2;
2123 symbuf = (char *)realloc (symbuf, length + 1);
2124 @}
2125 /* Add this character to the buffer. */
2126 symbuf[i++] = c;
2127 /* Get another character. */
2128 c = getchar ();
2129 @}
2130 @end group
2131 @group
2132 while (isalnum (c));
2133
2134 ungetc (c, stdin);
2135 symbuf[i] = '\0';
2136 @end group
2137
2138 @group
2139 s = getsym (symbuf);
2140 if (s == 0)
2141 s = putsym (symbuf, VAR);
2142 yylval.tptr = s;
2143 return s->type;
2144 @}
2145
2146 /* Any other character is a token by itself. */
2147 return c;
2148 @}
2149 @end group
2150 @end smallexample
2151
2152 This program is both powerful and flexible. You may easily add new
2153 functions, and it is a simple job to modify this code to install
2154 predefined variables such as @code{pi} or @code{e} as well.
2155
2156 @node Exercises
2157 @section Exercises
2158 @cindex exercises
2159
2160 @enumerate
2161 @item
2162 Add some new functions from @file{math.h} to the initialization list.
2163
2164 @item
2165 Add another array that contains constants and their values. Then
2166 modify @code{init_table} to add these constants to the symbol table.
2167 It will be easiest to give the constants type @code{VAR}.
2168
2169 @item
2170 Make the program report an error if the user refers to an
2171 uninitialized variable in any way except to store a value in it.
2172 @end enumerate
2173
2174 @node Grammar File
2175 @chapter Bison Grammar Files
2176
2177 Bison takes as input a context-free grammar specification and produces a
2178 C-language function that recognizes correct instances of the grammar.
2179
2180 The Bison grammar input file conventionally has a name ending in @samp{.y}.
2181 @xref{Invocation, ,Invoking Bison}.
2182
2183 @menu
2184 * Grammar Outline:: Overall layout of the grammar file.
2185 * Symbols:: Terminal and nonterminal symbols.
2186 * Rules:: How to write grammar rules.
2187 * Recursion:: Writing recursive rules.
2188 * Semantics:: Semantic values and actions.
2189 * Locations:: Locations and actions.
2190 * Declarations:: All kinds of Bison declarations are described here.
2191 * Multiple Parsers:: Putting more than one Bison parser in one program.
2192 @end menu
2193
2194 @node Grammar Outline
2195 @section Outline of a Bison Grammar
2196
2197 A Bison grammar file has four main sections, shown here with the
2198 appropriate delimiters:
2199
2200 @example
2201 %@{
2202 @var{Prologue}
2203 %@}
2204
2205 @var{Bison declarations}
2206
2207 %%
2208 @var{Grammar rules}
2209 %%
2210
2211 @var{Epilogue}
2212 @end example
2213
2214 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2215 As a @acronym{GNU} extension, @samp{//} introduces a comment that
2216 continues until end of line.
2217
2218 @menu
2219 * Prologue:: Syntax and usage of the prologue.
2220 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2221 * Grammar Rules:: Syntax and usage of the grammar rules section.
2222 * Epilogue:: Syntax and usage of the epilogue.
2223 @end menu
2224
2225 @node Prologue, Bison Declarations, , Grammar Outline
2226 @subsection The prologue
2227 @cindex declarations section
2228 @cindex Prologue
2229 @cindex declarations
2230
2231 The @var{Prologue} section contains macro definitions and
2232 declarations of functions and variables that are used in the actions in the
2233 grammar rules. These are copied to the beginning of the parser file so
2234 that they precede the definition of @code{yyparse}. You can use
2235 @samp{#include} to get the declarations from a header file. If you don't
2236 need any C declarations, you may omit the @samp{%@{} and @samp{%@}}
2237 delimiters that bracket this section.
2238
2239 You may have more than one @var{Prologue} section, intermixed with the
2240 @var{Bison declarations}. This allows you to have C and Bison
2241 declarations that refer to each other. For example, the @code{%union}
2242 declaration may use types defined in a header file, and you may wish to
2243 prototype functions that take arguments of type @code{YYSTYPE}. This
2244 can be done with two @var{Prologue} blocks, one before and one after the
2245 @code{%union} declaration.
2246
2247 @smallexample
2248 %@{
2249 #include <stdio.h>
2250 #include "ptypes.h"
2251 %@}
2252
2253 %union @{
2254 long n;
2255 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2256 @}
2257
2258 %@{
2259 static void yyprint(FILE *, int, YYSTYPE);
2260 #define YYPRINT(F, N, L) yyprint(F, N, L)
2261 %@}
2262
2263 @dots{}
2264 @end smallexample
2265
2266 @node Bison Declarations
2267 @subsection The Bison Declarations Section
2268 @cindex Bison declarations (introduction)
2269 @cindex declarations, Bison (introduction)
2270
2271 The @var{Bison declarations} section contains declarations that define
2272 terminal and nonterminal symbols, specify precedence, and so on.
2273 In some simple grammars you may not need any declarations.
2274 @xref{Declarations, ,Bison Declarations}.
2275
2276 @node Grammar Rules
2277 @subsection The Grammar Rules Section
2278 @cindex grammar rules section
2279 @cindex rules section for grammar
2280
2281 The @dfn{grammar rules} section contains one or more Bison grammar
2282 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
2283
2284 There must always be at least one grammar rule, and the first
2285 @samp{%%} (which precedes the grammar rules) may never be omitted even
2286 if it is the first thing in the file.
2287
2288 @node Epilogue, , Grammar Rules, Grammar Outline
2289 @subsection The epilogue
2290 @cindex additional C code section
2291 @cindex epilogue
2292 @cindex C code, section for additional
2293
2294 The @var{Epilogue} is copied verbatim to the end of the parser file, just as
2295 the @var{Prologue} is copied to the beginning. This is the most convenient
2296 place to put anything that you want to have in the parser file but which need
2297 not come before the definition of @code{yyparse}. For example, the
2298 definitions of @code{yylex} and @code{yyerror} often go here.
2299 @xref{Interface, ,Parser C-Language Interface}.
2300
2301 If the last section is empty, you may omit the @samp{%%} that separates it
2302 from the grammar rules.
2303
2304 The Bison parser itself contains many static variables whose names start
2305 with @samp{yy} and many macros whose names start with @samp{YY}. It is a
2306 good idea to avoid using any such names (except those documented in this
2307 manual) in the epilogue of the grammar file.
2308
2309 @node Symbols
2310 @section Symbols, Terminal and Nonterminal
2311 @cindex nonterminal symbol
2312 @cindex terminal symbol
2313 @cindex token type
2314 @cindex symbol
2315
2316 @dfn{Symbols} in Bison grammars represent the grammatical classifications
2317 of the language.
2318
2319 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
2320 class of syntactically equivalent tokens. You use the symbol in grammar
2321 rules to mean that a token in that class is allowed. The symbol is
2322 represented in the Bison parser by a numeric code, and the @code{yylex}
2323 function returns a token type code to indicate what kind of token has been
2324 read. You don't need to know what the code value is; you can use the
2325 symbol to stand for it.
2326
2327 A @dfn{nonterminal symbol} stands for a class of syntactically equivalent
2328 groupings. The symbol name is used in writing grammar rules. By convention,
2329 it should be all lower case.
2330
2331 Symbol names can contain letters, digits (not at the beginning),
2332 underscores and periods. Periods make sense only in nonterminals.
2333
2334 There are three ways of writing terminal symbols in the grammar:
2335
2336 @itemize @bullet
2337 @item
2338 A @dfn{named token type} is written with an identifier, like an
2339 identifier in C@. By convention, it should be all upper case. Each
2340 such name must be defined with a Bison declaration such as
2341 @code{%token}. @xref{Token Decl, ,Token Type Names}.
2342
2343 @item
2344 @cindex character token
2345 @cindex literal token
2346 @cindex single-character literal
2347 A @dfn{character token type} (or @dfn{literal character token}) is
2348 written in the grammar using the same syntax used in C for character
2349 constants; for example, @code{'+'} is a character token type. A
2350 character token type doesn't need to be declared unless you need to
2351 specify its semantic value data type (@pxref{Value Type, ,Data Types of
2352 Semantic Values}), associativity, or precedence (@pxref{Precedence,
2353 ,Operator Precedence}).
2354
2355 By convention, a character token type is used only to represent a
2356 token that consists of that particular character. Thus, the token
2357 type @code{'+'} is used to represent the character @samp{+} as a
2358 token. Nothing enforces this convention, but if you depart from it,
2359 your program will confuse other readers.
2360
2361 All the usual escape sequences used in character literals in C can be
2362 used in Bison as well, but you must not use the null character as a
2363 character literal because its numeric code, zero, signifies
2364 end-of-input (@pxref{Calling Convention, ,Calling Convention
2365 for @code{yylex}}). Also, unlike standard C, trigraphs have no
2366 special meaning in Bison character literals, nor is backslash-newline
2367 allowed.
2368
2369 @item
2370 @cindex string token
2371 @cindex literal string token
2372 @cindex multicharacter literal
2373 A @dfn{literal string token} is written like a C string constant; for
2374 example, @code{"<="} is a literal string token. A literal string token
2375 doesn't need to be declared unless you need to specify its semantic
2376 value data type (@pxref{Value Type}), associativity, or precedence
2377 (@pxref{Precedence}).
2378
2379 You can associate the literal string token with a symbolic name as an
2380 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
2381 Declarations}). If you don't do that, the lexical analyzer has to
2382 retrieve the token number for the literal string token from the
2383 @code{yytname} table (@pxref{Calling Convention}).
2384
2385 @strong{Warning}: literal string tokens do not work in Yacc.
2386
2387 By convention, a literal string token is used only to represent a token
2388 that consists of that particular string. Thus, you should use the token
2389 type @code{"<="} to represent the string @samp{<=} as a token. Bison
2390 does not enforce this convention, but if you depart from it, people who
2391 read your program will be confused.
2392
2393 All the escape sequences used in string literals in C can be used in
2394 Bison as well. However, unlike Standard C, trigraphs have no special
2395 meaning in Bison string literals, nor is backslash-newline allowed. A
2396 literal string token must contain two or more characters; for a token
2397 containing just one character, use a character token (see above).
2398 @end itemize
2399
2400 How you choose to write a terminal symbol has no effect on its
2401 grammatical meaning. That depends only on where it appears in rules and
2402 on when the parser function returns that symbol.
2403
2404 The value returned by @code{yylex} is always one of the terminal
2405 symbols, except that a zero or negative value signifies end-of-input.
2406 Whichever way you write the token type in the grammar rules, you write
2407 it the same way in the definition of @code{yylex}. The numeric code
2408 for a character token type is simply the positive numeric code of the
2409 character, so @code{yylex} can use the identical value to generate the
2410 requisite code, though you may need to convert it to @code{unsigned
2411 char} to avoid sign-extension on hosts where @code{char} is signed.
2412 Each named token type becomes a C macro in
2413 the parser file, so @code{yylex} can use the name to stand for the code.
2414 (This is why periods don't make sense in terminal symbols.)
2415 @xref{Calling Convention, ,Calling Convention for @code{yylex}}.
2416
2417 If @code{yylex} is defined in a separate file, you need to arrange for the
2418 token-type macro definitions to be available there. Use the @samp{-d}
2419 option when you run Bison, so that it will write these macro definitions
2420 into a separate header file @file{@var{name}.tab.h} which you can include
2421 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
2422
2423 If you want to write a grammar that is portable to any Standard C
2424 host, you must use only non-null character tokens taken from the basic
2425 execution character set of Standard C@. This set consists of the ten
2426 digits, the 52 lower- and upper-case English letters, and the
2427 characters in the following C-language string:
2428
2429 @example
2430 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
2431 @end example
2432
2433 The @code{yylex} function and Bison must use a consistent character
2434 set and encoding for character tokens. For example, if you run Bison in an
2435 @acronym{ASCII} environment, but then compile and run the resulting program
2436 in an environment that uses an incompatible character set like
2437 @acronym{EBCDIC}, the resulting program may not work because the
2438 tables generated by Bison will assume @acronym{ASCII} numeric values for
2439 character tokens. It is standard
2440 practice for software distributions to contain C source files that
2441 were generated by Bison in an @acronym{ASCII} environment, so installers on
2442 platforms that are incompatible with @acronym{ASCII} must rebuild those
2443 files before compiling them.
2444
2445 The symbol @code{error} is a terminal symbol reserved for error recovery
2446 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
2447 In particular, @code{yylex} should never return this value. The default
2448 value of the error token is 256, unless you explicitly assigned 256 to
2449 one of your tokens with a @code{%token} declaration.
2450
2451 @node Rules
2452 @section Syntax of Grammar Rules
2453 @cindex rule syntax
2454 @cindex grammar rule syntax
2455 @cindex syntax of grammar rules
2456
2457 A Bison grammar rule has the following general form:
2458
2459 @example
2460 @group
2461 @var{result}: @var{components}@dots{}
2462 ;
2463 @end group
2464 @end example
2465
2466 @noindent
2467 where @var{result} is the nonterminal symbol that this rule describes,
2468 and @var{components} are various terminal and nonterminal symbols that
2469 are put together by this rule (@pxref{Symbols}).
2470
2471 For example,
2472
2473 @example
2474 @group
2475 exp: exp '+' exp
2476 ;
2477 @end group
2478 @end example
2479
2480 @noindent
2481 says that two groupings of type @code{exp}, with a @samp{+} token in between,
2482 can be combined into a larger grouping of type @code{exp}.
2483
2484 White space in rules is significant only to separate symbols. You can add
2485 extra white space as you wish.
2486
2487 Scattered among the components can be @var{actions} that determine
2488 the semantics of the rule. An action looks like this:
2489
2490 @example
2491 @{@var{C statements}@}
2492 @end example
2493
2494 @noindent
2495 Usually there is only one action and it follows the components.
2496 @xref{Actions}.
2497
2498 @findex |
2499 Multiple rules for the same @var{result} can be written separately or can
2500 be joined with the vertical-bar character @samp{|} as follows:
2501
2502 @ifinfo
2503 @example
2504 @var{result}: @var{rule1-components}@dots{}
2505 | @var{rule2-components}@dots{}
2506 @dots{}
2507 ;
2508 @end example
2509 @end ifinfo
2510 @iftex
2511 @example
2512 @group
2513 @var{result}: @var{rule1-components}@dots{}
2514 | @var{rule2-components}@dots{}
2515 @dots{}
2516 ;
2517 @end group
2518 @end example
2519 @end iftex
2520
2521 @noindent
2522 They are still considered distinct rules even when joined in this way.
2523
2524 If @var{components} in a rule is empty, it means that @var{result} can
2525 match the empty string. For example, here is how to define a
2526 comma-separated sequence of zero or more @code{exp} groupings:
2527
2528 @example
2529 @group
2530 expseq: /* empty */
2531 | expseq1
2532 ;
2533 @end group
2534
2535 @group
2536 expseq1: exp
2537 | expseq1 ',' exp
2538 ;
2539 @end group
2540 @end example
2541
2542 @noindent
2543 It is customary to write a comment @samp{/* empty */} in each rule
2544 with no components.
2545
2546 @node Recursion
2547 @section Recursive Rules
2548 @cindex recursive rule
2549
2550 A rule is called @dfn{recursive} when its @var{result} nonterminal appears
2551 also on its right hand side. Nearly all Bison grammars need to use
2552 recursion, because that is the only way to define a sequence of any number
2553 of a particular thing. Consider this recursive definition of a
2554 comma-separated sequence of one or more expressions:
2555
2556 @example
2557 @group
2558 expseq1: exp
2559 | expseq1 ',' exp
2560 ;
2561 @end group
2562 @end example
2563
2564 @cindex left recursion
2565 @cindex right recursion
2566 @noindent
2567 Since the recursive use of @code{expseq1} is the leftmost symbol in the
2568 right hand side, we call this @dfn{left recursion}. By contrast, here
2569 the same construct is defined using @dfn{right recursion}:
2570
2571 @example
2572 @group
2573 expseq1: exp
2574 | exp ',' expseq1
2575 ;
2576 @end group
2577 @end example
2578
2579 @noindent
2580 Any kind of sequence can be defined using either left recursion or right
2581 recursion, but you should always use left recursion, because it can
2582 parse a sequence of any number of elements with bounded stack space.
2583 Right recursion uses up space on the Bison stack in proportion to the
2584 number of elements in the sequence, because all the elements must be
2585 shifted onto the stack before the rule can be applied even once.
2586 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
2587 of this.
2588
2589 @cindex mutual recursion
2590 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
2591 rule does not appear directly on its right hand side, but does appear
2592 in rules for other nonterminals which do appear on its right hand
2593 side.
2594
2595 For example:
2596
2597 @example
2598 @group
2599 expr: primary
2600 | primary '+' primary
2601 ;
2602 @end group
2603
2604 @group
2605 primary: constant
2606 | '(' expr ')'
2607 ;
2608 @end group
2609 @end example
2610
2611 @noindent
2612 defines two mutually-recursive nonterminals, since each refers to the
2613 other.
2614
2615 @node Semantics
2616 @section Defining Language Semantics
2617 @cindex defining language semantics
2618 @cindex language semantics, defining
2619
2620 The grammar rules for a language determine only the syntax. The semantics
2621 are determined by the semantic values associated with various tokens and
2622 groupings, and by the actions taken when various groupings are recognized.
2623
2624 For example, the calculator calculates properly because the value
2625 associated with each expression is the proper number; it adds properly
2626 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
2627 the numbers associated with @var{x} and @var{y}.
2628
2629 @menu
2630 * Value Type:: Specifying one data type for all semantic values.
2631 * Multiple Types:: Specifying several alternative data types.
2632 * Actions:: An action is the semantic definition of a grammar rule.
2633 * Action Types:: Specifying data types for actions to operate on.
2634 * Mid-Rule Actions:: Most actions go at the end of a rule.
2635 This says when, why and how to use the exceptional
2636 action in the middle of a rule.
2637 @end menu
2638
2639 @node Value Type
2640 @subsection Data Types of Semantic Values
2641 @cindex semantic value type
2642 @cindex value type, semantic
2643 @cindex data types of semantic values
2644 @cindex default data type
2645
2646 In a simple program it may be sufficient to use the same data type for
2647 the semantic values of all language constructs. This was true in the
2648 @acronym{RPN} and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
2649 Notation Calculator}).
2650
2651 Bison's default is to use type @code{int} for all semantic values. To
2652 specify some other type, define @code{YYSTYPE} as a macro, like this:
2653
2654 @example
2655 #define YYSTYPE double
2656 @end example
2657
2658 @noindent
2659 This macro definition must go in the prologue of the grammar file
2660 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
2661
2662 @node Multiple Types
2663 @subsection More Than One Value Type
2664
2665 In most programs, you will need different data types for different kinds
2666 of tokens and groupings. For example, a numeric constant may need type
2667 @code{int} or @code{long}, while a string constant needs type @code{char *},
2668 and an identifier might need a pointer to an entry in the symbol table.
2669
2670 To use more than one data type for semantic values in one parser, Bison
2671 requires you to do two things:
2672
2673 @itemize @bullet
2674 @item
2675 Specify the entire collection of possible data types, with the
2676 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
2677 Value Types}).
2678
2679 @item
2680 Choose one of those types for each symbol (terminal or nonterminal) for
2681 which semantic values are used. This is done for tokens with the
2682 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
2683 and for groupings with the @code{%type} Bison declaration (@pxref{Type
2684 Decl, ,Nonterminal Symbols}).
2685 @end itemize
2686
2687 @node Actions
2688 @subsection Actions
2689 @cindex action
2690 @vindex $$
2691 @vindex $@var{n}
2692
2693 An action accompanies a syntactic rule and contains C code to be executed
2694 each time an instance of that rule is recognized. The task of most actions
2695 is to compute a semantic value for the grouping built by the rule from the
2696 semantic values associated with tokens or smaller groupings.
2697
2698 An action consists of C statements surrounded by braces, much like a
2699 compound statement in C@. An action can contain any sequence of C
2700 statements. Bison does not look for trigraphs, though, so if your C
2701 code uses trigraphs you should ensure that they do not affect the
2702 nesting of braces or the boundaries of comments, strings, or character
2703 literals.
2704
2705 An action can be placed at any position in the rule;
2706 it is executed at that position. Most rules have just one action at the
2707 end of the rule, following all the components. Actions in the middle of
2708 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
2709 Actions, ,Actions in Mid-Rule}).
2710
2711 The C code in an action can refer to the semantic values of the components
2712 matched by the rule with the construct @code{$@var{n}}, which stands for
2713 the value of the @var{n}th component. The semantic value for the grouping
2714 being constructed is @code{$$}. (Bison translates both of these constructs
2715 into array element references when it copies the actions into the parser
2716 file.)
2717
2718 Here is a typical example:
2719
2720 @example
2721 @group
2722 exp: @dots{}
2723 | exp '+' exp
2724 @{ $$ = $1 + $3; @}
2725 @end group
2726 @end example
2727
2728 @noindent
2729 This rule constructs an @code{exp} from two smaller @code{exp} groupings
2730 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
2731 refer to the semantic values of the two component @code{exp} groupings,
2732 which are the first and third symbols on the right hand side of the rule.
2733 The sum is stored into @code{$$} so that it becomes the semantic value of
2734 the addition-expression just recognized by the rule. If there were a
2735 useful semantic value associated with the @samp{+} token, it could be
2736 referred to as @code{$2}.
2737
2738 Note that the vertical-bar character @samp{|} is really a rule
2739 separator, and actions are attached to a single rule. This is a
2740 difference with tools like Flex, for which @samp{|} stands for either
2741 ``or'', or ``the same action as that of the next rule''. In the
2742 following example, the action is triggered only when @samp{b} is found:
2743
2744 @example
2745 @group
2746 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
2747 @end group
2748 @end example
2749
2750 @cindex default action
2751 If you don't specify an action for a rule, Bison supplies a default:
2752 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule becomes
2753 the value of the whole rule. Of course, the default rule is valid only
2754 if the two data types match. There is no meaningful default action for
2755 an empty rule; every empty rule must have an explicit action unless the
2756 rule's value does not matter.
2757
2758 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
2759 to tokens and groupings on the stack @emph{before} those that match the
2760 current rule. This is a very risky practice, and to use it reliably
2761 you must be certain of the context in which the rule is applied. Here
2762 is a case in which you can use this reliably:
2763
2764 @example
2765 @group
2766 foo: expr bar '+' expr @{ @dots{} @}
2767 | expr bar '-' expr @{ @dots{} @}
2768 ;
2769 @end group
2770
2771 @group
2772 bar: /* empty */
2773 @{ previous_expr = $0; @}
2774 ;
2775 @end group
2776 @end example
2777
2778 As long as @code{bar} is used only in the fashion shown here, @code{$0}
2779 always refers to the @code{expr} which precedes @code{bar} in the
2780 definition of @code{foo}.
2781
2782 @node Action Types
2783 @subsection Data Types of Values in Actions
2784 @cindex action data types
2785 @cindex data types in actions
2786
2787 If you have chosen a single data type for semantic values, the @code{$$}
2788 and @code{$@var{n}} constructs always have that data type.
2789
2790 If you have used @code{%union} to specify a variety of data types, then you
2791 must declare a choice among these types for each terminal or nonterminal
2792 symbol that can have a semantic value. Then each time you use @code{$$} or
2793 @code{$@var{n}}, its data type is determined by which symbol it refers to
2794 in the rule. In this example,
2795
2796 @example
2797 @group
2798 exp: @dots{}
2799 | exp '+' exp
2800 @{ $$ = $1 + $3; @}
2801 @end group
2802 @end example
2803
2804 @noindent
2805 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
2806 have the data type declared for the nonterminal symbol @code{exp}. If
2807 @code{$2} were used, it would have the data type declared for the
2808 terminal symbol @code{'+'}, whatever that might be.
2809
2810 Alternatively, you can specify the data type when you refer to the value,
2811 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
2812 reference. For example, if you have defined types as shown here:
2813
2814 @example
2815 @group
2816 %union @{
2817 int itype;
2818 double dtype;
2819 @}
2820 @end group
2821 @end example
2822
2823 @noindent
2824 then you can write @code{$<itype>1} to refer to the first subunit of the
2825 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
2826
2827 @node Mid-Rule Actions
2828 @subsection Actions in Mid-Rule
2829 @cindex actions in mid-rule
2830 @cindex mid-rule actions
2831
2832 Occasionally it is useful to put an action in the middle of a rule.
2833 These actions are written just like usual end-of-rule actions, but they
2834 are executed before the parser even recognizes the following components.
2835
2836 A mid-rule action may refer to the components preceding it using
2837 @code{$@var{n}}, but it may not refer to subsequent components because
2838 it is run before they are parsed.
2839
2840 The mid-rule action itself counts as one of the components of the rule.
2841 This makes a difference when there is another action later in the same rule
2842 (and usually there is another at the end): you have to count the actions
2843 along with the symbols when working out which number @var{n} to use in
2844 @code{$@var{n}}.
2845
2846 The mid-rule action can also have a semantic value. The action can set
2847 its value with an assignment to @code{$$}, and actions later in the rule
2848 can refer to the value using @code{$@var{n}}. Since there is no symbol
2849 to name the action, there is no way to declare a data type for the value
2850 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
2851 specify a data type each time you refer to this value.
2852
2853 There is no way to set the value of the entire rule with a mid-rule
2854 action, because assignments to @code{$$} do not have that effect. The
2855 only way to set the value for the entire rule is with an ordinary action
2856 at the end of the rule.
2857
2858 Here is an example from a hypothetical compiler, handling a @code{let}
2859 statement that looks like @samp{let (@var{variable}) @var{statement}} and
2860 serves to create a variable named @var{variable} temporarily for the
2861 duration of @var{statement}. To parse this construct, we must put
2862 @var{variable} into the symbol table while @var{statement} is parsed, then
2863 remove it afterward. Here is how it is done:
2864
2865 @example
2866 @group
2867 stmt: LET '(' var ')'
2868 @{ $<context>$ = push_context ();
2869 declare_variable ($3); @}
2870 stmt @{ $$ = $6;
2871 pop_context ($<context>5); @}
2872 @end group
2873 @end example
2874
2875 @noindent
2876 As soon as @samp{let (@var{variable})} has been recognized, the first
2877 action is run. It saves a copy of the current semantic context (the
2878 list of accessible variables) as its semantic value, using alternative
2879 @code{context} in the data-type union. Then it calls
2880 @code{declare_variable} to add the new variable to that list. Once the
2881 first action is finished, the embedded statement @code{stmt} can be
2882 parsed. Note that the mid-rule action is component number 5, so the
2883 @samp{stmt} is component number 6.
2884
2885 After the embedded statement is parsed, its semantic value becomes the
2886 value of the entire @code{let}-statement. Then the semantic value from the
2887 earlier action is used to restore the prior list of variables. This
2888 removes the temporary @code{let}-variable from the list so that it won't
2889 appear to exist while the rest of the program is parsed.
2890
2891 Taking action before a rule is completely recognized often leads to
2892 conflicts since the parser must commit to a parse in order to execute the
2893 action. For example, the following two rules, without mid-rule actions,
2894 can coexist in a working parser because the parser can shift the open-brace
2895 token and look at what follows before deciding whether there is a
2896 declaration or not:
2897
2898 @example
2899 @group
2900 compound: '@{' declarations statements '@}'
2901 | '@{' statements '@}'
2902 ;
2903 @end group
2904 @end example
2905
2906 @noindent
2907 But when we add a mid-rule action as follows, the rules become nonfunctional:
2908
2909 @example
2910 @group
2911 compound: @{ prepare_for_local_variables (); @}
2912 '@{' declarations statements '@}'
2913 @end group
2914 @group
2915 | '@{' statements '@}'
2916 ;
2917 @end group
2918 @end example
2919
2920 @noindent
2921 Now the parser is forced to decide whether to run the mid-rule action
2922 when it has read no farther than the open-brace. In other words, it
2923 must commit to using one rule or the other, without sufficient
2924 information to do it correctly. (The open-brace token is what is called
2925 the @dfn{look-ahead} token at this time, since the parser is still
2926 deciding what to do about it. @xref{Look-Ahead, ,Look-Ahead Tokens}.)
2927
2928 You might think that you could correct the problem by putting identical
2929 actions into the two rules, like this:
2930
2931 @example
2932 @group
2933 compound: @{ prepare_for_local_variables (); @}
2934 '@{' declarations statements '@}'
2935 | @{ prepare_for_local_variables (); @}
2936 '@{' statements '@}'
2937 ;
2938 @end group
2939 @end example
2940
2941 @noindent
2942 But this does not help, because Bison does not realize that the two actions
2943 are identical. (Bison never tries to understand the C code in an action.)
2944
2945 If the grammar is such that a declaration can be distinguished from a
2946 statement by the first token (which is true in C), then one solution which
2947 does work is to put the action after the open-brace, like this:
2948
2949 @example
2950 @group
2951 compound: '@{' @{ prepare_for_local_variables (); @}
2952 declarations statements '@}'
2953 | '@{' statements '@}'
2954 ;
2955 @end group
2956 @end example
2957
2958 @noindent
2959 Now the first token of the following declaration or statement,
2960 which would in any case tell Bison which rule to use, can still do so.
2961
2962 Another solution is to bury the action inside a nonterminal symbol which
2963 serves as a subroutine:
2964
2965 @example
2966 @group
2967 subroutine: /* empty */
2968 @{ prepare_for_local_variables (); @}
2969 ;
2970
2971 @end group
2972
2973 @group
2974 compound: subroutine
2975 '@{' declarations statements '@}'
2976 | subroutine
2977 '@{' statements '@}'
2978 ;
2979 @end group
2980 @end example
2981
2982 @noindent
2983 Now Bison can execute the action in the rule for @code{subroutine} without
2984 deciding which rule for @code{compound} it will eventually use. Note that
2985 the action is now at the end of its rule. Any mid-rule action can be
2986 converted to an end-of-rule action in this way, and this is what Bison
2987 actually does to implement mid-rule actions.
2988
2989 @node Locations
2990 @section Tracking Locations
2991 @cindex location
2992 @cindex textual position
2993 @cindex position, textual
2994
2995 Though grammar rules and semantic actions are enough to write a fully
2996 functional parser, it can be useful to process some additional information,
2997 especially symbol locations.
2998
2999 @c (terminal or not) ?
3000
3001 The way locations are handled is defined by providing a data type, and
3002 actions to take when rules are matched.
3003
3004 @menu
3005 * Location Type:: Specifying a data type for locations.
3006 * Actions and Locations:: Using locations in actions.
3007 * Location Default Action:: Defining a general way to compute locations.
3008 @end menu
3009
3010 @node Location Type
3011 @subsection Data Type of Locations
3012 @cindex data type of locations
3013 @cindex default location type
3014
3015 Defining a data type for locations is much simpler than for semantic values,
3016 since all tokens and groupings always use the same type.
3017
3018 The type of locations is specified by defining a macro called @code{YYLTYPE}.
3019 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3020 four members:
3021
3022 @example
3023 struct
3024 @{
3025 int first_line;
3026 int first_column;
3027 int last_line;
3028 int last_column;
3029 @}
3030 @end example
3031
3032 @node Actions and Locations
3033 @subsection Actions and Locations
3034 @cindex location actions
3035 @cindex actions, location
3036 @vindex @@$
3037 @vindex @@@var{n}
3038
3039 Actions are not only useful for defining language semantics, but also for
3040 describing the behavior of the output parser with locations.
3041
3042 The most obvious way for building locations of syntactic groupings is very
3043 similar to the way semantic values are computed. In a given rule, several
3044 constructs can be used to access the locations of the elements being matched.
3045 The location of the @var{n}th component of the right hand side is
3046 @code{@@@var{n}}, while the location of the left hand side grouping is
3047 @code{@@$}.
3048
3049 Here is a basic example using the default data type for locations:
3050
3051 @example
3052 @group
3053 exp: @dots{}
3054 | exp '/' exp
3055 @{
3056 @@$.first_column = @@1.first_column;
3057 @@$.first_line = @@1.first_line;
3058 @@$.last_column = @@3.last_column;
3059 @@$.last_line = @@3.last_line;
3060 if ($3)
3061 $$ = $1 / $3;
3062 else
3063 @{
3064 $$ = 1;
3065 printf("Division by zero, l%d,c%d-l%d,c%d",
3066 @@3.first_line, @@3.first_column,
3067 @@3.last_line, @@3.last_column);
3068 @}
3069 @}
3070 @end group
3071 @end example
3072
3073 As for semantic values, there is a default action for locations that is
3074 run each time a rule is matched. It sets the beginning of @code{@@$} to the
3075 beginning of the first symbol, and the end of @code{@@$} to the end of the
3076 last symbol.
3077
3078 With this default action, the location tracking can be fully automatic. The
3079 example above simply rewrites this way:
3080
3081 @example
3082 @group
3083 exp: @dots{}
3084 | exp '/' exp
3085 @{
3086 if ($3)
3087 $$ = $1 / $3;
3088 else
3089 @{
3090 $$ = 1;
3091 printf("Division by zero, l%d,c%d-l%d,c%d",
3092 @@3.first_line, @@3.first_column,
3093 @@3.last_line, @@3.last_column);
3094 @}
3095 @}
3096 @end group
3097 @end example
3098
3099 @node Location Default Action
3100 @subsection Default Action for Locations
3101 @vindex YYLLOC_DEFAULT
3102
3103 Actually, actions are not the best place to compute locations. Since
3104 locations are much more general than semantic values, there is room in
3105 the output parser to redefine the default action to take for each
3106 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
3107 matched, before the associated action is run.
3108
3109 Most of the time, this macro is general enough to suppress location
3110 dedicated code from semantic actions.
3111
3112 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
3113 the location of the grouping (the result of the computation). The second one
3114 is an array holding locations of all right hand side elements of the rule
3115 being matched. The last one is the size of the right hand side rule.
3116
3117 By default, it is defined this way for simple @acronym{LALR}(1) parsers:
3118
3119 @example
3120 @group
3121 #define YYLLOC_DEFAULT(Current, Rhs, N) \
3122 Current.first_line = Rhs[1].first_line; \
3123 Current.first_column = Rhs[1].first_column; \
3124 Current.last_line = Rhs[N].last_line; \
3125 Current.last_column = Rhs[N].last_column;
3126 @end group
3127 @end example
3128
3129 @noindent
3130 and like this for @acronym{GLR} parsers:
3131
3132 @example
3133 @group
3134 #define YYLLOC_DEFAULT(Current, Rhs, N) \
3135 Current.first_line = YYRHSLOC(Rhs,1).first_line; \
3136 Current.first_column = YYRHSLOC(Rhs,1).first_column; \
3137 Current.last_line = YYRHSLOC(Rhs,N).last_line; \
3138 Current.last_column = YYRHSLOC(Rhs,N).last_column;
3139 @end group
3140 @end example
3141
3142 When defining @code{YYLLOC_DEFAULT}, you should consider that:
3143
3144 @itemize @bullet
3145 @item
3146 All arguments are free of side-effects. However, only the first one (the
3147 result) should be modified by @code{YYLLOC_DEFAULT}.
3148
3149 @item
3150 For consistency with semantic actions, valid indexes for the location
3151 array range from 1 to @var{n}.
3152 @end itemize
3153
3154 @node Declarations
3155 @section Bison Declarations
3156 @cindex declarations, Bison
3157 @cindex Bison declarations
3158
3159 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
3160 used in formulating the grammar and the data types of semantic values.
3161 @xref{Symbols}.
3162
3163 All token type names (but not single-character literal tokens such as
3164 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
3165 declared if you need to specify which data type to use for the semantic
3166 value (@pxref{Multiple Types, ,More Than One Value Type}).
3167
3168 The first rule in the file also specifies the start symbol, by default.
3169 If you want some other symbol to be the start symbol, you must declare
3170 it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free
3171 Grammars}).
3172
3173 @menu
3174 * Token Decl:: Declaring terminal symbols.
3175 * Precedence Decl:: Declaring terminals with precedence and associativity.
3176 * Union Decl:: Declaring the set of all semantic value types.
3177 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
3178 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
3179 * Start Decl:: Specifying the start symbol.
3180 * Pure Decl:: Requesting a reentrant parser.
3181 * Decl Summary:: Table of all Bison declarations.
3182 @end menu
3183
3184 @node Token Decl
3185 @subsection Token Type Names
3186 @cindex declaring token type names
3187 @cindex token type names, declaring
3188 @cindex declaring literal string tokens
3189 @findex %token
3190
3191 The basic way to declare a token type name (terminal symbol) is as follows:
3192
3193 @example
3194 %token @var{name}
3195 @end example
3196
3197 Bison will convert this into a @code{#define} directive in
3198 the parser, so that the function @code{yylex} (if it is in this file)
3199 can use the name @var{name} to stand for this token type's code.
3200
3201 Alternatively, you can use @code{%left}, @code{%right}, or
3202 @code{%nonassoc} instead of @code{%token}, if you wish to specify
3203 associativity and precedence. @xref{Precedence Decl, ,Operator
3204 Precedence}.
3205
3206 You can explicitly specify the numeric code for a token type by appending
3207 an integer value in the field immediately following the token name:
3208
3209 @example
3210 %token NUM 300
3211 @end example
3212
3213 @noindent
3214 It is generally best, however, to let Bison choose the numeric codes for
3215 all token types. Bison will automatically select codes that don't conflict
3216 with each other or with normal characters.
3217
3218 In the event that the stack type is a union, you must augment the
3219 @code{%token} or other token declaration to include the data type
3220 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
3221 Than One Value Type}).
3222
3223 For example:
3224
3225 @example
3226 @group
3227 %union @{ /* define stack type */
3228 double val;
3229 symrec *tptr;
3230 @}
3231 %token <val> NUM /* define token NUM and its type */
3232 @end group
3233 @end example
3234
3235 You can associate a literal string token with a token type name by
3236 writing the literal string at the end of a @code{%token}
3237 declaration which declares the name. For example:
3238
3239 @example
3240 %token arrow "=>"
3241 @end example
3242
3243 @noindent
3244 For example, a grammar for the C language might specify these names with
3245 equivalent literal string tokens:
3246
3247 @example
3248 %token <operator> OR "||"
3249 %token <operator> LE 134 "<="
3250 %left OR "<="
3251 @end example
3252
3253 @noindent
3254 Once you equate the literal string and the token name, you can use them
3255 interchangeably in further declarations or the grammar rules. The
3256 @code{yylex} function can use the token name or the literal string to
3257 obtain the token type code number (@pxref{Calling Convention}).
3258
3259 @node Precedence Decl
3260 @subsection Operator Precedence
3261 @cindex precedence declarations
3262 @cindex declaring operator precedence
3263 @cindex operator precedence, declaring
3264
3265 Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
3266 declare a token and specify its precedence and associativity, all at
3267 once. These are called @dfn{precedence declarations}.
3268 @xref{Precedence, ,Operator Precedence}, for general information on
3269 operator precedence.
3270
3271 The syntax of a precedence declaration is the same as that of
3272 @code{%token}: either
3273
3274 @example
3275 %left @var{symbols}@dots{}
3276 @end example
3277
3278 @noindent
3279 or
3280
3281 @example
3282 %left <@var{type}> @var{symbols}@dots{}
3283 @end example
3284
3285 And indeed any of these declarations serves the purposes of @code{%token}.
3286 But in addition, they specify the associativity and relative precedence for
3287 all the @var{symbols}:
3288
3289 @itemize @bullet
3290 @item
3291 The associativity of an operator @var{op} determines how repeated uses
3292 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
3293 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
3294 grouping @var{y} with @var{z} first. @code{%left} specifies
3295 left-associativity (grouping @var{x} with @var{y} first) and
3296 @code{%right} specifies right-associativity (grouping @var{y} with
3297 @var{z} first). @code{%nonassoc} specifies no associativity, which
3298 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
3299 considered a syntax error.
3300
3301 @item
3302 The precedence of an operator determines how it nests with other operators.
3303 All the tokens declared in a single precedence declaration have equal
3304 precedence and nest together according to their associativity.
3305 When two tokens declared in different precedence declarations associate,
3306 the one declared later has the higher precedence and is grouped first.
3307 @end itemize
3308
3309 @node Union Decl
3310 @subsection The Collection of Value Types
3311 @cindex declaring value types
3312 @cindex value types, declaring
3313 @findex %union
3314
3315 The @code{%union} declaration specifies the entire collection of possible
3316 data types for semantic values. The keyword @code{%union} is followed by a
3317 pair of braces containing the same thing that goes inside a @code{union} in
3318 C.
3319
3320 For example:
3321
3322 @example
3323 @group
3324 %union @{
3325 double val;
3326 symrec *tptr;
3327 @}
3328 @end group
3329 @end example
3330
3331 @noindent
3332 This says that the two alternative types are @code{double} and @code{symrec
3333 *}. They are given names @code{val} and @code{tptr}; these names are used
3334 in the @code{%token} and @code{%type} declarations to pick one of the types
3335 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
3336
3337 Note that, unlike making a @code{union} declaration in C, you do not write
3338 a semicolon after the closing brace.
3339
3340 @node Type Decl
3341 @subsection Nonterminal Symbols
3342 @cindex declaring value types, nonterminals
3343 @cindex value types, nonterminals, declaring
3344 @findex %type
3345
3346 @noindent
3347 When you use @code{%union} to specify multiple value types, you must
3348 declare the value type of each nonterminal symbol for which values are
3349 used. This is done with a @code{%type} declaration, like this:
3350
3351 @example
3352 %type <@var{type}> @var{nonterminal}@dots{}
3353 @end example
3354
3355 @noindent
3356 Here @var{nonterminal} is the name of a nonterminal symbol, and
3357 @var{type} is the name given in the @code{%union} to the alternative
3358 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
3359 can give any number of nonterminal symbols in the same @code{%type}
3360 declaration, if they have the same value type. Use spaces to separate
3361 the symbol names.
3362
3363 You can also declare the value type of a terminal symbol. To do this,
3364 use the same @code{<@var{type}>} construction in a declaration for the
3365 terminal symbol. All kinds of token declarations allow
3366 @code{<@var{type}>}.
3367
3368 @node Expect Decl
3369 @subsection Suppressing Conflict Warnings
3370 @cindex suppressing conflict warnings
3371 @cindex preventing warnings about conflicts
3372 @cindex warnings, preventing
3373 @cindex conflicts, suppressing warnings of
3374 @findex %expect
3375
3376 Bison normally warns if there are any conflicts in the grammar
3377 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
3378 have harmless shift/reduce conflicts which are resolved in a predictable
3379 way and would be difficult to eliminate. It is desirable to suppress
3380 the warning about these conflicts unless the number of conflicts
3381 changes. You can do this with the @code{%expect} declaration.
3382
3383 The declaration looks like this:
3384
3385 @example
3386 %expect @var{n}
3387 @end example
3388
3389 Here @var{n} is a decimal integer. The declaration says there should be
3390 no warning if there are @var{n} shift/reduce conflicts and no
3391 reduce/reduce conflicts. An error, instead of the usual warning, is
3392 given if there are either more or fewer conflicts, or if there are any
3393 reduce/reduce conflicts.
3394
3395 In general, using @code{%expect} involves these steps:
3396
3397 @itemize @bullet
3398 @item
3399 Compile your grammar without @code{%expect}. Use the @samp{-v} option
3400 to get a verbose list of where the conflicts occur. Bison will also
3401 print the number of conflicts.
3402
3403 @item
3404 Check each of the conflicts to make sure that Bison's default
3405 resolution is what you really want. If not, rewrite the grammar and
3406 go back to the beginning.
3407
3408 @item
3409 Add an @code{%expect} declaration, copying the number @var{n} from the
3410 number which Bison printed.
3411 @end itemize
3412
3413 Now Bison will stop annoying you about the conflicts you have checked, but
3414 it will warn you again if changes in the grammar result in additional
3415 conflicts.
3416
3417 @node Start Decl
3418 @subsection The Start-Symbol
3419 @cindex declaring the start symbol
3420 @cindex start symbol, declaring
3421 @cindex default start symbol
3422 @findex %start
3423
3424 Bison assumes by default that the start symbol for the grammar is the first
3425 nonterminal specified in the grammar specification section. The programmer
3426 may override this restriction with the @code{%start} declaration as follows:
3427
3428 @example
3429 %start @var{symbol}
3430 @end example
3431
3432 @node Pure Decl
3433 @subsection A Pure (Reentrant) Parser
3434 @cindex reentrant parser
3435 @cindex pure parser
3436 @findex %pure-parser
3437
3438 A @dfn{reentrant} program is one which does not alter in the course of
3439 execution; in other words, it consists entirely of @dfn{pure} (read-only)
3440 code. Reentrancy is important whenever asynchronous execution is possible;
3441 for example, a non-reentrant program may not be safe to call from a signal
3442 handler. In systems with multiple threads of control, a non-reentrant
3443 program must be called only within interlocks.
3444
3445 Normally, Bison generates a parser which is not reentrant. This is
3446 suitable for most uses, and it permits compatibility with Yacc. (The
3447 standard Yacc interfaces are inherently nonreentrant, because they use
3448 statically allocated variables for communication with @code{yylex},
3449 including @code{yylval} and @code{yylloc}.)
3450
3451 Alternatively, you can generate a pure, reentrant parser. The Bison
3452 declaration @code{%pure-parser} says that you want the parser to be
3453 reentrant. It looks like this:
3454
3455 @example
3456 %pure-parser
3457 @end example
3458
3459 The result is that the communication variables @code{yylval} and
3460 @code{yylloc} become local variables in @code{yyparse}, and a different
3461 calling convention is used for the lexical analyzer function
3462 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
3463 Parsers}, for the details of this. The variable @code{yynerrs} also
3464 becomes local in @code{yyparse} (@pxref{Error Reporting, ,The Error
3465 Reporting Function @code{yyerror}}). The convention for calling
3466 @code{yyparse} itself is unchanged.
3467
3468 Whether the parser is pure has nothing to do with the grammar rules.
3469 You can generate either a pure parser or a nonreentrant parser from any
3470 valid grammar.
3471
3472 @node Decl Summary
3473 @subsection Bison Declaration Summary
3474 @cindex Bison declaration summary
3475 @cindex declaration summary
3476 @cindex summary, Bison declaration
3477
3478 Here is a summary of the declarations used to define a grammar:
3479
3480 @table @code
3481 @item %union
3482 Declare the collection of data types that semantic values may have
3483 (@pxref{Union Decl, ,The Collection of Value Types}).
3484
3485 @item %token
3486 Declare a terminal symbol (token type name) with no precedence
3487 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
3488
3489 @item %right
3490 Declare a terminal symbol (token type name) that is right-associative
3491 (@pxref{Precedence Decl, ,Operator Precedence}).
3492
3493 @item %left
3494 Declare a terminal symbol (token type name) that is left-associative
3495 (@pxref{Precedence Decl, ,Operator Precedence}).
3496
3497 @item %nonassoc
3498 Declare a terminal symbol (token type name) that is nonassociative
3499 (using it in a way that would be associative is a syntax error)
3500 (@pxref{Precedence Decl, ,Operator Precedence}).
3501
3502 @item %type
3503 Declare the type of semantic values for a nonterminal symbol
3504 (@pxref{Type Decl, ,Nonterminal Symbols}).
3505
3506 @item %start
3507 Specify the grammar's start symbol (@pxref{Start Decl, ,The
3508 Start-Symbol}).
3509
3510 @item %expect
3511 Declare the expected number of shift-reduce conflicts
3512 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
3513 @end table
3514
3515 @sp 1
3516 @noindent
3517 In order to change the behavior of @command{bison}, use the following
3518 directives:
3519
3520 @table @code
3521 @item %debug
3522 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
3523 already defined, so that the debugging facilities are compiled.
3524 @xref{Tracing, ,Tracing Your Parser}.
3525
3526 @item %defines
3527 Write an extra output file containing macro definitions for the token
3528 type names defined in the grammar and the semantic value type
3529 @code{YYSTYPE}, as well as a few @code{extern} variable declarations.
3530
3531 If the parser output file is named @file{@var{name}.c} then this file
3532 is named @file{@var{name}.h}.
3533
3534 This output file is essential if you wish to put the definition of
3535 @code{yylex} in a separate source file, because @code{yylex} needs to
3536 be able to refer to token type codes and the variable
3537 @code{yylval}. @xref{Token Values, ,Semantic Values of Tokens}.
3538
3539 @item %file-prefix="@var{prefix}"
3540 Specify a prefix to use for all Bison output file names. The names are
3541 chosen as if the input file were named @file{@var{prefix}.y}.
3542
3543 @c @item %header-extension
3544 @c Specify the extension of the parser header file generated when
3545 @c @code{%define} or @samp{-d} are used.
3546 @c
3547 @c For example, a grammar file named @file{foo.ypp} and containing a
3548 @c @code{%header-extension .hh} directive will produce a header file
3549 @c named @file{foo.tab.hh}
3550
3551 @item %locations
3552 Generate the code processing the locations (@pxref{Action Features,
3553 ,Special Features for Use in Actions}). This mode is enabled as soon as
3554 the grammar uses the special @samp{@@@var{n}} tokens, but if your
3555 grammar does not use it, using @samp{%locations} allows for more
3556 accurate parse error messages.
3557
3558 @item %name-prefix="@var{prefix}"
3559 Rename the external symbols used in the parser so that they start with
3560 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
3561 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
3562 @code{yylval}, @code{yylloc}, @code{yychar}, @code{yydebug}, and
3563 possible @code{yylloc}. For example, if you use
3564 @samp{%name-prefix="c_"}, the names become @code{c_parse}, @code{c_lex},
3565 and so on. @xref{Multiple Parsers, ,Multiple Parsers in the Same
3566 Program}.
3567
3568 @item %no-parser
3569 Do not include any C code in the parser file; generate tables only. The
3570 parser file contains just @code{#define} directives and static variable
3571 declarations.
3572
3573 This option also tells Bison to write the C code for the grammar actions
3574 into a file named @file{@var{filename}.act}, in the form of a
3575 brace-surrounded body fit for a @code{switch} statement.
3576
3577 @item %no-lines
3578 Don't generate any @code{#line} preprocessor commands in the parser
3579 file. Ordinarily Bison writes these commands in the parser file so that
3580 the C compiler and debuggers will associate errors and object code with
3581 your source file (the grammar file). This directive causes them to
3582 associate errors with the parser file, treating it an independent source
3583 file in its own right.
3584
3585 @item %output="@var{filename}"
3586 Specify the @var{filename} for the parser file.
3587
3588 @item %pure-parser
3589 Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure
3590 (Reentrant) Parser}).
3591
3592 @c @item %source-extension
3593 @c Specify the extension of the parser output file.
3594 @c
3595 @c For example, a grammar file named @file{foo.yy} and containing a
3596 @c @code{%source-extension .cpp} directive will produce a parser file
3597 @c named @file{foo.tab.cpp}
3598
3599 @item %token-table
3600 Generate an array of token names in the parser file. The name of the
3601 array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
3602 token whose internal Bison token code number is @var{i}. The first
3603 three elements of @code{yytname} are always @code{"$end"},
3604 @code{"error"}, and @code{"$undefined"}; after these come the symbols
3605 defined in the grammar file.
3606
3607 For single-character literal tokens and literal string tokens, the name
3608 in the table includes the single-quote or double-quote characters: for
3609 example, @code{"'+'"} is a single-character literal and @code{"\"<=\""}
3610 is a literal string token. All the characters of the literal string
3611 token appear verbatim in the string found in the table; even
3612 double-quote characters are not escaped. For example, if the token
3613 consists of three characters @samp{*"*}, its string in @code{yytname}
3614 contains @samp{"*"*"}. (In C, that would be written as
3615 @code{"\"*\"*\""}).
3616
3617 When you specify @code{%token-table}, Bison also generates macro
3618 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
3619 @code{YYNRULES}, and @code{YYNSTATES}:
3620
3621 @table @code
3622 @item YYNTOKENS
3623 The highest token number, plus one.
3624 @item YYNNTS
3625 The number of nonterminal symbols.
3626 @item YYNRULES
3627 The number of grammar rules,
3628 @item YYNSTATES
3629 The number of parser states (@pxref{Parser States}).
3630 @end table
3631
3632 @item %verbose
3633 Write an extra output file containing verbose descriptions of the
3634 parser states and what is done for each type of look-ahead token in
3635 that state. @xref{Understanding, , Understanding Your Parser}, for more
3636 information.
3637
3638
3639
3640 @item %yacc
3641 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
3642 including its naming conventions. @xref{Bison Options}, for more.
3643 @end table
3644
3645
3646
3647
3648 @node Multiple Parsers
3649 @section Multiple Parsers in the Same Program
3650
3651 Most programs that use Bison parse only one language and therefore contain
3652 only one Bison parser. But what if you want to parse more than one
3653 language with the same program? Then you need to avoid a name conflict
3654 between different definitions of @code{yyparse}, @code{yylval}, and so on.
3655
3656 The easy way to do this is to use the option @samp{-p @var{prefix}}
3657 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
3658 functions and variables of the Bison parser to start with @var{prefix}
3659 instead of @samp{yy}. You can use this to give each parser distinct
3660 names that do not conflict.
3661
3662 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
3663 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
3664 @code{yychar} and @code{yydebug}. For example, if you use @samp{-p c},
3665 the names become @code{cparse}, @code{clex}, and so on.
3666
3667 @strong{All the other variables and macros associated with Bison are not
3668 renamed.} These others are not global; there is no conflict if the same
3669 name is used in different parsers. For example, @code{YYSTYPE} is not
3670 renamed, but defining this in different ways in different parsers causes
3671 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
3672
3673 The @samp{-p} option works by adding macro definitions to the beginning
3674 of the parser source file, defining @code{yyparse} as
3675 @code{@var{prefix}parse}, and so on. This effectively substitutes one
3676 name for the other in the entire parser file.
3677
3678 @node Interface
3679 @chapter Parser C-Language Interface
3680 @cindex C-language interface
3681 @cindex interface
3682
3683 The Bison parser is actually a C function named @code{yyparse}. Here we
3684 describe the interface conventions of @code{yyparse} and the other
3685 functions that it needs to use.
3686
3687 Keep in mind that the parser uses many C identifiers starting with
3688 @samp{yy} and @samp{YY} for internal purposes. If you use such an
3689 identifier (aside from those in this manual) in an action or in epilogue
3690 in the grammar file, you are likely to run into trouble.
3691
3692 @menu
3693 * Parser Function:: How to call @code{yyparse} and what it returns.
3694 * Lexical:: You must supply a function @code{yylex}
3695 which reads tokens.
3696 * Error Reporting:: You must supply a function @code{yyerror}.
3697 * Action Features:: Special features for use in actions.
3698 @end menu
3699
3700 @node Parser Function
3701 @section The Parser Function @code{yyparse}
3702 @findex yyparse
3703
3704 You call the function @code{yyparse} to cause parsing to occur. This
3705 function reads tokens, executes actions, and ultimately returns when it
3706 encounters end-of-input or an unrecoverable syntax error. You can also
3707 write an action which directs @code{yyparse} to return immediately
3708 without reading further.
3709
3710
3711 @deftypefun int yyparse (void)
3712 The value returned by @code{yyparse} is 0 if parsing was successful (return
3713 is due to end-of-input).
3714
3715 The value is 1 if parsing failed (return is due to a syntax error).
3716 @end deftypefun
3717
3718 In an action, you can cause immediate return from @code{yyparse} by using
3719 these macros:
3720
3721 @defmac YYACCEPT
3722 @findex YYACCEPT
3723 Return immediately with value 0 (to report success).
3724 @end defmac
3725
3726 @defmac YYABORT
3727 @findex YYABORT
3728 Return immediately with value 1 (to report failure).
3729 @end defmac
3730
3731 If you use a reentrant parser, you can optionally pass additional
3732 parameter information to it in a reentrant way. To do so, use the
3733 declaration @code{%parse-param}:
3734
3735 @deffn {Directive} %parse-param @var{argument-declaration} @var{argument-name}
3736 @findex %parse-param
3737 Declare that @code{argument-name} is an additional @code{yyparse}
3738 argument. This argument is also passed to @code{yyerror}. The
3739 @var{argument-declaration} is used when declaring functions or
3740 prototypes.
3741 @end deffn
3742
3743 Here's an example. Write this in the parser:
3744
3745 @example
3746 %parse-param "int *nastiness" "nastiness"
3747 %parse-param "int *randomness" "randomness"
3748 @end example
3749
3750 @noindent
3751 Then call the parser like this:
3752
3753 @example
3754 @{
3755 int nastiness, randomness;
3756 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
3757 value = yyparse (&nastiness, &randomness);
3758 @dots{}
3759 @}
3760 @end example
3761
3762 @noindent
3763 In the grammar actions, use expressions like this to refer to the data:
3764
3765 @example
3766 exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
3767 @end example
3768
3769
3770 @node Lexical
3771 @section The Lexical Analyzer Function @code{yylex}
3772 @findex yylex
3773 @cindex lexical analyzer
3774
3775 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
3776 the input stream and returns them to the parser. Bison does not create
3777 this function automatically; you must write it so that @code{yyparse} can
3778 call it. The function is sometimes referred to as a lexical scanner.
3779
3780 In simple programs, @code{yylex} is often defined at the end of the Bison
3781 grammar file. If @code{yylex} is defined in a separate source file, you
3782 need to arrange for the token-type macro definitions to be available there.
3783 To do this, use the @samp{-d} option when you run Bison, so that it will
3784 write these macro definitions into a separate header file
3785 @file{@var{name}.tab.h} which you can include in the other source files
3786 that need it. @xref{Invocation, ,Invoking Bison}.
3787
3788 @menu
3789 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
3790 * Token Values:: How @code{yylex} must return the semantic value
3791 of the token it has read.
3792 * Token Positions:: How @code{yylex} must return the text position
3793 (line number, etc.) of the token, if the
3794 actions want that.
3795 * Pure Calling:: How the calling convention differs
3796 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
3797 @end menu
3798
3799 @node Calling Convention
3800 @subsection Calling Convention for @code{yylex}
3801
3802 The value that @code{yylex} returns must be the positive numeric code
3803 for the type of token it has just found; a zero or negative value
3804 signifies end-of-input.
3805
3806 When a token is referred to in the grammar rules by a name, that name
3807 in the parser file becomes a C macro whose definition is the proper
3808 numeric code for that token type. So @code{yylex} can use the name
3809 to indicate that type. @xref{Symbols}.
3810
3811 When a token is referred to in the grammar rules by a character literal,
3812 the numeric code for that character is also the code for the token type.
3813 So @code{yylex} can simply return that character code, possibly converted
3814 to @code{unsigned char} to avoid sign-extension. The null character
3815 must not be used this way, because its code is zero and that
3816 signifies end-of-input.
3817
3818 Here is an example showing these things:
3819
3820 @example
3821 int
3822 yylex (void)
3823 @{
3824 @dots{}
3825 if (c == EOF) /* Detect end-of-input. */
3826 return 0;
3827 @dots{}
3828 if (c == '+' || c == '-')
3829 return c; /* Assume token type for `+' is '+'. */
3830 @dots{}
3831 return INT; /* Return the type of the token. */
3832 @dots{}
3833 @}
3834 @end example
3835
3836 @noindent
3837 This interface has been designed so that the output from the @code{lex}
3838 utility can be used without change as the definition of @code{yylex}.
3839
3840 If the grammar uses literal string tokens, there are two ways that
3841 @code{yylex} can determine the token type codes for them:
3842
3843 @itemize @bullet
3844 @item
3845 If the grammar defines symbolic token names as aliases for the
3846 literal string tokens, @code{yylex} can use these symbolic names like
3847 all others. In this case, the use of the literal string tokens in
3848 the grammar file has no effect on @code{yylex}.
3849
3850 @item
3851 @code{yylex} can find the multicharacter token in the @code{yytname}
3852 table. The index of the token in the table is the token type's code.
3853 The name of a multicharacter token is recorded in @code{yytname} with a
3854 double-quote, the token's characters, and another double-quote. The
3855 token's characters are not escaped in any way; they appear verbatim in
3856 the contents of the string in the table.
3857
3858 Here's code for looking up a token in @code{yytname}, assuming that the
3859 characters of the token are stored in @code{token_buffer}.
3860
3861 @smallexample
3862 for (i = 0; i < YYNTOKENS; i++)
3863 @{
3864 if (yytname[i] != 0
3865 && yytname[i][0] == '"'
3866 && ! strncmp (yytname[i] + 1, token_buffer,
3867 strlen (token_buffer))
3868 && yytname[i][strlen (token_buffer) + 1] == '"'
3869 && yytname[i][strlen (token_buffer) + 2] == 0)
3870 break;
3871 @}
3872 @end smallexample
3873
3874 The @code{yytname} table is generated only if you use the
3875 @code{%token-table} declaration. @xref{Decl Summary}.
3876 @end itemize
3877
3878 @node Token Values
3879 @subsection Semantic Values of Tokens
3880
3881 @vindex yylval
3882 In an ordinary (non-reentrant) parser, the semantic value of the token must
3883 be stored into the global variable @code{yylval}. When you are using
3884 just one data type for semantic values, @code{yylval} has that type.
3885 Thus, if the type is @code{int} (the default), you might write this in
3886 @code{yylex}:
3887
3888 @example
3889 @group
3890 @dots{}
3891 yylval = value; /* Put value onto Bison stack. */
3892 return INT; /* Return the type of the token. */
3893 @dots{}
3894 @end group
3895 @end example
3896
3897 When you are using multiple data types, @code{yylval}'s type is a union
3898 made from the @code{%union} declaration (@pxref{Union Decl, ,The
3899 Collection of Value Types}). So when you store a token's value, you
3900 must use the proper member of the union. If the @code{%union}
3901 declaration looks like this:
3902
3903 @example
3904 @group
3905 %union @{
3906 int intval;
3907 double val;
3908 symrec *tptr;
3909 @}
3910 @end group
3911 @end example
3912
3913 @noindent
3914 then the code in @code{yylex} might look like this:
3915
3916 @example
3917 @group
3918 @dots{}
3919 yylval.intval = value; /* Put value onto Bison stack. */
3920 return INT; /* Return the type of the token. */
3921 @dots{}
3922 @end group
3923 @end example
3924
3925 @node Token Positions
3926 @subsection Textual Positions of Tokens
3927
3928 @vindex yylloc
3929 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
3930 Tracking Locations}) in actions to keep track of the
3931 textual locations of tokens and groupings, then you must provide this
3932 information in @code{yylex}. The function @code{yyparse} expects to
3933 find the textual location of a token just parsed in the global variable
3934 @code{yylloc}. So @code{yylex} must store the proper data in that
3935 variable.
3936
3937 By default, the value of @code{yylloc} is a structure and you need only
3938 initialize the members that are going to be used by the actions. The
3939 four members are called @code{first_line}, @code{first_column},
3940 @code{last_line} and @code{last_column}. Note that the use of this
3941 feature makes the parser noticeably slower.
3942
3943 @tindex YYLTYPE
3944 The data type of @code{yylloc} has the name @code{YYLTYPE}.
3945
3946 @node Pure Calling
3947 @subsection Calling Conventions for Pure Parsers
3948
3949 When you use the Bison declaration @code{%pure-parser} to request a
3950 pure, reentrant parser, the global communication variables @code{yylval}
3951 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
3952 Parser}.) In such parsers the two global variables are replaced by
3953 pointers passed as arguments to @code{yylex}. You must declare them as
3954 shown here, and pass the information back by storing it through those
3955 pointers.
3956
3957 @example
3958 int
3959 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
3960 @{
3961 @dots{}
3962 *lvalp = value; /* Put value onto Bison stack. */
3963 return INT; /* Return the type of the token. */
3964 @dots{}
3965 @}
3966 @end example
3967
3968 If the grammar file does not use the @samp{@@} constructs to refer to
3969 textual positions, then the type @code{YYLTYPE} will not be defined. In
3970 this case, omit the second argument; @code{yylex} will be called with
3971 only one argument.
3972
3973
3974 If you wish to pass the additional parameter data to @code{yylex}, use
3975 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
3976 Function}).
3977
3978 @deffn {Directive} lex-param @var{argument-declaration} @var{argument-name}
3979 @findex %lex-param
3980 Declare that @code{argument-name} is an additional @code{yylex}
3981 argument.
3982 @end deffn
3983
3984 For instance:
3985
3986 @example
3987 %parse-param "int *nastiness" "nastiness"
3988 %lex-param "int *nastiness" "nastiness"
3989 %parse-param "int *randomness" "randomness"
3990 @end example
3991
3992 @noindent
3993 results in the following signature:
3994
3995 @example
3996 int yylex (int *nastiness);
3997 int yyparse (int *nastiness, int *randomness);
3998 @end example
3999
4000 If @code{%pure-parser} is added:
4001
4002 @example
4003 int yylex (YYSTYPE *lvalp, int *nastiness);
4004 int yyparse (int *nastiness, int *randomness);
4005 @end example
4006
4007 @noindent
4008 and finally, if both @code{%pure-parser} and @code{%locations} are used:
4009
4010 @example
4011 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
4012 int yyparse (int *nastiness, int *randomness);
4013 @end example
4014
4015 @node Error Reporting
4016 @section The Error Reporting Function @code{yyerror}
4017 @cindex error reporting function
4018 @findex yyerror
4019 @cindex parse error
4020 @cindex syntax error
4021
4022 The Bison parser detects a @dfn{parse error} or @dfn{syntax error}
4023 whenever it reads a token which cannot satisfy any syntax rule. An
4024 action in the grammar can also explicitly proclaim an error, using the
4025 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
4026 in Actions}).
4027
4028 The Bison parser expects to report the error by calling an error
4029 reporting function named @code{yyerror}, which you must supply. It is
4030 called by @code{yyparse} whenever a syntax error is found, and it
4031 receives one argument. For a parse error, the string is normally
4032 @w{@code{"parse error"}}.
4033
4034 @findex %error-verbose
4035 If you invoke the directive @code{%error-verbose} in the Bison
4036 declarations section (@pxref{Bison Declarations, ,The Bison Declarations
4037 Section}), then Bison provides a more verbose and specific error message
4038 string instead of just plain @w{@code{"parse error"}}.
4039
4040 The parser can detect one other kind of error: stack overflow. This
4041 happens when the input contains constructions that are very deeply
4042 nested. It isn't likely you will encounter this, since the Bison
4043 parser extends its stack automatically up to a very large limit. But
4044 if overflow happens, @code{yyparse} calls @code{yyerror} in the usual
4045 fashion, except that the argument string is @w{@code{"parser stack
4046 overflow"}}.
4047
4048 The following definition suffices in simple programs:
4049
4050 @example
4051 @group
4052 void
4053 yyerror (char *s)
4054 @{
4055 @end group
4056 @group
4057 fprintf (stderr, "%s\n", s);
4058 @}
4059 @end group
4060 @end example
4061
4062 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
4063 error recovery if you have written suitable error recovery grammar rules
4064 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
4065 immediately return 1.
4066
4067 Oviously, in location tracking pure parsers, @code{yyerror} should have
4068 an access to the current location. This is indeed the case for the GLR
4069 parsers, but not for the Yacc parser, for historical reasons. I.e., if
4070 @samp{%locations %pure-parser} is passed then the prototypes for
4071 @code{yyerror} are:
4072
4073 @example
4074 void yyerror (const char *msg); /* Yacc parsers. */
4075 void yyerror (const char *msg, YYLTYPE *locp); /* GLR parsers. */
4076 @end example
4077
4078 If @samp{%parse-param "int *nastiness" "nastiness"} is used, then:
4079
4080 @example
4081 void yyerror (int *randomness); /* Yacc parsers. */
4082 void yyerror (int *randomness); /* GLR parsers. */
4083 @end example
4084
4085 Finally, GLR and Yacc parsers share the same @code{yyerror} calling
4086 convention for absolutely pure parsers, i.e., when the calling
4087 convention of @code{yylex} @emph{and} the calling convention of
4088 @code{%pure-parser} are pure. I.e.:
4089
4090 @example
4091 /* Location tracking. */
4092 %locations
4093 /* Pure yylex. */
4094 %pure-parser
4095 %lex-param "int *nastiness" "nastiness"
4096 /* Pure yyparse. */
4097 %parse-param "int *nastiness" "nastiness"
4098 %parse-param "int *randomness" "randomness"
4099 @end example
4100
4101 @noindent
4102 results in the following signatures for all the parser kinds:
4103
4104 @example
4105 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
4106 int yyparse (int *nastiness, int *randomness);
4107 void yyerror (const char *msg, YYLTYPE *locp,
4108 int *nastiness, int *randomness);
4109 @end example
4110
4111 @vindex yynerrs
4112 The variable @code{yynerrs} contains the number of syntax errors
4113 encountered so far. Normally this variable is global; but if you
4114 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
4115 then it is a local variable which only the actions can access.
4116
4117 @node Action Features
4118 @section Special Features for Use in Actions
4119 @cindex summary, action features
4120 @cindex action features summary
4121
4122 Here is a table of Bison constructs, variables and macros that
4123 are useful in actions.
4124
4125 @table @samp
4126 @item $$
4127 Acts like a variable that contains the semantic value for the
4128 grouping made by the current rule. @xref{Actions}.
4129
4130 @item $@var{n}
4131 Acts like a variable that contains the semantic value for the
4132 @var{n}th component of the current rule. @xref{Actions}.
4133
4134 @item $<@var{typealt}>$
4135 Like @code{$$} but specifies alternative @var{typealt} in the union
4136 specified by the @code{%union} declaration. @xref{Action Types, ,Data
4137 Types of Values in Actions}.
4138
4139 @item $<@var{typealt}>@var{n}
4140 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
4141 union specified by the @code{%union} declaration.
4142 @xref{Action Types, ,Data Types of Values in Actions}.
4143
4144 @item YYABORT;
4145 Return immediately from @code{yyparse}, indicating failure.
4146 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
4147
4148 @item YYACCEPT;
4149 Return immediately from @code{yyparse}, indicating success.
4150 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
4151
4152 @item YYBACKUP (@var{token}, @var{value});
4153 @findex YYBACKUP
4154 Unshift a token. This macro is allowed only for rules that reduce
4155 a single value, and only when there is no look-ahead token.
4156 It is also disallowed in @acronym{GLR} parsers.
4157 It installs a look-ahead token with token type @var{token} and
4158 semantic value @var{value}; then it discards the value that was
4159 going to be reduced by this rule.
4160
4161 If the macro is used when it is not valid, such as when there is
4162 a look-ahead token already, then it reports a syntax error with
4163 a message @samp{cannot back up} and performs ordinary error
4164 recovery.
4165
4166 In either case, the rest of the action is not executed.
4167
4168 @item YYEMPTY
4169 @vindex YYEMPTY
4170 Value stored in @code{yychar} when there is no look-ahead token.
4171
4172 @item YYERROR;
4173 @findex YYERROR
4174 Cause an immediate syntax error. This statement initiates error
4175 recovery just as if the parser itself had detected an error; however, it
4176 does not call @code{yyerror}, and does not print any message. If you
4177 want to print an error message, call @code{yyerror} explicitly before
4178 the @samp{YYERROR;} statement. @xref{Error Recovery}.
4179
4180 @item YYRECOVERING
4181 This macro stands for an expression that has the value 1 when the parser
4182 is recovering from a syntax error, and 0 the rest of the time.
4183 @xref{Error Recovery}.
4184
4185 @item yychar
4186 Variable containing the current look-ahead token. (In a pure parser,
4187 this is actually a local variable within @code{yyparse}.) When there is
4188 no look-ahead token, the value @code{YYEMPTY} is stored in the variable.
4189 @xref{Look-Ahead, ,Look-Ahead Tokens}.
4190
4191 @item yyclearin;
4192 Discard the current look-ahead token. This is useful primarily in
4193 error rules. @xref{Error Recovery}.
4194
4195 @item yyerrok;
4196 Resume generating error messages immediately for subsequent syntax
4197 errors. This is useful primarily in error rules.
4198 @xref{Error Recovery}.
4199
4200 @item @@$
4201 @findex @@$
4202 Acts like a structure variable containing information on the textual position
4203 of the grouping made by the current rule. @xref{Locations, ,
4204 Tracking Locations}.
4205
4206 @c Check if those paragraphs are still useful or not.
4207
4208 @c @example
4209 @c struct @{
4210 @c int first_line, last_line;
4211 @c int first_column, last_column;
4212 @c @};
4213 @c @end example
4214
4215 @c Thus, to get the starting line number of the third component, you would
4216 @c use @samp{@@3.first_line}.
4217
4218 @c In order for the members of this structure to contain valid information,
4219 @c you must make @code{yylex} supply this information about each token.
4220 @c If you need only certain members, then @code{yylex} need only fill in
4221 @c those members.
4222
4223 @c The use of this feature makes the parser noticeably slower.
4224
4225 @item @@@var{n}
4226 @findex @@@var{n}
4227 Acts like a structure variable containing information on the textual position
4228 of the @var{n}th component of the current rule. @xref{Locations, ,
4229 Tracking Locations}.
4230
4231 @end table
4232
4233 @node Algorithm
4234 @chapter The Bison Parser Algorithm
4235 @cindex Bison parser algorithm
4236 @cindex algorithm of parser
4237 @cindex shifting
4238 @cindex reduction
4239 @cindex parser stack
4240 @cindex stack, parser
4241
4242 As Bison reads tokens, it pushes them onto a stack along with their
4243 semantic values. The stack is called the @dfn{parser stack}. Pushing a
4244 token is traditionally called @dfn{shifting}.
4245
4246 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
4247 @samp{3} to come. The stack will have four elements, one for each token
4248 that was shifted.
4249
4250 But the stack does not always have an element for each token read. When
4251 the last @var{n} tokens and groupings shifted match the components of a
4252 grammar rule, they can be combined according to that rule. This is called
4253 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
4254 single grouping whose symbol is the result (left hand side) of that rule.
4255 Running the rule's action is part of the process of reduction, because this
4256 is what computes the semantic value of the resulting grouping.
4257
4258 For example, if the infix calculator's parser stack contains this:
4259
4260 @example
4261 1 + 5 * 3
4262 @end example
4263
4264 @noindent
4265 and the next input token is a newline character, then the last three
4266 elements can be reduced to 15 via the rule:
4267
4268 @example
4269 expr: expr '*' expr;
4270 @end example
4271
4272 @noindent
4273 Then the stack contains just these three elements:
4274
4275 @example
4276 1 + 15
4277 @end example
4278
4279 @noindent
4280 At this point, another reduction can be made, resulting in the single value
4281 16. Then the newline token can be shifted.
4282
4283 The parser tries, by shifts and reductions, to reduce the entire input down
4284 to a single grouping whose symbol is the grammar's start-symbol
4285 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
4286
4287 This kind of parser is known in the literature as a bottom-up parser.
4288
4289 @menu
4290 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
4291 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
4292 * Precedence:: Operator precedence works by resolving conflicts.
4293 * Contextual Precedence:: When an operator's precedence depends on context.
4294 * Parser States:: The parser is a finite-state-machine with stack.
4295 * Reduce/Reduce:: When two rules are applicable in the same situation.
4296 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
4297 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
4298 * Stack Overflow:: What happens when stack gets full. How to avoid it.
4299 @end menu
4300
4301 @node Look-Ahead
4302 @section Look-Ahead Tokens
4303 @cindex look-ahead token
4304
4305 The Bison parser does @emph{not} always reduce immediately as soon as the
4306 last @var{n} tokens and groupings match a rule. This is because such a
4307 simple strategy is inadequate to handle most languages. Instead, when a
4308 reduction is possible, the parser sometimes ``looks ahead'' at the next
4309 token in order to decide what to do.
4310
4311 When a token is read, it is not immediately shifted; first it becomes the
4312 @dfn{look-ahead token}, which is not on the stack. Now the parser can
4313 perform one or more reductions of tokens and groupings on the stack, while
4314 the look-ahead token remains off to the side. When no more reductions
4315 should take place, the look-ahead token is shifted onto the stack. This
4316 does not mean that all possible reductions have been done; depending on the
4317 token type of the look-ahead token, some rules may choose to delay their
4318 application.
4319
4320 Here is a simple case where look-ahead is needed. These three rules define
4321 expressions which contain binary addition operators and postfix unary
4322 factorial operators (@samp{!}), and allow parentheses for grouping.
4323
4324 @example
4325 @group
4326 expr: term '+' expr
4327 | term
4328 ;
4329 @end group
4330
4331 @group
4332 term: '(' expr ')'
4333 | term '!'
4334 | NUMBER
4335 ;
4336 @end group
4337 @end example
4338
4339 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
4340 should be done? If the following token is @samp{)}, then the first three
4341 tokens must be reduced to form an @code{expr}. This is the only valid
4342 course, because shifting the @samp{)} would produce a sequence of symbols
4343 @w{@code{term ')'}}, and no rule allows this.
4344
4345 If the following token is @samp{!}, then it must be shifted immediately so
4346 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
4347 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
4348 @code{expr}. It would then be impossible to shift the @samp{!} because
4349 doing so would produce on the stack the sequence of symbols @code{expr
4350 '!'}. No rule allows that sequence.
4351
4352 @vindex yychar
4353 The current look-ahead token is stored in the variable @code{yychar}.
4354 @xref{Action Features, ,Special Features for Use in Actions}.
4355
4356 @node Shift/Reduce
4357 @section Shift/Reduce Conflicts
4358 @cindex conflicts
4359 @cindex shift/reduce conflicts
4360 @cindex dangling @code{else}
4361 @cindex @code{else}, dangling
4362
4363 Suppose we are parsing a language which has if-then and if-then-else
4364 statements, with a pair of rules like this:
4365
4366 @example
4367 @group
4368 if_stmt:
4369 IF expr THEN stmt
4370 | IF expr THEN stmt ELSE stmt
4371 ;
4372 @end group
4373 @end example
4374
4375 @noindent
4376 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
4377 terminal symbols for specific keyword tokens.
4378
4379 When the @code{ELSE} token is read and becomes the look-ahead token, the
4380 contents of the stack (assuming the input is valid) are just right for
4381 reduction by the first rule. But it is also legitimate to shift the
4382 @code{ELSE}, because that would lead to eventual reduction by the second
4383 rule.
4384
4385 This situation, where either a shift or a reduction would be valid, is
4386 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
4387 these conflicts by choosing to shift, unless otherwise directed by
4388 operator precedence declarations. To see the reason for this, let's
4389 contrast it with the other alternative.
4390
4391 Since the parser prefers to shift the @code{ELSE}, the result is to attach
4392 the else-clause to the innermost if-statement, making these two inputs
4393 equivalent:
4394
4395 @example
4396 if x then if y then win (); else lose;
4397
4398 if x then do; if y then win (); else lose; end;
4399 @end example
4400
4401 But if the parser chose to reduce when possible rather than shift, the
4402 result would be to attach the else-clause to the outermost if-statement,
4403 making these two inputs equivalent:
4404
4405 @example
4406 if x then if y then win (); else lose;
4407
4408 if x then do; if y then win (); end; else lose;
4409 @end example
4410
4411 The conflict exists because the grammar as written is ambiguous: either
4412 parsing of the simple nested if-statement is legitimate. The established
4413 convention is that these ambiguities are resolved by attaching the
4414 else-clause to the innermost if-statement; this is what Bison accomplishes
4415 by choosing to shift rather than reduce. (It would ideally be cleaner to
4416 write an unambiguous grammar, but that is very hard to do in this case.)
4417 This particular ambiguity was first encountered in the specifications of
4418 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
4419
4420 To avoid warnings from Bison about predictable, legitimate shift/reduce
4421 conflicts, use the @code{%expect @var{n}} declaration. There will be no
4422 warning as long as the number of shift/reduce conflicts is exactly @var{n}.
4423 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
4424
4425 The definition of @code{if_stmt} above is solely to blame for the
4426 conflict, but the conflict does not actually appear without additional
4427 rules. Here is a complete Bison input file that actually manifests the
4428 conflict:
4429
4430 @example
4431 @group
4432 %token IF THEN ELSE variable
4433 %%
4434 @end group
4435 @group
4436 stmt: expr
4437 | if_stmt
4438 ;
4439 @end group
4440
4441 @group
4442 if_stmt:
4443 IF expr THEN stmt
4444 | IF expr THEN stmt ELSE stmt
4445 ;
4446 @end group
4447
4448 expr: variable
4449 ;
4450 @end example
4451
4452 @node Precedence
4453 @section Operator Precedence
4454 @cindex operator precedence
4455 @cindex precedence of operators
4456
4457 Another situation where shift/reduce conflicts appear is in arithmetic
4458 expressions. Here shifting is not always the preferred resolution; the
4459 Bison declarations for operator precedence allow you to specify when to
4460 shift and when to reduce.
4461
4462 @menu
4463 * Why Precedence:: An example showing why precedence is needed.
4464 * Using Precedence:: How to specify precedence in Bison grammars.
4465 * Precedence Examples:: How these features are used in the previous example.
4466 * How Precedence:: How they work.
4467 @end menu
4468
4469 @node Why Precedence
4470 @subsection When Precedence is Needed
4471
4472 Consider the following ambiguous grammar fragment (ambiguous because the
4473 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
4474
4475 @example
4476 @group
4477 expr: expr '-' expr
4478 | expr '*' expr
4479 | expr '<' expr
4480 | '(' expr ')'
4481 @dots{}
4482 ;
4483 @end group
4484 @end example
4485
4486 @noindent
4487 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
4488 should it reduce them via the rule for the subtraction operator? It
4489 depends on the next token. Of course, if the next token is @samp{)}, we
4490 must reduce; shifting is invalid because no single rule can reduce the
4491 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
4492 the next token is @samp{*} or @samp{<}, we have a choice: either
4493 shifting or reduction would allow the parse to complete, but with
4494 different results.
4495
4496 To decide which one Bison should do, we must consider the results. If
4497 the next operator token @var{op} is shifted, then it must be reduced
4498 first in order to permit another opportunity to reduce the difference.
4499 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
4500 hand, if the subtraction is reduced before shifting @var{op}, the result
4501 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
4502 reduce should depend on the relative precedence of the operators
4503 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
4504 @samp{<}.
4505
4506 @cindex associativity
4507 What about input such as @w{@samp{1 - 2 - 5}}; should this be
4508 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
4509 operators we prefer the former, which is called @dfn{left association}.
4510 The latter alternative, @dfn{right association}, is desirable for
4511 assignment operators. The choice of left or right association is a
4512 matter of whether the parser chooses to shift or reduce when the stack
4513 contains @w{@samp{1 - 2}} and the look-ahead token is @samp{-}: shifting
4514 makes right-associativity.
4515
4516 @node Using Precedence
4517 @subsection Specifying Operator Precedence
4518 @findex %left
4519 @findex %right
4520 @findex %nonassoc
4521
4522 Bison allows you to specify these choices with the operator precedence
4523 declarations @code{%left} and @code{%right}. Each such declaration
4524 contains a list of tokens, which are operators whose precedence and
4525 associativity is being declared. The @code{%left} declaration makes all
4526 those operators left-associative and the @code{%right} declaration makes
4527 them right-associative. A third alternative is @code{%nonassoc}, which
4528 declares that it is a syntax error to find the same operator twice ``in a
4529 row''.
4530
4531 The relative precedence of different operators is controlled by the
4532 order in which they are declared. The first @code{%left} or
4533 @code{%right} declaration in the file declares the operators whose
4534 precedence is lowest, the next such declaration declares the operators
4535 whose precedence is a little higher, and so on.
4536
4537 @node Precedence Examples
4538 @subsection Precedence Examples
4539
4540 In our example, we would want the following declarations:
4541
4542 @example
4543 %left '<'
4544 %left '-'
4545 %left '*'
4546 @end example
4547
4548 In a more complete example, which supports other operators as well, we
4549 would declare them in groups of equal precedence. For example, @code{'+'} is
4550 declared with @code{'-'}:
4551
4552 @example
4553 %left '<' '>' '=' NE LE GE
4554 %left '+' '-'
4555 %left '*' '/'
4556 @end example
4557
4558 @noindent
4559 (Here @code{NE} and so on stand for the operators for ``not equal''
4560 and so on. We assume that these tokens are more than one character long
4561 and therefore are represented by names, not character literals.)
4562
4563 @node How Precedence
4564 @subsection How Precedence Works
4565
4566 The first effect of the precedence declarations is to assign precedence
4567 levels to the terminal symbols declared. The second effect is to assign
4568 precedence levels to certain rules: each rule gets its precedence from
4569 the last terminal symbol mentioned in the components. (You can also
4570 specify explicitly the precedence of a rule. @xref{Contextual
4571 Precedence, ,Context-Dependent Precedence}.)
4572
4573 Finally, the resolution of conflicts works by comparing the precedence
4574 of the rule being considered with that of the look-ahead token. If the
4575 token's precedence is higher, the choice is to shift. If the rule's
4576 precedence is higher, the choice is to reduce. If they have equal
4577 precedence, the choice is made based on the associativity of that
4578 precedence level. The verbose output file made by @samp{-v}
4579 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
4580 resolved.
4581
4582 Not all rules and not all tokens have precedence. If either the rule or
4583 the look-ahead token has no precedence, then the default is to shift.
4584
4585 @node Contextual Precedence
4586 @section Context-Dependent Precedence
4587 @cindex context-dependent precedence
4588 @cindex unary operator precedence
4589 @cindex precedence, context-dependent
4590 @cindex precedence, unary operator
4591 @findex %prec
4592
4593 Often the precedence of an operator depends on the context. This sounds
4594 outlandish at first, but it is really very common. For example, a minus
4595 sign typically has a very high precedence as a unary operator, and a
4596 somewhat lower precedence (lower than multiplication) as a binary operator.
4597
4598 The Bison precedence declarations, @code{%left}, @code{%right} and
4599 @code{%nonassoc}, can only be used once for a given token; so a token has
4600 only one precedence declared in this way. For context-dependent
4601 precedence, you need to use an additional mechanism: the @code{%prec}
4602 modifier for rules.
4603
4604 The @code{%prec} modifier declares the precedence of a particular rule by
4605 specifying a terminal symbol whose precedence should be used for that rule.
4606 It's not necessary for that symbol to appear otherwise in the rule. The
4607 modifier's syntax is:
4608
4609 @example
4610 %prec @var{terminal-symbol}
4611 @end example
4612
4613 @noindent
4614 and it is written after the components of the rule. Its effect is to
4615 assign the rule the precedence of @var{terminal-symbol}, overriding
4616 the precedence that would be deduced for it in the ordinary way. The
4617 altered rule precedence then affects how conflicts involving that rule
4618 are resolved (@pxref{Precedence, ,Operator Precedence}).
4619
4620 Here is how @code{%prec} solves the problem of unary minus. First, declare
4621 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
4622 are no tokens of this type, but the symbol serves to stand for its
4623 precedence:
4624
4625 @example
4626 @dots{}
4627 %left '+' '-'
4628 %left '*'
4629 %left UMINUS
4630 @end example
4631
4632 Now the precedence of @code{UMINUS} can be used in specific rules:
4633
4634 @example
4635 @group
4636 exp: @dots{}
4637 | exp '-' exp
4638 @dots{}
4639 | '-' exp %prec UMINUS
4640 @end group
4641 @end example
4642
4643 @node Parser States
4644 @section Parser States
4645 @cindex finite-state machine
4646 @cindex parser state
4647 @cindex state (of parser)
4648
4649 The function @code{yyparse} is implemented using a finite-state machine.
4650 The values pushed on the parser stack are not simply token type codes; they
4651 represent the entire sequence of terminal and nonterminal symbols at or
4652 near the top of the stack. The current state collects all the information
4653 about previous input which is relevant to deciding what to do next.
4654
4655 Each time a look-ahead token is read, the current parser state together
4656 with the type of look-ahead token are looked up in a table. This table
4657 entry can say, ``Shift the look-ahead token.'' In this case, it also
4658 specifies the new parser state, which is pushed onto the top of the
4659 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
4660 This means that a certain number of tokens or groupings are taken off
4661 the top of the stack, and replaced by one grouping. In other words,
4662 that number of states are popped from the stack, and one new state is
4663 pushed.
4664
4665 There is one other alternative: the table can say that the look-ahead token
4666 is erroneous in the current state. This causes error processing to begin
4667 (@pxref{Error Recovery}).
4668
4669 @node Reduce/Reduce
4670 @section Reduce/Reduce Conflicts
4671 @cindex reduce/reduce conflict
4672 @cindex conflicts, reduce/reduce
4673
4674 A reduce/reduce conflict occurs if there are two or more rules that apply
4675 to the same sequence of input. This usually indicates a serious error
4676 in the grammar.
4677
4678 For example, here is an erroneous attempt to define a sequence
4679 of zero or more @code{word} groupings.
4680
4681 @example
4682 sequence: /* empty */
4683 @{ printf ("empty sequence\n"); @}
4684 | maybeword
4685 | sequence word
4686 @{ printf ("added word %s\n", $2); @}
4687 ;
4688
4689 maybeword: /* empty */
4690 @{ printf ("empty maybeword\n"); @}
4691 | word
4692 @{ printf ("single word %s\n", $1); @}
4693 ;
4694 @end example
4695
4696 @noindent
4697 The error is an ambiguity: there is more than one way to parse a single
4698 @code{word} into a @code{sequence}. It could be reduced to a
4699 @code{maybeword} and then into a @code{sequence} via the second rule.
4700 Alternatively, nothing-at-all could be reduced into a @code{sequence}
4701 via the first rule, and this could be combined with the @code{word}
4702 using the third rule for @code{sequence}.
4703
4704 There is also more than one way to reduce nothing-at-all into a
4705 @code{sequence}. This can be done directly via the first rule,
4706 or indirectly via @code{maybeword} and then the second rule.
4707
4708 You might think that this is a distinction without a difference, because it
4709 does not change whether any particular input is valid or not. But it does
4710 affect which actions are run. One parsing order runs the second rule's
4711 action; the other runs the first rule's action and the third rule's action.
4712 In this example, the output of the program changes.
4713
4714 Bison resolves a reduce/reduce conflict by choosing to use the rule that
4715 appears first in the grammar, but it is very risky to rely on this. Every
4716 reduce/reduce conflict must be studied and usually eliminated. Here is the
4717 proper way to define @code{sequence}:
4718
4719 @example
4720 sequence: /* empty */
4721 @{ printf ("empty sequence\n"); @}
4722 | sequence word
4723 @{ printf ("added word %s\n", $2); @}
4724 ;
4725 @end example
4726
4727 Here is another common error that yields a reduce/reduce conflict:
4728
4729 @example
4730 sequence: /* empty */
4731 | sequence words
4732 | sequence redirects
4733 ;
4734
4735 words: /* empty */
4736 | words word
4737 ;
4738
4739 redirects:/* empty */
4740 | redirects redirect
4741 ;
4742 @end example
4743
4744 @noindent
4745 The intention here is to define a sequence which can contain either
4746 @code{word} or @code{redirect} groupings. The individual definitions of
4747 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
4748 three together make a subtle ambiguity: even an empty input can be parsed
4749 in infinitely many ways!
4750
4751 Consider: nothing-at-all could be a @code{words}. Or it could be two
4752 @code{words} in a row, or three, or any number. It could equally well be a
4753 @code{redirects}, or two, or any number. Or it could be a @code{words}
4754 followed by three @code{redirects} and another @code{words}. And so on.
4755
4756 Here are two ways to correct these rules. First, to make it a single level
4757 of sequence:
4758
4759 @example
4760 sequence: /* empty */
4761 | sequence word
4762 | sequence redirect
4763 ;
4764 @end example
4765
4766 Second, to prevent either a @code{words} or a @code{redirects}
4767 from being empty:
4768
4769 @example
4770 sequence: /* empty */
4771 | sequence words
4772 | sequence redirects
4773 ;
4774
4775 words: word
4776 | words word
4777 ;
4778
4779 redirects:redirect
4780 | redirects redirect
4781 ;
4782 @end example
4783
4784 @node Mystery Conflicts
4785 @section Mysterious Reduce/Reduce Conflicts
4786
4787 Sometimes reduce/reduce conflicts can occur that don't look warranted.
4788 Here is an example:
4789
4790 @example
4791 @group
4792 %token ID
4793
4794 %%
4795 def: param_spec return_spec ','
4796 ;
4797 param_spec:
4798 type
4799 | name_list ':' type
4800 ;
4801 @end group
4802 @group
4803 return_spec:
4804 type
4805 | name ':' type
4806 ;
4807 @end group
4808 @group
4809 type: ID
4810 ;
4811 @end group
4812 @group
4813 name: ID
4814 ;
4815 name_list:
4816 name
4817 | name ',' name_list
4818 ;
4819 @end group
4820 @end example
4821
4822 It would seem that this grammar can be parsed with only a single token
4823 of look-ahead: when a @code{param_spec} is being read, an @code{ID} is
4824 a @code{name} if a comma or colon follows, or a @code{type} if another
4825 @code{ID} follows. In other words, this grammar is @acronym{LR}(1).
4826
4827 @cindex @acronym{LR}(1)
4828 @cindex @acronym{LALR}(1)
4829 However, Bison, like most parser generators, cannot actually handle all
4830 @acronym{LR}(1) grammars. In this grammar, two contexts, that after
4831 an @code{ID}
4832 at the beginning of a @code{param_spec} and likewise at the beginning of
4833 a @code{return_spec}, are similar enough that Bison assumes they are the
4834 same. They appear similar because the same set of rules would be
4835 active---the rule for reducing to a @code{name} and that for reducing to
4836 a @code{type}. Bison is unable to determine at that stage of processing
4837 that the rules would require different look-ahead tokens in the two
4838 contexts, so it makes a single parser state for them both. Combining
4839 the two contexts causes a conflict later. In parser terminology, this
4840 occurrence means that the grammar is not @acronym{LALR}(1).
4841
4842 In general, it is better to fix deficiencies than to document them. But
4843 this particular deficiency is intrinsically hard to fix; parser
4844 generators that can handle @acronym{LR}(1) grammars are hard to write
4845 and tend to
4846 produce parsers that are very large. In practice, Bison is more useful
4847 as it is now.
4848
4849 When the problem arises, you can often fix it by identifying the two
4850 parser states that are being confused, and adding something to make them
4851 look distinct. In the above example, adding one rule to
4852 @code{return_spec} as follows makes the problem go away:
4853
4854 @example
4855 @group
4856 %token BOGUS
4857 @dots{}
4858 %%
4859 @dots{}
4860 return_spec:
4861 type
4862 | name ':' type
4863 /* This rule is never used. */
4864 | ID BOGUS
4865 ;
4866 @end group
4867 @end example
4868
4869 This corrects the problem because it introduces the possibility of an
4870 additional active rule in the context after the @code{ID} at the beginning of
4871 @code{return_spec}. This rule is not active in the corresponding context
4872 in a @code{param_spec}, so the two contexts receive distinct parser states.
4873 As long as the token @code{BOGUS} is never generated by @code{yylex},
4874 the added rule cannot alter the way actual input is parsed.
4875
4876 In this particular example, there is another way to solve the problem:
4877 rewrite the rule for @code{return_spec} to use @code{ID} directly
4878 instead of via @code{name}. This also causes the two confusing
4879 contexts to have different sets of active rules, because the one for
4880 @code{return_spec} activates the altered rule for @code{return_spec}
4881 rather than the one for @code{name}.
4882
4883 @example
4884 param_spec:
4885 type
4886 | name_list ':' type
4887 ;
4888 return_spec:
4889 type
4890 | ID ':' type
4891 ;
4892 @end example
4893
4894 @node Generalized LR Parsing
4895 @section Generalized @acronym{LR} (@acronym{GLR}) Parsing
4896 @cindex @acronym{GLR} parsing
4897 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
4898 @cindex ambiguous grammars
4899 @cindex non-deterministic parsing
4900
4901 Bison produces @emph{deterministic} parsers that choose uniquely
4902 when to reduce and which reduction to apply
4903 based on a summary of the preceding input and on one extra token of lookahead.
4904 As a result, normal Bison handles a proper subset of the family of
4905 context-free languages.
4906 Ambiguous grammars, since they have strings with more than one possible
4907 sequence of reductions cannot have deterministic parsers in this sense.
4908 The same is true of languages that require more than one symbol of
4909 lookahead, since the parser lacks the information necessary to make a
4910 decision at the point it must be made in a shift-reduce parser.
4911 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
4912 there are languages where Bison's particular choice of how to
4913 summarize the input seen so far loses necessary information.
4914
4915 When you use the @samp{%glr-parser} declaration in your grammar file,
4916 Bison generates a parser that uses a different algorithm, called
4917 Generalized @acronym{LR} (or @acronym{GLR}). A Bison @acronym{GLR}
4918 parser uses the same basic
4919 algorithm for parsing as an ordinary Bison parser, but behaves
4920 differently in cases where there is a shift-reduce conflict that has not
4921 been resolved by precedence rules (@pxref{Precedence}) or a
4922 reduce-reduce conflict. When a @acronym{GLR} parser encounters such a
4923 situation, it
4924 effectively @emph{splits} into a several parsers, one for each possible
4925 shift or reduction. These parsers then proceed as usual, consuming
4926 tokens in lock-step. Some of the stacks may encounter other conflicts
4927 and split further, with the result that instead of a sequence of states,
4928 a Bison @acronym{GLR} parsing stack is what is in effect a tree of states.
4929
4930 In effect, each stack represents a guess as to what the proper parse
4931 is. Additional input may indicate that a guess was wrong, in which case
4932 the appropriate stack silently disappears. Otherwise, the semantics
4933 actions generated in each stack are saved, rather than being executed
4934 immediately. When a stack disappears, its saved semantic actions never
4935 get executed. When a reduction causes two stacks to become equivalent,
4936 their sets of semantic actions are both saved with the state that
4937 results from the reduction. We say that two stacks are equivalent
4938 when they both represent the same sequence of states,
4939 and each pair of corresponding states represents a
4940 grammar symbol that produces the same segment of the input token
4941 stream.
4942
4943 Whenever the parser makes a transition from having multiple
4944 states to having one, it reverts to the normal @acronym{LALR}(1) parsing
4945 algorithm, after resolving and executing the saved-up actions.
4946 At this transition, some of the states on the stack will have semantic
4947 values that are sets (actually multisets) of possible actions. The
4948 parser tries to pick one of the actions by first finding one whose rule
4949 has the highest dynamic precedence, as set by the @samp{%dprec}
4950 declaration. Otherwise, if the alternative actions are not ordered by
4951 precedence, but there the same merging function is declared for both
4952 rules by the @samp{%merge} declaration,
4953 Bison resolves and evaluates both and then calls the merge function on
4954 the result. Otherwise, it reports an ambiguity.
4955
4956 It is possible to use a data structure for the @acronym{GLR} parsing tree that
4957 permits the processing of any @acronym{LALR}(1) grammar in linear time (in the
4958 size of the input), any unambiguous (not necessarily
4959 @acronym{LALR}(1)) grammar in
4960 quadratic worst-case time, and any general (possibly ambiguous)
4961 context-free grammar in cubic worst-case time. However, Bison currently
4962 uses a simpler data structure that requires time proportional to the
4963 length of the input times the maximum number of stacks required for any
4964 prefix of the input. Thus, really ambiguous or non-deterministic
4965 grammars can require exponential time and space to process. Such badly
4966 behaving examples, however, are not generally of practical interest.
4967 Usually, non-determinism in a grammar is local---the parser is ``in
4968 doubt'' only for a few tokens at a time. Therefore, the current data
4969 structure should generally be adequate. On @acronym{LALR}(1) portions of a
4970 grammar, in particular, it is only slightly slower than with the default
4971 Bison parser.
4972
4973 @node Stack Overflow
4974 @section Stack Overflow, and How to Avoid It
4975 @cindex stack overflow
4976 @cindex parser stack overflow
4977 @cindex overflow of parser stack
4978
4979 The Bison parser stack can overflow if too many tokens are shifted and
4980 not reduced. When this happens, the parser function @code{yyparse}
4981 returns a nonzero value, pausing only to call @code{yyerror} to report
4982 the overflow.
4983
4984 Because Bison parsers have growing stacks, hitting the upper limit
4985 usually results from using a right recursion instead of a left
4986 recursion, @xref{Recursion, ,Recursive Rules}.
4987
4988 @vindex YYMAXDEPTH
4989 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
4990 parser stack can become before a stack overflow occurs. Define the
4991 macro with a value that is an integer. This value is the maximum number
4992 of tokens that can be shifted (and not reduced) before overflow.
4993 It must be a constant expression whose value is known at compile time.
4994
4995 The stack space allowed is not necessarily allocated. If you specify a
4996 large value for @code{YYMAXDEPTH}, the parser actually allocates a small
4997 stack at first, and then makes it bigger by stages as needed. This
4998 increasing allocation happens automatically and silently. Therefore,
4999 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
5000 space for ordinary inputs that do not need much stack.
5001
5002 @cindex default stack limit
5003 The default value of @code{YYMAXDEPTH}, if you do not define it, is
5004 10000.
5005
5006 @vindex YYINITDEPTH
5007 You can control how much stack is allocated initially by defining the
5008 macro @code{YYINITDEPTH}. This value too must be a compile-time
5009 constant integer. The default is 200.
5010
5011 @c FIXME: C++ output.
5012 Because of semantical differences between C and C++, the
5013 @acronym{LALR}(1) parsers
5014 in C produced by Bison by compiled as C++ cannot grow. In this precise
5015 case (compiling a C parser as C++) you are suggested to grow
5016 @code{YYINITDEPTH}. In the near future, a C++ output output will be
5017 provided which addresses this issue.
5018
5019 @node Error Recovery
5020 @chapter Error Recovery
5021 @cindex error recovery
5022 @cindex recovery from errors
5023
5024 It is not usually acceptable to have a program terminate on a parse
5025 error. For example, a compiler should recover sufficiently to parse the
5026 rest of the input file and check it for errors; a calculator should accept
5027 another expression.
5028
5029 In a simple interactive command parser where each input is one line, it may
5030 be sufficient to allow @code{yyparse} to return 1 on error and have the
5031 caller ignore the rest of the input line when that happens (and then call
5032 @code{yyparse} again). But this is inadequate for a compiler, because it
5033 forgets all the syntactic context leading up to the error. A syntax error
5034 deep within a function in the compiler input should not cause the compiler
5035 to treat the following line like the beginning of a source file.
5036
5037 @findex error
5038 You can define how to recover from a syntax error by writing rules to
5039 recognize the special token @code{error}. This is a terminal symbol that
5040 is always defined (you need not declare it) and reserved for error
5041 handling. The Bison parser generates an @code{error} token whenever a
5042 syntax error happens; if you have provided a rule to recognize this token
5043 in the current context, the parse can continue.
5044
5045 For example:
5046
5047 @example
5048 stmnts: /* empty string */
5049 | stmnts '\n'
5050 | stmnts exp '\n'
5051 | stmnts error '\n'
5052 @end example
5053
5054 The fourth rule in this example says that an error followed by a newline
5055 makes a valid addition to any @code{stmnts}.
5056
5057 What happens if a syntax error occurs in the middle of an @code{exp}? The
5058 error recovery rule, interpreted strictly, applies to the precise sequence
5059 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
5060 the middle of an @code{exp}, there will probably be some additional tokens
5061 and subexpressions on the stack after the last @code{stmnts}, and there
5062 will be tokens to read before the next newline. So the rule is not
5063 applicable in the ordinary way.
5064
5065 But Bison can force the situation to fit the rule, by discarding part of
5066 the semantic context and part of the input. First it discards states and
5067 objects from the stack until it gets back to a state in which the
5068 @code{error} token is acceptable. (This means that the subexpressions
5069 already parsed are discarded, back to the last complete @code{stmnts}.) At
5070 this point the @code{error} token can be shifted. Then, if the old
5071 look-ahead token is not acceptable to be shifted next, the parser reads
5072 tokens and discards them until it finds a token which is acceptable. In
5073 this example, Bison reads and discards input until the next newline
5074 so that the fourth rule can apply.
5075
5076 The choice of error rules in the grammar is a choice of strategies for
5077 error recovery. A simple and useful strategy is simply to skip the rest of
5078 the current input line or current statement if an error is detected:
5079
5080 @example
5081 stmnt: error ';' /* On error, skip until ';' is read. */
5082 @end example
5083
5084 It is also useful to recover to the matching close-delimiter of an
5085 opening-delimiter that has already been parsed. Otherwise the
5086 close-delimiter will probably appear to be unmatched, and generate another,
5087 spurious error message:
5088
5089 @example
5090 primary: '(' expr ')'
5091 | '(' error ')'
5092 @dots{}
5093 ;
5094 @end example
5095
5096 Error recovery strategies are necessarily guesses. When they guess wrong,
5097 one syntax error often leads to another. In the above example, the error
5098 recovery rule guesses that an error is due to bad input within one
5099 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
5100 middle of a valid @code{stmnt}. After the error recovery rule recovers
5101 from the first error, another syntax error will be found straightaway,
5102 since the text following the spurious semicolon is also an invalid
5103 @code{stmnt}.
5104
5105 To prevent an outpouring of error messages, the parser will output no error
5106 message for another syntax error that happens shortly after the first; only
5107 after three consecutive input tokens have been successfully shifted will
5108 error messages resume.
5109
5110 Note that rules which accept the @code{error} token may have actions, just
5111 as any other rules can.
5112
5113 @findex yyerrok
5114 You can make error messages resume immediately by using the macro
5115 @code{yyerrok} in an action. If you do this in the error rule's action, no
5116 error messages will be suppressed. This macro requires no arguments;
5117 @samp{yyerrok;} is a valid C statement.
5118
5119 @findex yyclearin
5120 The previous look-ahead token is reanalyzed immediately after an error. If
5121 this is unacceptable, then the macro @code{yyclearin} may be used to clear
5122 this token. Write the statement @samp{yyclearin;} in the error rule's
5123 action.
5124
5125 For example, suppose that on a parse error, an error handling routine is
5126 called that advances the input stream to some point where parsing should
5127 once again commence. The next symbol returned by the lexical scanner is
5128 probably correct. The previous look-ahead token ought to be discarded
5129 with @samp{yyclearin;}.
5130
5131 @vindex YYRECOVERING
5132 The macro @code{YYRECOVERING} stands for an expression that has the
5133 value 1 when the parser is recovering from a syntax error, and 0 the
5134 rest of the time. A value of 1 indicates that error messages are
5135 currently suppressed for new syntax errors.
5136
5137 @node Context Dependency
5138 @chapter Handling Context Dependencies
5139
5140 The Bison paradigm is to parse tokens first, then group them into larger
5141 syntactic units. In many languages, the meaning of a token is affected by
5142 its context. Although this violates the Bison paradigm, certain techniques
5143 (known as @dfn{kludges}) may enable you to write Bison parsers for such
5144 languages.
5145
5146 @menu
5147 * Semantic Tokens:: Token parsing can depend on the semantic context.
5148 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
5149 * Tie-in Recovery:: Lexical tie-ins have implications for how
5150 error recovery rules must be written.
5151 @end menu
5152
5153 (Actually, ``kludge'' means any technique that gets its job done but is
5154 neither clean nor robust.)
5155
5156 @node Semantic Tokens
5157 @section Semantic Info in Token Types
5158
5159 The C language has a context dependency: the way an identifier is used
5160 depends on what its current meaning is. For example, consider this:
5161
5162 @example
5163 foo (x);
5164 @end example
5165
5166 This looks like a function call statement, but if @code{foo} is a typedef
5167 name, then this is actually a declaration of @code{x}. How can a Bison
5168 parser for C decide how to parse this input?
5169
5170 The method used in @acronym{GNU} C is to have two different token types,
5171 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
5172 identifier, it looks up the current declaration of the identifier in order
5173 to decide which token type to return: @code{TYPENAME} if the identifier is
5174 declared as a typedef, @code{IDENTIFIER} otherwise.
5175
5176 The grammar rules can then express the context dependency by the choice of
5177 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
5178 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
5179 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
5180 is @emph{not} significant, such as in declarations that can shadow a
5181 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
5182 accepted---there is one rule for each of the two token types.
5183
5184 This technique is simple to use if the decision of which kinds of
5185 identifiers to allow is made at a place close to where the identifier is
5186 parsed. But in C this is not always so: C allows a declaration to
5187 redeclare a typedef name provided an explicit type has been specified
5188 earlier:
5189
5190 @example
5191 typedef int foo, bar, lose;
5192 static foo (bar); /* @r{redeclare @code{bar} as static variable} */
5193 static int foo (lose); /* @r{redeclare @code{foo} as function} */
5194 @end example
5195
5196 Unfortunately, the name being declared is separated from the declaration
5197 construct itself by a complicated syntactic structure---the ``declarator''.
5198
5199 As a result, part of the Bison parser for C needs to be duplicated, with
5200 all the nonterminal names changed: once for parsing a declaration in
5201 which a typedef name can be redefined, and once for parsing a
5202 declaration in which that can't be done. Here is a part of the
5203 duplication, with actions omitted for brevity:
5204
5205 @example
5206 initdcl:
5207 declarator maybeasm '='
5208 init
5209 | declarator maybeasm
5210 ;
5211
5212 notype_initdcl:
5213 notype_declarator maybeasm '='
5214 init
5215 | notype_declarator maybeasm
5216 ;
5217 @end example
5218
5219 @noindent
5220 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
5221 cannot. The distinction between @code{declarator} and
5222 @code{notype_declarator} is the same sort of thing.
5223
5224 There is some similarity between this technique and a lexical tie-in
5225 (described next), in that information which alters the lexical analysis is
5226 changed during parsing by other parts of the program. The difference is
5227 here the information is global, and is used for other purposes in the
5228 program. A true lexical tie-in has a special-purpose flag controlled by
5229 the syntactic context.
5230
5231 @node Lexical Tie-ins
5232 @section Lexical Tie-ins
5233 @cindex lexical tie-in
5234
5235 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
5236 which is set by Bison actions, whose purpose is to alter the way tokens are
5237 parsed.
5238
5239 For example, suppose we have a language vaguely like C, but with a special
5240 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
5241 an expression in parentheses in which all integers are hexadecimal. In
5242 particular, the token @samp{a1b} must be treated as an integer rather than
5243 as an identifier if it appears in that context. Here is how you can do it:
5244
5245 @example
5246 @group
5247 %@{
5248 int hexflag;
5249 %@}
5250 %%
5251 @dots{}
5252 @end group
5253 @group
5254 expr: IDENTIFIER
5255 | constant
5256 | HEX '('
5257 @{ hexflag = 1; @}
5258 expr ')'
5259 @{ hexflag = 0;
5260 $$ = $4; @}
5261 | expr '+' expr
5262 @{ $$ = make_sum ($1, $3); @}
5263 @dots{}
5264 ;
5265 @end group
5266
5267 @group
5268 constant:
5269 INTEGER
5270 | STRING
5271 ;
5272 @end group
5273 @end example
5274
5275 @noindent
5276 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
5277 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
5278 with letters are parsed as integers if possible.
5279
5280 The declaration of @code{hexflag} shown in the prologue of the parser file
5281 is needed to make it accessible to the actions (@pxref{Prologue, ,The Prologue}).
5282 You must also write the code in @code{yylex} to obey the flag.
5283
5284 @node Tie-in Recovery
5285 @section Lexical Tie-ins and Error Recovery
5286
5287 Lexical tie-ins make strict demands on any error recovery rules you have.
5288 @xref{Error Recovery}.
5289
5290 The reason for this is that the purpose of an error recovery rule is to
5291 abort the parsing of one construct and resume in some larger construct.
5292 For example, in C-like languages, a typical error recovery rule is to skip
5293 tokens until the next semicolon, and then start a new statement, like this:
5294
5295 @example
5296 stmt: expr ';'
5297 | IF '(' expr ')' stmt @{ @dots{} @}
5298 @dots{}
5299 error ';'
5300 @{ hexflag = 0; @}
5301 ;
5302 @end example
5303
5304 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
5305 construct, this error rule will apply, and then the action for the
5306 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
5307 remain set for the entire rest of the input, or until the next @code{hex}
5308 keyword, causing identifiers to be misinterpreted as integers.
5309
5310 To avoid this problem the error recovery rule itself clears @code{hexflag}.
5311
5312 There may also be an error recovery rule that works within expressions.
5313 For example, there could be a rule which applies within parentheses
5314 and skips to the close-parenthesis:
5315
5316 @example
5317 @group
5318 expr: @dots{}
5319 | '(' expr ')'
5320 @{ $$ = $2; @}
5321 | '(' error ')'
5322 @dots{}
5323 @end group
5324 @end example
5325
5326 If this rule acts within the @code{hex} construct, it is not going to abort
5327 that construct (since it applies to an inner level of parentheses within
5328 the construct). Therefore, it should not clear the flag: the rest of
5329 the @code{hex} construct should be parsed with the flag still in effect.
5330
5331 What if there is an error recovery rule which might abort out of the
5332 @code{hex} construct or might not, depending on circumstances? There is no
5333 way you can write the action to determine whether a @code{hex} construct is
5334 being aborted or not. So if you are using a lexical tie-in, you had better
5335 make sure your error recovery rules are not of this kind. Each rule must
5336 be such that you can be sure that it always will, or always won't, have to
5337 clear the flag.
5338
5339 @c ================================================== Debugging Your Parser
5340
5341 @node Debugging
5342 @chapter Debugging Your Parser
5343
5344 Developing a parser can be a challenge, especially if you don't
5345 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
5346 Algorithm}). Even so, sometimes a detailed description of the automaton
5347 can help (@pxref{Understanding, , Understanding Your Parser}), or
5348 tracing the execution of the parser can give some insight on why it
5349 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
5350
5351 @menu
5352 * Understanding:: Understanding the structure of your parser.
5353 * Tracing:: Tracing the execution of your parser.
5354 @end menu
5355
5356 @node Understanding
5357 @section Understanding Your Parser
5358
5359 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
5360 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
5361 frequent than one would hope), looking at this automaton is required to
5362 tune or simply fix a parser. Bison provides two different
5363 representation of it, either textually or graphically (as a @acronym{VCG}
5364 file).
5365
5366 The textual file is generated when the options @option{--report} or
5367 @option{--verbose} are specified, see @xref{Invocation, , Invoking
5368 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
5369 the parser output file name, and adding @samp{.output} instead.
5370 Therefore, if the input file is @file{foo.y}, then the parser file is
5371 called @file{foo.tab.c} by default. As a consequence, the verbose
5372 output file is called @file{foo.output}.
5373
5374 The following grammar file, @file{calc.y}, will be used in the sequel:
5375
5376 @example
5377 %token NUM STR
5378 %left '+' '-'
5379 %left '*'
5380 %%
5381 exp: exp '+' exp
5382 | exp '-' exp
5383 | exp '*' exp
5384 | exp '/' exp
5385 | NUM
5386 ;
5387 useless: STR;
5388 %%
5389 @end example
5390
5391 @command{bison} reports:
5392
5393 @example
5394 calc.y: warning: 1 useless nonterminal and 1 useless rule
5395 calc.y:11.1-7: warning: useless nonterminal: useless
5396 calc.y:11.8-12: warning: useless rule: useless: STR
5397 calc.y contains 7 shift/reduce conflicts.
5398 @end example
5399
5400 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
5401 creates a file @file{calc.output} with contents detailed below. The
5402 order of the output and the exact presentation might vary, but the
5403 interpretation is the same.
5404
5405 The first section includes details on conflicts that were solved thanks
5406 to precedence and/or associativity:
5407
5408 @example
5409 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
5410 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
5411 Conflict in state 8 between rule 2 and token '*' resolved as shift.
5412 @exdent @dots{}
5413 @end example
5414
5415 @noindent
5416 The next section lists states that still have conflicts.
5417
5418 @example
5419 State 8 contains 1 shift/reduce conflict.
5420 State 9 contains 1 shift/reduce conflict.
5421 State 10 contains 1 shift/reduce conflict.
5422 State 11 contains 4 shift/reduce conflicts.
5423 @end example
5424
5425 @noindent
5426 @cindex token, useless
5427 @cindex useless token
5428 @cindex nonterminal, useless
5429 @cindex useless nonterminal
5430 @cindex rule, useless
5431 @cindex useless rule
5432 The next section reports useless tokens, nonterminal and rules. Useless
5433 nonterminals and rules are removed in order to produce a smaller parser,
5434 but useless tokens are preserved, since they might be used by the
5435 scanner (note the difference between ``useless'' and ``not used''
5436 below):
5437
5438 @example
5439 Useless nonterminals:
5440 useless
5441
5442 Terminals which are not used:
5443 STR
5444
5445 Useless rules:
5446 #6 useless: STR;
5447 @end example
5448
5449 @noindent
5450 The next section reproduces the exact grammar that Bison used:
5451
5452 @example
5453 Grammar
5454
5455 Number, Line, Rule
5456 0 5 $accept -> exp $end
5457 1 5 exp -> exp '+' exp
5458 2 6 exp -> exp '-' exp
5459 3 7 exp -> exp '*' exp
5460 4 8 exp -> exp '/' exp
5461 5 9 exp -> NUM
5462 @end example
5463
5464 @noindent
5465 and reports the uses of the symbols:
5466
5467 @example
5468 Terminals, with rules where they appear
5469
5470 $end (0) 0
5471 '*' (42) 3
5472 '+' (43) 1
5473 '-' (45) 2
5474 '/' (47) 4
5475 error (256)
5476 NUM (258) 5
5477
5478 Nonterminals, with rules where they appear
5479
5480 $accept (8)
5481 on left: 0
5482 exp (9)
5483 on left: 1 2 3 4 5, on right: 0 1 2 3 4
5484 @end example
5485
5486 @noindent
5487 @cindex item
5488 @cindex pointed rule
5489 @cindex rule, pointed
5490 Bison then proceeds onto the automaton itself, describing each state
5491 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
5492 item is a production rule together with a point (marked by @samp{.})
5493 that the input cursor.
5494
5495 @example
5496 state 0
5497
5498 $accept -> . exp $ (rule 0)
5499
5500 NUM shift, and go to state 1
5501
5502 exp go to state 2
5503 @end example
5504
5505 This reads as follows: ``state 0 corresponds to being at the very
5506 beginning of the parsing, in the initial rule, right before the start
5507 symbol (here, @code{exp}). When the parser returns to this state right
5508 after having reduced a rule that produced an @code{exp}, the control
5509 flow jumps to state 2. If there is no such transition on a nonterminal
5510 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
5511 the parse stack, and the control flow jumps to state 1. Any other
5512 lookahead triggers a parse error.''
5513
5514 @cindex core, item set
5515 @cindex item set core
5516 @cindex kernel, item set
5517 @cindex item set core
5518 Even though the only active rule in state 0 seems to be rule 0, the
5519 report lists @code{NUM} as a lookahead symbol because @code{NUM} can be
5520 at the beginning of any rule deriving an @code{exp}. By default Bison
5521 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
5522 you want to see more detail you can invoke @command{bison} with
5523 @option{--report=itemset} to list all the items, include those that can
5524 be derived:
5525
5526 @example
5527 state 0
5528
5529 $accept -> . exp $ (rule 0)
5530 exp -> . exp '+' exp (rule 1)
5531 exp -> . exp '-' exp (rule 2)
5532 exp -> . exp '*' exp (rule 3)
5533 exp -> . exp '/' exp (rule 4)
5534 exp -> . NUM (rule 5)
5535
5536 NUM shift, and go to state 1
5537
5538 exp go to state 2
5539 @end example
5540
5541 @noindent
5542 In the state 1...
5543
5544 @example
5545 state 1
5546
5547 exp -> NUM . (rule 5)
5548
5549 $default reduce using rule 5 (exp)
5550 @end example
5551
5552 @noindent
5553 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead
5554 (@samp{$default}), the parser will reduce it. If it was coming from
5555 state 0, then, after this reduction it will return to state 0, and will
5556 jump to state 2 (@samp{exp: go to state 2}).
5557
5558 @example
5559 state 2
5560
5561 $accept -> exp . $ (rule 0)
5562 exp -> exp . '+' exp (rule 1)
5563 exp -> exp . '-' exp (rule 2)
5564 exp -> exp . '*' exp (rule 3)
5565 exp -> exp . '/' exp (rule 4)
5566
5567 $ shift, and go to state 3
5568 '+' shift, and go to state 4
5569 '-' shift, and go to state 5
5570 '*' shift, and go to state 6
5571 '/' shift, and go to state 7
5572 @end example
5573
5574 @noindent
5575 In state 2, the automaton can only shift a symbol. For instance,
5576 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
5577 @samp{+}, it will be shifted on the parse stack, and the automaton
5578 control will jump to state 4, corresponding to the item @samp{exp -> exp
5579 '+' . exp}. Since there is no default action, any other token than
5580 those listed above will trigger a parse error.
5581
5582 The state 3 is named the @dfn{final state}, or the @dfn{accepting
5583 state}:
5584
5585 @example
5586 state 3
5587
5588 $accept -> exp $ . (rule 0)
5589
5590 $default accept
5591 @end example
5592
5593 @noindent
5594 the initial rule is completed (the start symbol and the end
5595 of input were read), the parsing exits successfully.
5596
5597 The interpretation of states 4 to 7 is straightforward, and is left to
5598 the reader.
5599
5600 @example
5601 state 4
5602
5603 exp -> exp '+' . exp (rule 1)
5604
5605 NUM shift, and go to state 1
5606
5607 exp go to state 8
5608
5609 state 5
5610
5611 exp -> exp '-' . exp (rule 2)
5612
5613 NUM shift, and go to state 1
5614
5615 exp go to state 9
5616
5617 state 6
5618
5619 exp -> exp '*' . exp (rule 3)
5620
5621 NUM shift, and go to state 1
5622
5623 exp go to state 10
5624
5625 state 7
5626
5627 exp -> exp '/' . exp (rule 4)
5628
5629 NUM shift, and go to state 1
5630
5631 exp go to state 11
5632 @end example
5633
5634 As was announced in beginning of the report, @samp{State 8 contains 1
5635 shift/reduce conflict}:
5636
5637 @example
5638 state 8
5639
5640 exp -> exp . '+' exp (rule 1)
5641 exp -> exp '+' exp . (rule 1)
5642 exp -> exp . '-' exp (rule 2)
5643 exp -> exp . '*' exp (rule 3)
5644 exp -> exp . '/' exp (rule 4)
5645
5646 '*' shift, and go to state 6
5647 '/' shift, and go to state 7
5648
5649 '/' [reduce using rule 1 (exp)]
5650 $default reduce using rule 1 (exp)
5651 @end example
5652
5653 Indeed, there are two actions associated to the lookahead @samp{/}:
5654 either shifting (and going to state 7), or reducing rule 1. The
5655 conflict means that either the grammar is ambiguous, or the parser lacks
5656 information to make the right decision. Indeed the grammar is
5657 ambiguous, as, since we did not specify the precedence of @samp{/}, the
5658 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
5659 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
5660 NUM}, which corresponds to reducing rule 1.
5661
5662 Because in @acronym{LALR}(1) parsing a single decision can be made, Bison
5663 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
5664 Shift/Reduce Conflicts}. Discarded actions are reported in between
5665 square brackets.
5666
5667 Note that all the previous states had a single possible action: either
5668 shifting the next token and going to the corresponding state, or
5669 reducing a single rule. In the other cases, i.e., when shifting
5670 @emph{and} reducing is possible or when @emph{several} reductions are
5671 possible, the lookahead is required to select the action. State 8 is
5672 one such state: if the lookahead is @samp{*} or @samp{/} then the action
5673 is shifting, otherwise the action is reducing rule 1. In other words,
5674 the first two items, corresponding to rule 1, are not eligible when the
5675 lookahead is @samp{*}, since we specified that @samp{*} has higher
5676 precedence that @samp{+}. More generally, some items are eligible only
5677 with some set of possible lookaheads. When run with
5678 @option{--report=lookahead}, Bison specifies these lookaheads:
5679
5680 @example
5681 state 8
5682
5683 exp -> exp . '+' exp [$, '+', '-', '/'] (rule 1)
5684 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
5685 exp -> exp . '-' exp (rule 2)
5686 exp -> exp . '*' exp (rule 3)
5687 exp -> exp . '/' exp (rule 4)
5688
5689 '*' shift, and go to state 6
5690 '/' shift, and go to state 7
5691
5692 '/' [reduce using rule 1 (exp)]
5693 $default reduce using rule 1 (exp)
5694 @end example
5695
5696 The remaining states are similar:
5697
5698 @example
5699 state 9
5700
5701 exp -> exp . '+' exp (rule 1)
5702 exp -> exp . '-' exp (rule 2)
5703 exp -> exp '-' exp . (rule 2)
5704 exp -> exp . '*' exp (rule 3)
5705 exp -> exp . '/' exp (rule 4)
5706
5707 '*' shift, and go to state 6
5708 '/' shift, and go to state 7
5709
5710 '/' [reduce using rule 2 (exp)]
5711 $default reduce using rule 2 (exp)
5712
5713 state 10
5714
5715 exp -> exp . '+' exp (rule 1)
5716 exp -> exp . '-' exp (rule 2)
5717 exp -> exp . '*' exp (rule 3)
5718 exp -> exp '*' exp . (rule 3)
5719 exp -> exp . '/' exp (rule 4)
5720
5721 '/' shift, and go to state 7
5722
5723 '/' [reduce using rule 3 (exp)]
5724 $default reduce using rule 3 (exp)
5725
5726 state 11
5727
5728 exp -> exp . '+' exp (rule 1)
5729 exp -> exp . '-' exp (rule 2)
5730 exp -> exp . '*' exp (rule 3)
5731 exp -> exp . '/' exp (rule 4)
5732 exp -> exp '/' exp . (rule 4)
5733
5734 '+' shift, and go to state 4
5735 '-' shift, and go to state 5
5736 '*' shift, and go to state 6
5737 '/' shift, and go to state 7
5738
5739 '+' [reduce using rule 4 (exp)]
5740 '-' [reduce using rule 4 (exp)]
5741 '*' [reduce using rule 4 (exp)]
5742 '/' [reduce using rule 4 (exp)]
5743 $default reduce using rule 4 (exp)
5744 @end example
5745
5746 @noindent
5747 Observe that state 11 contains conflicts due to the lack of precedence
5748 of @samp{/} wrt @samp{+}, @samp{-}, and @samp{*}, but also because the
5749 associativity of @samp{/} is not specified.
5750
5751
5752 @node Tracing
5753 @section Tracing Your Parser
5754 @findex yydebug
5755 @cindex debugging
5756 @cindex tracing the parser
5757
5758 If a Bison grammar compiles properly but doesn't do what you want when it
5759 runs, the @code{yydebug} parser-trace feature can help you figure out why.
5760
5761 There are several means to enable compilation of trace facilities:
5762
5763 @table @asis
5764 @item the macro @code{YYDEBUG}
5765 @findex YYDEBUG
5766 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
5767 parser. This is compliant with @acronym{POSIX} Yacc. You could use
5768 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
5769 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
5770 Prologue}).
5771
5772 @item the option @option{-t}, @option{--debug}
5773 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
5774 ,Invoking Bison}). This is @acronym{POSIX} compliant too.
5775
5776 @item the directive @samp{%debug}
5777 @findex %debug
5778 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison
5779 Declaration Summary}). This is a Bison extension, which will prove
5780 useful when Bison will output parsers for languages that don't use a
5781 preprocessor. Unless @acronym{POSIX} and Yacc portability matter to
5782 you, this is
5783 the preferred solution.
5784 @end table
5785
5786 We suggest that you always enable the debug option so that debugging is
5787 always possible.
5788
5789 The trace facility outputs messages with macro calls of the form
5790 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
5791 @var{format} and @var{args} are the usual @code{printf} format and
5792 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
5793 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
5794 and @code{YYPRINTF} is defined to @code{fprintf}.
5795
5796 Once you have compiled the program with trace facilities, the way to
5797 request a trace is to store a nonzero value in the variable @code{yydebug}.
5798 You can do this by making the C code do it (in @code{main}, perhaps), or
5799 you can alter the value with a C debugger.
5800
5801 Each step taken by the parser when @code{yydebug} is nonzero produces a
5802 line or two of trace information, written on @code{stderr}. The trace
5803 messages tell you these things:
5804
5805 @itemize @bullet
5806 @item
5807 Each time the parser calls @code{yylex}, what kind of token was read.
5808
5809 @item
5810 Each time a token is shifted, the depth and complete contents of the
5811 state stack (@pxref{Parser States}).
5812
5813 @item
5814 Each time a rule is reduced, which rule it is, and the complete contents
5815 of the state stack afterward.
5816 @end itemize
5817
5818 To make sense of this information, it helps to refer to the listing file
5819 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
5820 Bison}). This file shows the meaning of each state in terms of
5821 positions in various rules, and also what each state will do with each
5822 possible input token. As you read the successive trace messages, you
5823 can see that the parser is functioning according to its specification in
5824 the listing file. Eventually you will arrive at the place where
5825 something undesirable happens, and you will see which parts of the
5826 grammar are to blame.
5827
5828 The parser file is a C program and you can use C debuggers on it, but it's
5829 not easy to interpret what it is doing. The parser function is a
5830 finite-state machine interpreter, and aside from the actions it executes
5831 the same code over and over. Only the values of variables show where in
5832 the grammar it is working.
5833
5834 @findex YYPRINT
5835 The debugging information normally gives the token type of each token
5836 read, but not its semantic value. You can optionally define a macro
5837 named @code{YYPRINT} to provide a way to print the value. If you define
5838 @code{YYPRINT}, it should take three arguments. The parser will pass a
5839 standard I/O stream, the numeric code for the token type, and the token
5840 value (from @code{yylval}).
5841
5842 Here is an example of @code{YYPRINT} suitable for the multi-function
5843 calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
5844
5845 @smallexample
5846 #define YYPRINT(file, type, value) yyprint (file, type, value)
5847
5848 static void
5849 yyprint (FILE *file, int type, YYSTYPE value)
5850 @{
5851 if (type == VAR)
5852 fprintf (file, " %s", value.tptr->name);
5853 else if (type == NUM)
5854 fprintf (file, " %d", value.val);
5855 @}
5856 @end smallexample
5857
5858 @c ================================================= Invoking Bison
5859
5860 @node Invocation
5861 @chapter Invoking Bison
5862 @cindex invoking Bison
5863 @cindex Bison invocation
5864 @cindex options for invoking Bison
5865
5866 The usual way to invoke Bison is as follows:
5867
5868 @example
5869 bison @var{infile}
5870 @end example
5871
5872 Here @var{infile} is the grammar file name, which usually ends in
5873 @samp{.y}. The parser file's name is made by replacing the @samp{.y}
5874 with @samp{.tab.c}. Thus, the @samp{bison foo.y} filename yields
5875 @file{foo.tab.c}, and the @samp{bison hack/foo.y} filename yields
5876 @file{hack/foo.tab.c}. It's also possible, in case you are writing
5877 C++ code instead of C in your grammar file, to name it @file{foo.ypp}
5878 or @file{foo.y++}. Then, the output files will take an extension like
5879 the given one as input (respectively @file{foo.tab.cpp} and
5880 @file{foo.tab.c++}).
5881 This feature takes effect with all options that manipulate filenames like
5882 @samp{-o} or @samp{-d}.
5883
5884 For example :
5885
5886 @example
5887 bison -d @var{infile.yxx}
5888 @end example
5889 @noindent
5890 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
5891
5892 @example
5893 bison -d -o @var{output.c++} @var{infile.y}
5894 @end example
5895 @noindent
5896 will produce @file{output.c++} and @file{outfile.h++}.
5897
5898 @menu
5899 * Bison Options:: All the options described in detail,
5900 in alphabetical order by short options.
5901 * Option Cross Key:: Alphabetical list of long options.
5902 * VMS Invocation:: Bison command syntax on @acronym{VMS}.
5903 @end menu
5904
5905 @node Bison Options
5906 @section Bison Options
5907
5908 Bison supports both traditional single-letter options and mnemonic long
5909 option names. Long option names are indicated with @samp{--} instead of
5910 @samp{-}. Abbreviations for option names are allowed as long as they
5911 are unique. When a long option takes an argument, like
5912 @samp{--file-prefix}, connect the option name and the argument with
5913 @samp{=}.
5914
5915 Here is a list of options that can be used with Bison, alphabetized by
5916 short option. It is followed by a cross key alphabetized by long
5917 option.
5918
5919 @c Please, keep this ordered as in `bison --help'.
5920 @noindent
5921 Operations modes:
5922 @table @option
5923 @item -h
5924 @itemx --help
5925 Print a summary of the command-line options to Bison and exit.
5926
5927 @item -V
5928 @itemx --version
5929 Print the version number of Bison and exit.
5930
5931 @need 1750
5932 @item -y
5933 @itemx --yacc
5934 Equivalent to @samp{-o y.tab.c}; the parser output file is called
5935 @file{y.tab.c}, and the other outputs are called @file{y.output} and
5936 @file{y.tab.h}. The purpose of this option is to imitate Yacc's output
5937 file name conventions. Thus, the following shell script can substitute
5938 for Yacc:
5939
5940 @example
5941 bison -y $*
5942 @end example
5943 @end table
5944
5945 @noindent
5946 Tuning the parser:
5947
5948 @table @option
5949 @item -S @var{file}
5950 @itemx --skeleton=@var{file}
5951 Specify the skeleton to use. You probably don't need this option unless
5952 you are developing Bison.
5953
5954 @item -t
5955 @itemx --debug
5956 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
5957 already defined, so that the debugging facilities are compiled.
5958 @xref{Tracing, ,Tracing Your Parser}.
5959
5960 @item --locations
5961 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
5962
5963 @item -p @var{prefix}
5964 @itemx --name-prefix=@var{prefix}
5965 Pretend that @code{%name-prefix="@var{prefix}"} was specified.
5966 @xref{Decl Summary}.
5967
5968 @item -l
5969 @itemx --no-lines
5970 Don't put any @code{#line} preprocessor commands in the parser file.
5971 Ordinarily Bison puts them in the parser file so that the C compiler
5972 and debuggers will associate errors with your source file, the
5973 grammar file. This option causes them to associate errors with the
5974 parser file, treating it as an independent source file in its own right.
5975
5976 @item -n
5977 @itemx --no-parser
5978 Pretend that @code{%no-parser} was specified. @xref{Decl Summary}.
5979
5980 @item -k
5981 @itemx --token-table
5982 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
5983 @end table
5984
5985 @noindent
5986 Adjust the output:
5987
5988 @table @option
5989 @item -d
5990 @itemx --defines
5991 Pretend that @code{%defines} was specified, i.e., write an extra output
5992 file containing macro definitions for the token type names defined in
5993 the grammar and the semantic value type @code{YYSTYPE}, as well as a few
5994 @code{extern} variable declarations. @xref{Decl Summary}.
5995
5996 @item --defines=@var{defines-file}
5997 Same as above, but save in the file @var{defines-file}.
5998
5999 @item -b @var{file-prefix}
6000 @itemx --file-prefix=@var{prefix}
6001 Pretend that @code{%verbose} was specified, i.e, specify prefix to use
6002 for all Bison output file names. @xref{Decl Summary}.
6003
6004 @item -r @var{things}
6005 @itemx --report=@var{things}
6006 Write an extra output file containing verbose description of the comma
6007 separated list of @var{things} among:
6008
6009 @table @code
6010 @item state
6011 Description of the grammar, conflicts (resolved and unresolved), and
6012 @acronym{LALR} automaton.
6013
6014 @item lookahead
6015 Implies @code{state} and augments the description of the automaton with
6016 each rule's lookahead set.
6017
6018 @item itemset
6019 Implies @code{state} and augments the description of the automaton with
6020 the full set of items for each state, instead of its core only.
6021 @end table
6022
6023 For instance, on the following grammar
6024
6025 @item -v
6026 @itemx --verbose
6027 Pretend that @code{%verbose} was specified, i.e, write an extra output
6028 file containing verbose descriptions of the grammar and
6029 parser. @xref{Decl Summary}.
6030
6031 @item -o @var{filename}
6032 @itemx --output=@var{filename}
6033 Specify the @var{filename} for the parser file.
6034
6035 The other output files' names are constructed from @var{filename} as
6036 described under the @samp{-v} and @samp{-d} options.
6037
6038 @item -g
6039 Output a @acronym{VCG} definition of the @acronym{LALR}(1) grammar
6040 automaton computed by Bison. If the grammar file is @file{foo.y}, the
6041 @acronym{VCG} output file will
6042 be @file{foo.vcg}.
6043
6044 @item --graph=@var{graph-file}
6045 The behavior of @var{--graph} is the same than @samp{-g}. The only
6046 difference is that it has an optional argument which is the name of
6047 the output graph filename.
6048 @end table
6049
6050 @node Option Cross Key
6051 @section Option Cross Key
6052
6053 Here is a list of options, alphabetized by long option, to help you find
6054 the corresponding short option.
6055
6056 @tex
6057 \def\leaderfill{\leaders\hbox to 1em{\hss.\hss}\hfill}
6058
6059 {\tt
6060 \line{ --debug \leaderfill -t}
6061 \line{ --defines \leaderfill -d}
6062 \line{ --file-prefix \leaderfill -b}
6063 \line{ --graph \leaderfill -g}
6064 \line{ --help \leaderfill -h}
6065 \line{ --name-prefix \leaderfill -p}
6066 \line{ --no-lines \leaderfill -l}
6067 \line{ --no-parser \leaderfill -n}
6068 \line{ --output \leaderfill -o}
6069 \line{ --token-table \leaderfill -k}
6070 \line{ --verbose \leaderfill -v}
6071 \line{ --version \leaderfill -V}
6072 \line{ --yacc \leaderfill -y}
6073 }
6074 @end tex
6075
6076 @ifinfo
6077 @example
6078 --debug -t
6079 --defines=@var{defines-file} -d
6080 --file-prefix=@var{prefix} -b @var{file-prefix}
6081 --graph=@var{graph-file} -d
6082 --help -h
6083 --name-prefix=@var{prefix} -p @var{name-prefix}
6084 --no-lines -l
6085 --no-parser -n
6086 --output=@var{outfile} -o @var{outfile}
6087 --token-table -k
6088 --verbose -v
6089 --version -V
6090 --yacc -y
6091 @end example
6092 @end ifinfo
6093
6094 @node VMS Invocation
6095 @section Invoking Bison under @acronym{VMS}
6096 @cindex invoking Bison under @acronym{VMS}
6097 @cindex @acronym{VMS}
6098
6099 The command line syntax for Bison on @acronym{VMS} is a variant of the usual
6100 Bison command syntax---adapted to fit @acronym{VMS} conventions.
6101
6102 To find the @acronym{VMS} equivalent for any Bison option, start with the long
6103 option, and substitute a @samp{/} for the leading @samp{--}, and
6104 substitute a @samp{_} for each @samp{-} in the name of the long option.
6105 For example, the following invocation under @acronym{VMS}:
6106
6107 @example
6108 bison /debug/name_prefix=bar foo.y
6109 @end example
6110
6111 @noindent
6112 is equivalent to the following command under @acronym{POSIX}.
6113
6114 @example
6115 bison --debug --name-prefix=bar foo.y
6116 @end example
6117
6118 The @acronym{VMS} file system does not permit filenames such as
6119 @file{foo.tab.c}. In the above example, the output file
6120 would instead be named @file{foo_tab.c}.
6121
6122 @c ================================================= Invoking Bison
6123
6124 @node FAQ
6125 @chapter Frequently Asked Questions
6126 @cindex frequently asked questions
6127 @cindex questions
6128
6129 Several questions about Bison come up occasionally. Here some of them
6130 are addressed.
6131
6132 @menu
6133 * Parser Stack Overflow:: Breaking the Stack Limits
6134 @end menu
6135
6136 @node Parser Stack Overflow
6137 @section Parser Stack Overflow
6138
6139 @display
6140 My parser returns with error with a @samp{parser stack overflow}
6141 message. What can I do?
6142 @end display
6143
6144 This question is already addressed elsewhere, @xref{Recursion,
6145 ,Recursive Rules}.
6146
6147 @c ================================================= Table of Symbols
6148
6149 @node Table of Symbols
6150 @appendix Bison Symbols
6151 @cindex Bison symbols, table of
6152 @cindex symbols in Bison, table of
6153
6154 @table @code
6155 @item @@$
6156 In an action, the location of the left-hand side of the rule.
6157 @xref{Locations, , Locations Overview}.
6158
6159 @item @@@var{n}
6160 In an action, the location of the @var{n}-th symbol of the right-hand
6161 side of the rule. @xref{Locations, , Locations Overview}.
6162
6163 @item $$
6164 In an action, the semantic value of the left-hand side of the rule.
6165 @xref{Actions}.
6166
6167 @item $@var{n}
6168 In an action, the semantic value of the @var{n}-th symbol of the
6169 right-hand side of the rule. @xref{Actions}.
6170
6171 @item $accept
6172 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
6173 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
6174 Start-Symbol}. It cannot be used in the grammar.
6175
6176 @item $end
6177 The predefined token marking the end of the token stream. It cannot be
6178 used in the grammar.
6179
6180 @item $undefined
6181 The predefined token onto which all undefined values returned by
6182 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
6183 @code{error}.
6184
6185 @item error
6186 A token name reserved for error recovery. This token may be used in
6187 grammar rules so as to allow the Bison parser to recognize an error in
6188 the grammar without halting the process. In effect, a sentence
6189 containing an error may be recognized as valid. On a parse error, the
6190 token @code{error} becomes the current look-ahead token. Actions
6191 corresponding to @code{error} are then executed, and the look-ahead
6192 token is reset to the token that originally caused the violation.
6193 @xref{Error Recovery}.
6194
6195 @item YYABORT
6196 Macro to pretend that an unrecoverable syntax error has occurred, by
6197 making @code{yyparse} return 1 immediately. The error reporting
6198 function @code{yyerror} is not called. @xref{Parser Function, ,The
6199 Parser Function @code{yyparse}}.
6200
6201 @item YYACCEPT
6202 Macro to pretend that a complete utterance of the language has been
6203 read, by making @code{yyparse} return 0 immediately.
6204 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6205
6206 @item YYBACKUP
6207 Macro to discard a value from the parser stack and fake a look-ahead
6208 token. @xref{Action Features, ,Special Features for Use in Actions}.
6209
6210 @item YYDEBUG
6211 Macro to define to equip the parser with tracing code. @xref{Tracing,
6212 ,Tracing Your Parser}.
6213
6214 @item YYERROR
6215 Macro to pretend that a syntax error has just been detected: call
6216 @code{yyerror} and then perform normal error recovery if possible
6217 (@pxref{Error Recovery}), or (if recovery is impossible) make
6218 @code{yyparse} return 1. @xref{Error Recovery}.
6219
6220 @item YYERROR_VERBOSE
6221 An obsolete macro that you define with @code{#define} in the Bison
6222 declarations section to request verbose, specific error message strings
6223 when @code{yyerror} is called. It doesn't matter what definition you
6224 use for @code{YYERROR_VERBOSE}, just whether you define it. Using
6225 @code{%error-verbose} is preferred.
6226
6227 @item YYINITDEPTH
6228 Macro for specifying the initial size of the parser stack.
6229 @xref{Stack Overflow}.
6230
6231 @item YYLEX_PARAM
6232 An obsolete macro for specifying an extra argument (or list of extra
6233 arguments) for @code{yyparse} to pass to @code{yylex}. he use of this
6234 macro is deprecated, and is supported only for Yacc like parsers.
6235 @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
6236
6237 @item YYLTYPE
6238 Macro for the data type of @code{yylloc}; a structure with four
6239 members. @xref{Location Type, , Data Types of Locations}.
6240
6241 @item yyltype
6242 Default value for YYLTYPE.
6243
6244 @item YYMAXDEPTH
6245 Macro for specifying the maximum size of the parser stack.
6246 @xref{Stack Overflow}.
6247
6248 @item YYPARSE_PARAM
6249 An obsolete macro for specifying the name of a parameter that
6250 @code{yyparse} should accept. The use of this macro is deprecated, and
6251 is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
6252 Conventions for Pure Parsers}.
6253
6254 @item YYRECOVERING
6255 Macro whose value indicates whether the parser is recovering from a
6256 syntax error. @xref{Action Features, ,Special Features for Use in Actions}.
6257
6258 @item YYSTACK_USE_ALLOCA
6259 Macro used to control the use of @code{alloca}. If defined to @samp{0},
6260 the parser will not use @code{alloca} but @code{malloc} when trying to
6261 grow its internal stacks. Do @emph{not} define @code{YYSTACK_USE_ALLOCA}
6262 to anything else.
6263
6264 @item YYSTYPE
6265 Macro for the data type of semantic values; @code{int} by default.
6266 @xref{Value Type, ,Data Types of Semantic Values}.
6267
6268 @item yychar
6269 External integer variable that contains the integer value of the current
6270 look-ahead token. (In a pure parser, it is a local variable within
6271 @code{yyparse}.) Error-recovery rule actions may examine this variable.
6272 @xref{Action Features, ,Special Features for Use in Actions}.
6273
6274 @item yyclearin
6275 Macro used in error-recovery rule actions. It clears the previous
6276 look-ahead token. @xref{Error Recovery}.
6277
6278 @item yydebug
6279 External integer variable set to zero by default. If @code{yydebug}
6280 is given a nonzero value, the parser will output information on input
6281 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
6282
6283 @item yyerrok
6284 Macro to cause parser to recover immediately to its normal mode
6285 after a parse error. @xref{Error Recovery}.
6286
6287 @item yyerror
6288 User-supplied function to be called by @code{yyparse} on error. The
6289 function receives one argument, a pointer to a character string
6290 containing an error message. @xref{Error Reporting, ,The Error
6291 Reporting Function @code{yyerror}}.
6292
6293 @item yylex
6294 User-supplied lexical analyzer function, called with no arguments to get
6295 the next token. @xref{Lexical, ,The Lexical Analyzer Function
6296 @code{yylex}}.
6297
6298 @item yylval
6299 External variable in which @code{yylex} should place the semantic
6300 value associated with a token. (In a pure parser, it is a local
6301 variable within @code{yyparse}, and its address is passed to
6302 @code{yylex}.) @xref{Token Values, ,Semantic Values of Tokens}.
6303
6304 @item yylloc
6305 External variable in which @code{yylex} should place the line and column
6306 numbers associated with a token. (In a pure parser, it is a local
6307 variable within @code{yyparse}, and its address is passed to
6308 @code{yylex}.) You can ignore this variable if you don't use the
6309 @samp{@@} feature in the grammar actions. @xref{Token Positions,
6310 ,Textual Positions of Tokens}.
6311
6312 @item yynerrs
6313 Global variable which Bison increments each time there is a parse error.
6314 (In a pure parser, it is a local variable within @code{yyparse}.)
6315 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
6316
6317 @item yyparse
6318 The parser function produced by Bison; call this function to start
6319 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6320
6321 @item %debug
6322 Equip the parser for debugging. @xref{Decl Summary}.
6323
6324 @item %defines
6325 Bison declaration to create a header file meant for the scanner.
6326 @xref{Decl Summary}.
6327
6328 @item %dprec
6329 Bison declaration to assign a precedence to a rule that is used at parse
6330 time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
6331 @acronym{GLR} Parsers}.
6332
6333 @item %error-verbose
6334 Bison declaration to request verbose, specific error message strings
6335 when @code{yyerror} is called.
6336
6337 @item %file-prefix="@var{prefix}"
6338 Bison declaration to set the prefix of the output files. @xref{Decl
6339 Summary}.
6340
6341 @item %glr-parser
6342 Bison declaration to produce a @acronym{GLR} parser. @xref{GLR
6343 Parsers, ,Writing @acronym{GLR} Parsers}.
6344
6345 @c @item %source-extension
6346 @c Bison declaration to specify the generated parser output file extension.
6347 @c @xref{Decl Summary}.
6348 @c
6349 @c @item %header-extension
6350 @c Bison declaration to specify the generated parser header file extension
6351 @c if required. @xref{Decl Summary}.
6352
6353 @item %left
6354 Bison declaration to assign left associativity to token(s).
6355 @xref{Precedence Decl, ,Operator Precedence}.
6356
6357 @item %lex-param "@var{argument-declaration}" "@var{argument-name}"
6358 Bison declaration to specifying an additional parameter that
6359 @code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
6360 for Pure Parsers}.
6361
6362 @item %merge
6363 Bison declaration to assign a merging function to a rule. If there is a
6364 reduce/reduce conflict with a rule having the same merging function, the
6365 function is applied to the two semantic values to get a single result.
6366 @xref{GLR Parsers, ,Writing @acronym{GLR} Parsers}.
6367
6368 @item %name-prefix="@var{prefix}"
6369 Bison declaration to rename the external symbols. @xref{Decl Summary}.
6370
6371 @item %no-lines
6372 Bison declaration to avoid generating @code{#line} directives in the
6373 parser file. @xref{Decl Summary}.
6374
6375 @item %nonassoc
6376 Bison declaration to assign non-associativity to token(s).
6377 @xref{Precedence Decl, ,Operator Precedence}.
6378
6379 @item %output="@var{filename}"
6380 Bison declaration to set the name of the parser file. @xref{Decl
6381 Summary}.
6382
6383 @item %parse-param "@var{argument-declaration}" "@var{argument-name}"
6384 Bison declaration to specifying an additional parameter that
6385 @code{yyparse} should accept. @xref{Parser Function,, The Parser
6386 Function @code{yyparse}}.
6387
6388 @item %prec
6389 Bison declaration to assign a precedence to a specific rule.
6390 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
6391
6392 @item %pure-parser
6393 Bison declaration to request a pure (reentrant) parser.
6394 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6395
6396 @item %right
6397 Bison declaration to assign right associativity to token(s).
6398 @xref{Precedence Decl, ,Operator Precedence}.
6399
6400 @item %start
6401 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
6402 Start-Symbol}.
6403
6404 @item %token
6405 Bison declaration to declare token(s) without specifying precedence.
6406 @xref{Token Decl, ,Token Type Names}.
6407
6408 @item %token-table
6409 Bison declaration to include a token name table in the parser file.
6410 @xref{Decl Summary}.
6411
6412 @item %type
6413 Bison declaration to declare nonterminals. @xref{Type Decl,
6414 ,Nonterminal Symbols}.
6415
6416 @item %union
6417 Bison declaration to specify several possible data types for semantic
6418 values. @xref{Union Decl, ,The Collection of Value Types}.
6419 @end table
6420
6421 @sp 1
6422
6423 These are the punctuation and delimiters used in Bison input:
6424
6425 @table @samp
6426 @item %%
6427 Delimiter used to separate the grammar rule section from the
6428 Bison declarations section or the epilogue.
6429 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
6430
6431 @item %@{ %@}
6432 All code listed between @samp{%@{} and @samp{%@}} is copied directly to
6433 the output file uninterpreted. Such code forms the prologue of the input
6434 file. @xref{Grammar Outline, ,Outline of a Bison
6435 Grammar}.
6436
6437 @item /*@dots{}*/
6438 Comment delimiters, as in C.
6439
6440 @item :
6441 Separates a rule's result from its components. @xref{Rules, ,Syntax of
6442 Grammar Rules}.
6443
6444 @item ;
6445 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
6446
6447 @item |
6448 Separates alternate rules for the same result nonterminal.
6449 @xref{Rules, ,Syntax of Grammar Rules}.
6450 @end table
6451
6452 @node Glossary
6453 @appendix Glossary
6454 @cindex glossary
6455
6456 @table @asis
6457 @item Backus-Naur Form (@acronym{BNF}; also called ``Backus Normal Form'')
6458 Formal method of specifying context-free grammars originally proposed
6459 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
6460 committee document contributing to what became the Algol 60 report.
6461 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6462
6463 @item Context-free grammars
6464 Grammars specified as rules that can be applied regardless of context.
6465 Thus, if there is a rule which says that an integer can be used as an
6466 expression, integers are allowed @emph{anywhere} an expression is
6467 permitted. @xref{Language and Grammar, ,Languages and Context-Free
6468 Grammars}.
6469
6470 @item Dynamic allocation
6471 Allocation of memory that occurs during execution, rather than at
6472 compile time or on entry to a function.
6473
6474 @item Empty string
6475 Analogous to the empty set in set theory, the empty string is a
6476 character string of length zero.
6477
6478 @item Finite-state stack machine
6479 A ``machine'' that has discrete states in which it is said to exist at
6480 each instant in time. As input to the machine is processed, the
6481 machine moves from state to state as specified by the logic of the
6482 machine. In the case of the parser, the input is the language being
6483 parsed, and the states correspond to various stages in the grammar
6484 rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
6485
6486 @item Generalized @acronym{LR} (@acronym{GLR})
6487 A parsing algorithm that can handle all context-free grammars, including those
6488 that are not @acronym{LALR}(1). It resolves situations that Bison's
6489 usual @acronym{LALR}(1)
6490 algorithm cannot by effectively splitting off multiple parsers, trying all
6491 possible parsers, and discarding those that fail in the light of additional
6492 right context. @xref{Generalized LR Parsing, ,Generalized
6493 @acronym{LR} Parsing}.
6494
6495 @item Grouping
6496 A language construct that is (in general) grammatically divisible;
6497 for example, `expression' or `declaration' in C@.
6498 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6499
6500 @item Infix operator
6501 An arithmetic operator that is placed between the operands on which it
6502 performs some operation.
6503
6504 @item Input stream
6505 A continuous flow of data between devices or programs.
6506
6507 @item Language construct
6508 One of the typical usage schemas of the language. For example, one of
6509 the constructs of the C language is the @code{if} statement.
6510 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6511
6512 @item Left associativity
6513 Operators having left associativity are analyzed from left to right:
6514 @samp{a+b+c} first computes @samp{a+b} and then combines with
6515 @samp{c}. @xref{Precedence, ,Operator Precedence}.
6516
6517 @item Left recursion
6518 A rule whose result symbol is also its first component symbol; for
6519 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
6520 Rules}.
6521
6522 @item Left-to-right parsing
6523 Parsing a sentence of a language by analyzing it token by token from
6524 left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
6525
6526 @item Lexical analyzer (scanner)
6527 A function that reads an input stream and returns tokens one by one.
6528 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
6529
6530 @item Lexical tie-in
6531 A flag, set by actions in the grammar rules, which alters the way
6532 tokens are parsed. @xref{Lexical Tie-ins}.
6533
6534 @item Literal string token
6535 A token which consists of two or more fixed characters. @xref{Symbols}.
6536
6537 @item Look-ahead token
6538 A token already read but not yet shifted. @xref{Look-Ahead, ,Look-Ahead
6539 Tokens}.
6540
6541 @item @acronym{LALR}(1)
6542 The class of context-free grammars that Bison (like most other parser
6543 generators) can handle; a subset of @acronym{LR}(1). @xref{Mystery
6544 Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
6545
6546 @item @acronym{LR}(1)
6547 The class of context-free grammars in which at most one token of
6548 look-ahead is needed to disambiguate the parsing of any piece of input.
6549
6550 @item Nonterminal symbol
6551 A grammar symbol standing for a grammatical construct that can
6552 be expressed through rules in terms of smaller constructs; in other
6553 words, a construct that is not a token. @xref{Symbols}.
6554
6555 @item Parse error
6556 An error encountered during parsing of an input stream due to invalid
6557 syntax. @xref{Error Recovery}.
6558
6559 @item Parser
6560 A function that recognizes valid sentences of a language by analyzing
6561 the syntax structure of a set of tokens passed to it from a lexical
6562 analyzer.
6563
6564 @item Postfix operator
6565 An arithmetic operator that is placed after the operands upon which it
6566 performs some operation.
6567
6568 @item Reduction
6569 Replacing a string of nonterminals and/or terminals with a single
6570 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
6571 Parser Algorithm}.
6572
6573 @item Reentrant
6574 A reentrant subprogram is a subprogram which can be in invoked any
6575 number of times in parallel, without interference between the various
6576 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6577
6578 @item Reverse polish notation
6579 A language in which all operators are postfix operators.
6580
6581 @item Right recursion
6582 A rule whose result symbol is also its last component symbol; for
6583 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
6584 Rules}.
6585
6586 @item Semantics
6587 In computer languages, the semantics are specified by the actions
6588 taken for each instance of the language, i.e., the meaning of
6589 each statement. @xref{Semantics, ,Defining Language Semantics}.
6590
6591 @item Shift
6592 A parser is said to shift when it makes the choice of analyzing
6593 further input from the stream rather than reducing immediately some
6594 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
6595
6596 @item Single-character literal
6597 A single character that is recognized and interpreted as is.
6598 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
6599
6600 @item Start symbol
6601 The nonterminal symbol that stands for a complete valid utterance in
6602 the language being parsed. The start symbol is usually listed as the
6603 first nonterminal symbol in a language specification.
6604 @xref{Start Decl, ,The Start-Symbol}.
6605
6606 @item Symbol table
6607 A data structure where symbol names and associated data are stored
6608 during parsing to allow for recognition and use of existing
6609 information in repeated uses of a symbol. @xref{Multi-function Calc}.
6610
6611 @item Token
6612 A basic, grammatically indivisible unit of a language. The symbol
6613 that describes a token in the grammar is a terminal symbol.
6614 The input of the Bison parser is a stream of tokens which comes from
6615 the lexical analyzer. @xref{Symbols}.
6616
6617 @item Terminal symbol
6618 A grammar symbol that has no rules in the grammar and therefore is
6619 grammatically indivisible. The piece of text it represents is a token.
6620 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6621 @end table
6622
6623 @node Copying This Manual
6624 @appendix Copying This Manual
6625
6626 @menu
6627 * GNU Free Documentation License:: License for copying this manual.
6628 @end menu
6629
6630 @include fdl.texi
6631
6632 @node Index
6633 @unnumbered Index
6634
6635 @printindex cp
6636
6637 @bye