]> git.saurik.com Git - bison.git/blob - doc/bison.texinfo
(Torturing the Scanner): Don't invoke "cc a.c b.c
[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 * Destructor Decl:: Declaring how symbols are freed.
212 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
213 * Start Decl:: Specifying the start symbol.
214 * Pure Decl:: Requesting a reentrant parser.
215 * Decl Summary:: Table of all Bison declarations.
216
217 Parser C-Language Interface
218
219 * Parser Function:: How to call @code{yyparse} and what it returns.
220 * Lexical:: You must supply a function @code{yylex}
221 which reads tokens.
222 * Error Reporting:: You must supply a function @code{yyerror}.
223 * Action Features:: Special features for use in actions.
224
225 The Lexical Analyzer Function @code{yylex}
226
227 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
228 * Token Values:: How @code{yylex} must return the semantic value
229 of the token it has read.
230 * Token Positions:: How @code{yylex} must return the text position
231 (line number, etc.) of the token, if the
232 actions want that.
233 * Pure Calling:: How the calling convention differs
234 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
235
236 The Bison Parser Algorithm
237
238 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
239 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
240 * Precedence:: Operator precedence works by resolving conflicts.
241 * Contextual Precedence:: When an operator's precedence depends on context.
242 * Parser States:: The parser is a finite-state-machine with stack.
243 * Reduce/Reduce:: When two rules are applicable in the same situation.
244 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
245 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
246 * Stack Overflow:: What happens when stack gets full. How to avoid it.
247
248 Operator Precedence
249
250 * Why Precedence:: An example showing why precedence is needed.
251 * Using Precedence:: How to specify precedence in Bison grammars.
252 * Precedence Examples:: How these features are used in the previous example.
253 * How Precedence:: How they work.
254
255 Handling Context Dependencies
256
257 * Semantic Tokens:: Token parsing can depend on the semantic context.
258 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
259 * Tie-in Recovery:: Lexical tie-ins have implications for how
260 error recovery rules must be written.
261
262 Understanding or Debugging Your Parser
263
264 * Understanding:: Understanding the structure of your parser.
265 * Tracing:: Tracing the execution of your parser.
266
267 Invoking Bison
268
269 * Bison Options:: All the options described in detail,
270 in alphabetical order by short options.
271 * Option Cross Key:: Alphabetical list of long options.
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 @end smallexample
1857
1858 The above grammar introduces only two new features of the Bison language.
1859 These features allow semantic values to have various data types
1860 (@pxref{Multiple Types, ,More Than One Value Type}).
1861
1862 The @code{%union} declaration specifies the entire list of possible types;
1863 this is instead of defining @code{YYSTYPE}. The allowable types are now
1864 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
1865 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
1866
1867 Since values can now have various types, it is necessary to associate a
1868 type with each grammar symbol whose semantic value is used. These symbols
1869 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
1870 declarations are augmented with information about their data type (placed
1871 between angle brackets).
1872
1873 The Bison construct @code{%type} is used for declaring nonterminal
1874 symbols, just as @code{%token} is used for declaring token types. We
1875 have not used @code{%type} before because nonterminal symbols are
1876 normally declared implicitly by the rules that define them. But
1877 @code{exp} must be declared explicitly so we can specify its value type.
1878 @xref{Type Decl, ,Nonterminal Symbols}.
1879
1880 @node Mfcalc Rules
1881 @subsection Grammar Rules for @code{mfcalc}
1882
1883 Here are the grammar rules for the multi-function calculator.
1884 Most of them are copied directly from @code{calc}; three rules,
1885 those which mention @code{VAR} or @code{FNCT}, are new.
1886
1887 @smallexample
1888 input: /* empty */
1889 | input line
1890 ;
1891
1892 line:
1893 '\n'
1894 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1895 | error '\n' @{ yyerrok; @}
1896 ;
1897
1898 exp: NUM @{ $$ = $1; @}
1899 | VAR @{ $$ = $1->value.var; @}
1900 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
1901 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
1902 | exp '+' exp @{ $$ = $1 + $3; @}
1903 | exp '-' exp @{ $$ = $1 - $3; @}
1904 | exp '*' exp @{ $$ = $1 * $3; @}
1905 | exp '/' exp @{ $$ = $1 / $3; @}
1906 | '-' exp %prec NEG @{ $$ = -$2; @}
1907 | exp '^' exp @{ $$ = pow ($1, $3); @}
1908 | '(' exp ')' @{ $$ = $2; @}
1909 ;
1910 /* End of grammar */
1911 %%
1912 @end smallexample
1913
1914 @node Mfcalc Symtab
1915 @subsection The @code{mfcalc} Symbol Table
1916 @cindex symbol table example
1917
1918 The multi-function calculator requires a symbol table to keep track of the
1919 names and meanings of variables and functions. This doesn't affect the
1920 grammar rules (except for the actions) or the Bison declarations, but it
1921 requires some additional C functions for support.
1922
1923 The symbol table itself consists of a linked list of records. Its
1924 definition, which is kept in the header @file{calc.h}, is as follows. It
1925 provides for either functions or variables to be placed in the table.
1926
1927 @smallexample
1928 @group
1929 /* Function type. */
1930 typedef double (*func_t) (double);
1931 @end group
1932
1933 @group
1934 /* Data type for links in the chain of symbols. */
1935 struct symrec
1936 @{
1937 char *name; /* name of symbol */
1938 int type; /* type of symbol: either VAR or FNCT */
1939 union
1940 @{
1941 double var; /* value of a VAR */
1942 func_t fnctptr; /* value of a FNCT */
1943 @} value;
1944 struct symrec *next; /* link field */
1945 @};
1946 @end group
1947
1948 @group
1949 typedef struct symrec symrec;
1950
1951 /* The symbol table: a chain of `struct symrec'. */
1952 extern symrec *sym_table;
1953
1954 symrec *putsym (const char *, func_t);
1955 symrec *getsym (const char *);
1956 @end group
1957 @end smallexample
1958
1959 The new version of @code{main} includes a call to @code{init_table}, a
1960 function that initializes the symbol table. Here it is, and
1961 @code{init_table} as well:
1962
1963 @smallexample
1964 @group
1965 #include <stdio.h>
1966
1967 int
1968 main (void)
1969 @{
1970 init_table ();
1971 return yyparse ();
1972 @}
1973 @end group
1974
1975 @group
1976 void
1977 yyerror (const char *s) /* Called by yyparse on error. */
1978 @{
1979 printf ("%s\n", s);
1980 @}
1981
1982 struct init
1983 @{
1984 char *fname;
1985 double (*fnct)(double);
1986 @};
1987 @end group
1988
1989 @group
1990 struct init arith_fncts[] =
1991 @{
1992 "sin", sin,
1993 "cos", cos,
1994 "atan", atan,
1995 "ln", log,
1996 "exp", exp,
1997 "sqrt", sqrt,
1998 0, 0
1999 @};
2000
2001 /* The symbol table: a chain of `struct symrec'. */
2002 symrec *sym_table = (symrec *) 0;
2003 @end group
2004
2005 @group
2006 /* Put arithmetic functions in table. */
2007 void
2008 init_table (void)
2009 @{
2010 int i;
2011 symrec *ptr;
2012 for (i = 0; arith_fncts[i].fname != 0; i++)
2013 @{
2014 ptr = putsym (arith_fncts[i].fname, FNCT);
2015 ptr->value.fnctptr = arith_fncts[i].fnct;
2016 @}
2017 @}
2018 @end group
2019 @end smallexample
2020
2021 By simply editing the initialization list and adding the necessary include
2022 files, you can add additional functions to the calculator.
2023
2024 Two important functions allow look-up and installation of symbols in the
2025 symbol table. The function @code{putsym} is passed a name and the type
2026 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2027 linked to the front of the list, and a pointer to the object is returned.
2028 The function @code{getsym} is passed the name of the symbol to look up. If
2029 found, a pointer to that symbol is returned; otherwise zero is returned.
2030
2031 @smallexample
2032 symrec *
2033 putsym (char *sym_name, int sym_type)
2034 @{
2035 symrec *ptr;
2036 ptr = (symrec *) malloc (sizeof (symrec));
2037 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2038 strcpy (ptr->name,sym_name);
2039 ptr->type = sym_type;
2040 ptr->value.var = 0; /* Set value to 0 even if fctn. */
2041 ptr->next = (struct symrec *)sym_table;
2042 sym_table = ptr;
2043 return ptr;
2044 @}
2045
2046 symrec *
2047 getsym (const char *sym_name)
2048 @{
2049 symrec *ptr;
2050 for (ptr = sym_table; ptr != (symrec *) 0;
2051 ptr = (symrec *)ptr->next)
2052 if (strcmp (ptr->name,sym_name) == 0)
2053 return ptr;
2054 return 0;
2055 @}
2056 @end smallexample
2057
2058 The function @code{yylex} must now recognize variables, numeric values, and
2059 the single-character arithmetic operators. Strings of alphanumeric
2060 characters with a leading non-digit are recognized as either variables or
2061 functions depending on what the symbol table says about them.
2062
2063 The string is passed to @code{getsym} for look up in the symbol table. If
2064 the name appears in the table, a pointer to its location and its type
2065 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2066 already in the table, then it is installed as a @code{VAR} using
2067 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2068 returned to @code{yyparse}.
2069
2070 No change is needed in the handling of numeric values and arithmetic
2071 operators in @code{yylex}.
2072
2073 @smallexample
2074 @group
2075 #include <ctype.h>
2076
2077 int
2078 yylex (void)
2079 @{
2080 int c;
2081
2082 /* Ignore white space, get first nonwhite character. */
2083 while ((c = getchar ()) == ' ' || c == '\t');
2084
2085 if (c == EOF)
2086 return 0;
2087 @end group
2088
2089 @group
2090 /* Char starts a number => parse the number. */
2091 if (c == '.' || isdigit (c))
2092 @{
2093 ungetc (c, stdin);
2094 scanf ("%lf", &yylval.val);
2095 return NUM;
2096 @}
2097 @end group
2098
2099 @group
2100 /* Char starts an identifier => read the name. */
2101 if (isalpha (c))
2102 @{
2103 symrec *s;
2104 static char *symbuf = 0;
2105 static int length = 0;
2106 int i;
2107 @end group
2108
2109 @group
2110 /* Initially make the buffer long enough
2111 for a 40-character symbol name. */
2112 if (length == 0)
2113 length = 40, symbuf = (char *)malloc (length + 1);
2114
2115 i = 0;
2116 do
2117 @end group
2118 @group
2119 @{
2120 /* If buffer is full, make it bigger. */
2121 if (i == length)
2122 @{
2123 length *= 2;
2124 symbuf = (char *)realloc (symbuf, length + 1);
2125 @}
2126 /* Add this character to the buffer. */
2127 symbuf[i++] = c;
2128 /* Get another character. */
2129 c = getchar ();
2130 @}
2131 @end group
2132 @group
2133 while (isalnum (c));
2134
2135 ungetc (c, stdin);
2136 symbuf[i] = '\0';
2137 @end group
2138
2139 @group
2140 s = getsym (symbuf);
2141 if (s == 0)
2142 s = putsym (symbuf, VAR);
2143 yylval.tptr = s;
2144 return s->type;
2145 @}
2146
2147 /* Any other character is a token by itself. */
2148 return c;
2149 @}
2150 @end group
2151 @end smallexample
2152
2153 This program is both powerful and flexible. You may easily add new
2154 functions, and it is a simple job to modify this code to install
2155 predefined variables such as @code{pi} or @code{e} as well.
2156
2157 @node Exercises
2158 @section Exercises
2159 @cindex exercises
2160
2161 @enumerate
2162 @item
2163 Add some new functions from @file{math.h} to the initialization list.
2164
2165 @item
2166 Add another array that contains constants and their values. Then
2167 modify @code{init_table} to add these constants to the symbol table.
2168 It will be easiest to give the constants type @code{VAR}.
2169
2170 @item
2171 Make the program report an error if the user refers to an
2172 uninitialized variable in any way except to store a value in it.
2173 @end enumerate
2174
2175 @node Grammar File
2176 @chapter Bison Grammar Files
2177
2178 Bison takes as input a context-free grammar specification and produces a
2179 C-language function that recognizes correct instances of the grammar.
2180
2181 The Bison grammar input file conventionally has a name ending in @samp{.y}.
2182 @xref{Invocation, ,Invoking Bison}.
2183
2184 @menu
2185 * Grammar Outline:: Overall layout of the grammar file.
2186 * Symbols:: Terminal and nonterminal symbols.
2187 * Rules:: How to write grammar rules.
2188 * Recursion:: Writing recursive rules.
2189 * Semantics:: Semantic values and actions.
2190 * Locations:: Locations and actions.
2191 * Declarations:: All kinds of Bison declarations are described here.
2192 * Multiple Parsers:: Putting more than one Bison parser in one program.
2193 @end menu
2194
2195 @node Grammar Outline
2196 @section Outline of a Bison Grammar
2197
2198 A Bison grammar file has four main sections, shown here with the
2199 appropriate delimiters:
2200
2201 @example
2202 %@{
2203 @var{Prologue}
2204 %@}
2205
2206 @var{Bison declarations}
2207
2208 %%
2209 @var{Grammar rules}
2210 %%
2211
2212 @var{Epilogue}
2213 @end example
2214
2215 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2216 As a @acronym{GNU} extension, @samp{//} introduces a comment that
2217 continues until end of line.
2218
2219 @menu
2220 * Prologue:: Syntax and usage of the prologue.
2221 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2222 * Grammar Rules:: Syntax and usage of the grammar rules section.
2223 * Epilogue:: Syntax and usage of the epilogue.
2224 @end menu
2225
2226 @node Prologue, Bison Declarations, , Grammar Outline
2227 @subsection The prologue
2228 @cindex declarations section
2229 @cindex Prologue
2230 @cindex declarations
2231
2232 The @var{Prologue} section contains macro definitions and
2233 declarations of functions and variables that are used in the actions in the
2234 grammar rules. These are copied to the beginning of the parser file so
2235 that they precede the definition of @code{yyparse}. You can use
2236 @samp{#include} to get the declarations from a header file. If you don't
2237 need any C declarations, you may omit the @samp{%@{} and @samp{%@}}
2238 delimiters that bracket this section.
2239
2240 You may have more than one @var{Prologue} section, intermixed with the
2241 @var{Bison declarations}. This allows you to have C and Bison
2242 declarations that refer to each other. For example, the @code{%union}
2243 declaration may use types defined in a header file, and you may wish to
2244 prototype functions that take arguments of type @code{YYSTYPE}. This
2245 can be done with two @var{Prologue} blocks, one before and one after the
2246 @code{%union} declaration.
2247
2248 @smallexample
2249 %@{
2250 #include <stdio.h>
2251 #include "ptypes.h"
2252 %@}
2253
2254 %union @{
2255 long n;
2256 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2257 @}
2258
2259 %@{
2260 static void yyprint(FILE *, int, YYSTYPE);
2261 #define YYPRINT(F, N, L) yyprint(F, N, L)
2262 %@}
2263
2264 @dots{}
2265 @end smallexample
2266
2267 @node Bison Declarations
2268 @subsection The Bison Declarations Section
2269 @cindex Bison declarations (introduction)
2270 @cindex declarations, Bison (introduction)
2271
2272 The @var{Bison declarations} section contains declarations that define
2273 terminal and nonterminal symbols, specify precedence, and so on.
2274 In some simple grammars you may not need any declarations.
2275 @xref{Declarations, ,Bison Declarations}.
2276
2277 @node Grammar Rules
2278 @subsection The Grammar Rules Section
2279 @cindex grammar rules section
2280 @cindex rules section for grammar
2281
2282 The @dfn{grammar rules} section contains one or more Bison grammar
2283 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
2284
2285 There must always be at least one grammar rule, and the first
2286 @samp{%%} (which precedes the grammar rules) may never be omitted even
2287 if it is the first thing in the file.
2288
2289 @node Epilogue, , Grammar Rules, Grammar Outline
2290 @subsection The epilogue
2291 @cindex additional C code section
2292 @cindex epilogue
2293 @cindex C code, section for additional
2294
2295 The @var{Epilogue} is copied verbatim to the end of the parser file, just as
2296 the @var{Prologue} is copied to the beginning. This is the most convenient
2297 place to put anything that you want to have in the parser file but which need
2298 not come before the definition of @code{yyparse}. For example, the
2299 definitions of @code{yylex} and @code{yyerror} often go here.
2300 @xref{Interface, ,Parser C-Language Interface}.
2301
2302 If the last section is empty, you may omit the @samp{%%} that separates it
2303 from the grammar rules.
2304
2305 The Bison parser itself contains many static variables whose names start
2306 with @samp{yy} and many macros whose names start with @samp{YY}. It is a
2307 good idea to avoid using any such names (except those documented in this
2308 manual) in the epilogue of the grammar file.
2309
2310 @node Symbols
2311 @section Symbols, Terminal and Nonterminal
2312 @cindex nonterminal symbol
2313 @cindex terminal symbol
2314 @cindex token type
2315 @cindex symbol
2316
2317 @dfn{Symbols} in Bison grammars represent the grammatical classifications
2318 of the language.
2319
2320 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
2321 class of syntactically equivalent tokens. You use the symbol in grammar
2322 rules to mean that a token in that class is allowed. The symbol is
2323 represented in the Bison parser by a numeric code, and the @code{yylex}
2324 function returns a token type code to indicate what kind of token has been
2325 read. You don't need to know what the code value is; you can use the
2326 symbol to stand for it.
2327
2328 A @dfn{nonterminal symbol} stands for a class of syntactically equivalent
2329 groupings. The symbol name is used in writing grammar rules. By convention,
2330 it should be all lower case.
2331
2332 Symbol names can contain letters, digits (not at the beginning),
2333 underscores and periods. Periods make sense only in nonterminals.
2334
2335 There are three ways of writing terminal symbols in the grammar:
2336
2337 @itemize @bullet
2338 @item
2339 A @dfn{named token type} is written with an identifier, like an
2340 identifier in C@. By convention, it should be all upper case. Each
2341 such name must be defined with a Bison declaration such as
2342 @code{%token}. @xref{Token Decl, ,Token Type Names}.
2343
2344 @item
2345 @cindex character token
2346 @cindex literal token
2347 @cindex single-character literal
2348 A @dfn{character token type} (or @dfn{literal character token}) is
2349 written in the grammar using the same syntax used in C for character
2350 constants; for example, @code{'+'} is a character token type. A
2351 character token type doesn't need to be declared unless you need to
2352 specify its semantic value data type (@pxref{Value Type, ,Data Types of
2353 Semantic Values}), associativity, or precedence (@pxref{Precedence,
2354 ,Operator Precedence}).
2355
2356 By convention, a character token type is used only to represent a
2357 token that consists of that particular character. Thus, the token
2358 type @code{'+'} is used to represent the character @samp{+} as a
2359 token. Nothing enforces this convention, but if you depart from it,
2360 your program will confuse other readers.
2361
2362 All the usual escape sequences used in character literals in C can be
2363 used in Bison as well, but you must not use the null character as a
2364 character literal because its numeric code, zero, signifies
2365 end-of-input (@pxref{Calling Convention, ,Calling Convention
2366 for @code{yylex}}). Also, unlike standard C, trigraphs have no
2367 special meaning in Bison character literals, nor is backslash-newline
2368 allowed.
2369
2370 @item
2371 @cindex string token
2372 @cindex literal string token
2373 @cindex multicharacter literal
2374 A @dfn{literal string token} is written like a C string constant; for
2375 example, @code{"<="} is a literal string token. A literal string token
2376 doesn't need to be declared unless you need to specify its semantic
2377 value data type (@pxref{Value Type}), associativity, or precedence
2378 (@pxref{Precedence}).
2379
2380 You can associate the literal string token with a symbolic name as an
2381 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
2382 Declarations}). If you don't do that, the lexical analyzer has to
2383 retrieve the token number for the literal string token from the
2384 @code{yytname} table (@pxref{Calling Convention}).
2385
2386 @strong{Warning}: literal string tokens do not work in Yacc.
2387
2388 By convention, a literal string token is used only to represent a token
2389 that consists of that particular string. Thus, you should use the token
2390 type @code{"<="} to represent the string @samp{<=} as a token. Bison
2391 does not enforce this convention, but if you depart from it, people who
2392 read your program will be confused.
2393
2394 All the escape sequences used in string literals in C can be used in
2395 Bison as well. However, unlike Standard C, trigraphs have no special
2396 meaning in Bison string literals, nor is backslash-newline allowed. A
2397 literal string token must contain two or more characters; for a token
2398 containing just one character, use a character token (see above).
2399 @end itemize
2400
2401 How you choose to write a terminal symbol has no effect on its
2402 grammatical meaning. That depends only on where it appears in rules and
2403 on when the parser function returns that symbol.
2404
2405 The value returned by @code{yylex} is always one of the terminal
2406 symbols, except that a zero or negative value signifies end-of-input.
2407 Whichever way you write the token type in the grammar rules, you write
2408 it the same way in the definition of @code{yylex}. The numeric code
2409 for a character token type is simply the positive numeric code of the
2410 character, so @code{yylex} can use the identical value to generate the
2411 requisite code, though you may need to convert it to @code{unsigned
2412 char} to avoid sign-extension on hosts where @code{char} is signed.
2413 Each named token type becomes a C macro in
2414 the parser file, so @code{yylex} can use the name to stand for the code.
2415 (This is why periods don't make sense in terminal symbols.)
2416 @xref{Calling Convention, ,Calling Convention for @code{yylex}}.
2417
2418 If @code{yylex} is defined in a separate file, you need to arrange for the
2419 token-type macro definitions to be available there. Use the @samp{-d}
2420 option when you run Bison, so that it will write these macro definitions
2421 into a separate header file @file{@var{name}.tab.h} which you can include
2422 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
2423
2424 If you want to write a grammar that is portable to any Standard C
2425 host, you must use only non-null character tokens taken from the basic
2426 execution character set of Standard C@. This set consists of the ten
2427 digits, the 52 lower- and upper-case English letters, and the
2428 characters in the following C-language string:
2429
2430 @example
2431 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
2432 @end example
2433
2434 The @code{yylex} function and Bison must use a consistent character
2435 set and encoding for character tokens. For example, if you run Bison in an
2436 @acronym{ASCII} environment, but then compile and run the resulting program
2437 in an environment that uses an incompatible character set like
2438 @acronym{EBCDIC}, the resulting program may not work because the
2439 tables generated by Bison will assume @acronym{ASCII} numeric values for
2440 character tokens. It is standard
2441 practice for software distributions to contain C source files that
2442 were generated by Bison in an @acronym{ASCII} environment, so installers on
2443 platforms that are incompatible with @acronym{ASCII} must rebuild those
2444 files before compiling them.
2445
2446 The symbol @code{error} is a terminal symbol reserved for error recovery
2447 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
2448 In particular, @code{yylex} should never return this value. The default
2449 value of the error token is 256, unless you explicitly assigned 256 to
2450 one of your tokens with a @code{%token} declaration.
2451
2452 @node Rules
2453 @section Syntax of Grammar Rules
2454 @cindex rule syntax
2455 @cindex grammar rule syntax
2456 @cindex syntax of grammar rules
2457
2458 A Bison grammar rule has the following general form:
2459
2460 @example
2461 @group
2462 @var{result}: @var{components}@dots{}
2463 ;
2464 @end group
2465 @end example
2466
2467 @noindent
2468 where @var{result} is the nonterminal symbol that this rule describes,
2469 and @var{components} are various terminal and nonterminal symbols that
2470 are put together by this rule (@pxref{Symbols}).
2471
2472 For example,
2473
2474 @example
2475 @group
2476 exp: exp '+' exp
2477 ;
2478 @end group
2479 @end example
2480
2481 @noindent
2482 says that two groupings of type @code{exp}, with a @samp{+} token in between,
2483 can be combined into a larger grouping of type @code{exp}.
2484
2485 White space in rules is significant only to separate symbols. You can add
2486 extra white space as you wish.
2487
2488 Scattered among the components can be @var{actions} that determine
2489 the semantics of the rule. An action looks like this:
2490
2491 @example
2492 @{@var{C statements}@}
2493 @end example
2494
2495 @noindent
2496 Usually there is only one action and it follows the components.
2497 @xref{Actions}.
2498
2499 @findex |
2500 Multiple rules for the same @var{result} can be written separately or can
2501 be joined with the vertical-bar character @samp{|} as follows:
2502
2503 @ifinfo
2504 @example
2505 @var{result}: @var{rule1-components}@dots{}
2506 | @var{rule2-components}@dots{}
2507 @dots{}
2508 ;
2509 @end example
2510 @end ifinfo
2511 @iftex
2512 @example
2513 @group
2514 @var{result}: @var{rule1-components}@dots{}
2515 | @var{rule2-components}@dots{}
2516 @dots{}
2517 ;
2518 @end group
2519 @end example
2520 @end iftex
2521
2522 @noindent
2523 They are still considered distinct rules even when joined in this way.
2524
2525 If @var{components} in a rule is empty, it means that @var{result} can
2526 match the empty string. For example, here is how to define a
2527 comma-separated sequence of zero or more @code{exp} groupings:
2528
2529 @example
2530 @group
2531 expseq: /* empty */
2532 | expseq1
2533 ;
2534 @end group
2535
2536 @group
2537 expseq1: exp
2538 | expseq1 ',' exp
2539 ;
2540 @end group
2541 @end example
2542
2543 @noindent
2544 It is customary to write a comment @samp{/* empty */} in each rule
2545 with no components.
2546
2547 @node Recursion
2548 @section Recursive Rules
2549 @cindex recursive rule
2550
2551 A rule is called @dfn{recursive} when its @var{result} nonterminal appears
2552 also on its right hand side. Nearly all Bison grammars need to use
2553 recursion, because that is the only way to define a sequence of any number
2554 of a particular thing. Consider this recursive definition of a
2555 comma-separated sequence of one or more expressions:
2556
2557 @example
2558 @group
2559 expseq1: exp
2560 | expseq1 ',' exp
2561 ;
2562 @end group
2563 @end example
2564
2565 @cindex left recursion
2566 @cindex right recursion
2567 @noindent
2568 Since the recursive use of @code{expseq1} is the leftmost symbol in the
2569 right hand side, we call this @dfn{left recursion}. By contrast, here
2570 the same construct is defined using @dfn{right recursion}:
2571
2572 @example
2573 @group
2574 expseq1: exp
2575 | exp ',' expseq1
2576 ;
2577 @end group
2578 @end example
2579
2580 @noindent
2581 Any kind of sequence can be defined using either left recursion or right
2582 recursion, but you should always use left recursion, because it can
2583 parse a sequence of any number of elements with bounded stack space.
2584 Right recursion uses up space on the Bison stack in proportion to the
2585 number of elements in the sequence, because all the elements must be
2586 shifted onto the stack before the rule can be applied even once.
2587 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
2588 of this.
2589
2590 @cindex mutual recursion
2591 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
2592 rule does not appear directly on its right hand side, but does appear
2593 in rules for other nonterminals which do appear on its right hand
2594 side.
2595
2596 For example:
2597
2598 @example
2599 @group
2600 expr: primary
2601 | primary '+' primary
2602 ;
2603 @end group
2604
2605 @group
2606 primary: constant
2607 | '(' expr ')'
2608 ;
2609 @end group
2610 @end example
2611
2612 @noindent
2613 defines two mutually-recursive nonterminals, since each refers to the
2614 other.
2615
2616 @node Semantics
2617 @section Defining Language Semantics
2618 @cindex defining language semantics
2619 @cindex language semantics, defining
2620
2621 The grammar rules for a language determine only the syntax. The semantics
2622 are determined by the semantic values associated with various tokens and
2623 groupings, and by the actions taken when various groupings are recognized.
2624
2625 For example, the calculator calculates properly because the value
2626 associated with each expression is the proper number; it adds properly
2627 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
2628 the numbers associated with @var{x} and @var{y}.
2629
2630 @menu
2631 * Value Type:: Specifying one data type for all semantic values.
2632 * Multiple Types:: Specifying several alternative data types.
2633 * Actions:: An action is the semantic definition of a grammar rule.
2634 * Action Types:: Specifying data types for actions to operate on.
2635 * Mid-Rule Actions:: Most actions go at the end of a rule.
2636 This says when, why and how to use the exceptional
2637 action in the middle of a rule.
2638 @end menu
2639
2640 @node Value Type
2641 @subsection Data Types of Semantic Values
2642 @cindex semantic value type
2643 @cindex value type, semantic
2644 @cindex data types of semantic values
2645 @cindex default data type
2646
2647 In a simple program it may be sufficient to use the same data type for
2648 the semantic values of all language constructs. This was true in the
2649 @acronym{RPN} and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
2650 Notation Calculator}).
2651
2652 Bison's default is to use type @code{int} for all semantic values. To
2653 specify some other type, define @code{YYSTYPE} as a macro, like this:
2654
2655 @example
2656 #define YYSTYPE double
2657 @end example
2658
2659 @noindent
2660 This macro definition must go in the prologue of the grammar file
2661 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
2662
2663 @node Multiple Types
2664 @subsection More Than One Value Type
2665
2666 In most programs, you will need different data types for different kinds
2667 of tokens and groupings. For example, a numeric constant may need type
2668 @code{int} or @code{long}, while a string constant needs type @code{char *},
2669 and an identifier might need a pointer to an entry in the symbol table.
2670
2671 To use more than one data type for semantic values in one parser, Bison
2672 requires you to do two things:
2673
2674 @itemize @bullet
2675 @item
2676 Specify the entire collection of possible data types, with the
2677 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
2678 Value Types}).
2679
2680 @item
2681 Choose one of those types for each symbol (terminal or nonterminal) for
2682 which semantic values are used. This is done for tokens with the
2683 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
2684 and for groupings with the @code{%type} Bison declaration (@pxref{Type
2685 Decl, ,Nonterminal Symbols}).
2686 @end itemize
2687
2688 @node Actions
2689 @subsection Actions
2690 @cindex action
2691 @vindex $$
2692 @vindex $@var{n}
2693
2694 An action accompanies a syntactic rule and contains C code to be executed
2695 each time an instance of that rule is recognized. The task of most actions
2696 is to compute a semantic value for the grouping built by the rule from the
2697 semantic values associated with tokens or smaller groupings.
2698
2699 An action consists of C statements surrounded by braces, much like a
2700 compound statement in C@. An action can contain any sequence of C
2701 statements. Bison does not look for trigraphs, though, so if your C
2702 code uses trigraphs you should ensure that they do not affect the
2703 nesting of braces or the boundaries of comments, strings, or character
2704 literals.
2705
2706 An action can be placed at any position in the rule;
2707 it is executed at that position. Most rules have just one action at the
2708 end of the rule, following all the components. Actions in the middle of
2709 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
2710 Actions, ,Actions in Mid-Rule}).
2711
2712 The C code in an action can refer to the semantic values of the components
2713 matched by the rule with the construct @code{$@var{n}}, which stands for
2714 the value of the @var{n}th component. The semantic value for the grouping
2715 being constructed is @code{$$}. (Bison translates both of these constructs
2716 into array element references when it copies the actions into the parser
2717 file.)
2718
2719 Here is a typical example:
2720
2721 @example
2722 @group
2723 exp: @dots{}
2724 | exp '+' exp
2725 @{ $$ = $1 + $3; @}
2726 @end group
2727 @end example
2728
2729 @noindent
2730 This rule constructs an @code{exp} from two smaller @code{exp} groupings
2731 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
2732 refer to the semantic values of the two component @code{exp} groupings,
2733 which are the first and third symbols on the right hand side of the rule.
2734 The sum is stored into @code{$$} so that it becomes the semantic value of
2735 the addition-expression just recognized by the rule. If there were a
2736 useful semantic value associated with the @samp{+} token, it could be
2737 referred to as @code{$2}.
2738
2739 Note that the vertical-bar character @samp{|} is really a rule
2740 separator, and actions are attached to a single rule. This is a
2741 difference with tools like Flex, for which @samp{|} stands for either
2742 ``or'', or ``the same action as that of the next rule''. In the
2743 following example, the action is triggered only when @samp{b} is found:
2744
2745 @example
2746 @group
2747 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
2748 @end group
2749 @end example
2750
2751 @cindex default action
2752 If you don't specify an action for a rule, Bison supplies a default:
2753 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule
2754 becomes the value of the whole rule. Of course, the default action is
2755 valid only if the two data types match. There is no meaningful default
2756 action for an empty rule; every empty rule must have an explicit action
2757 unless the rule's value does not matter.
2758
2759 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
2760 to tokens and groupings on the stack @emph{before} those that match the
2761 current rule. This is a very risky practice, and to use it reliably
2762 you must be certain of the context in which the rule is applied. Here
2763 is a case in which you can use this reliably:
2764
2765 @example
2766 @group
2767 foo: expr bar '+' expr @{ @dots{} @}
2768 | expr bar '-' expr @{ @dots{} @}
2769 ;
2770 @end group
2771
2772 @group
2773 bar: /* empty */
2774 @{ previous_expr = $0; @}
2775 ;
2776 @end group
2777 @end example
2778
2779 As long as @code{bar} is used only in the fashion shown here, @code{$0}
2780 always refers to the @code{expr} which precedes @code{bar} in the
2781 definition of @code{foo}.
2782
2783 @node Action Types
2784 @subsection Data Types of Values in Actions
2785 @cindex action data types
2786 @cindex data types in actions
2787
2788 If you have chosen a single data type for semantic values, the @code{$$}
2789 and @code{$@var{n}} constructs always have that data type.
2790
2791 If you have used @code{%union} to specify a variety of data types, then you
2792 must declare a choice among these types for each terminal or nonterminal
2793 symbol that can have a semantic value. Then each time you use @code{$$} or
2794 @code{$@var{n}}, its data type is determined by which symbol it refers to
2795 in the rule. In this example,
2796
2797 @example
2798 @group
2799 exp: @dots{}
2800 | exp '+' exp
2801 @{ $$ = $1 + $3; @}
2802 @end group
2803 @end example
2804
2805 @noindent
2806 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
2807 have the data type declared for the nonterminal symbol @code{exp}. If
2808 @code{$2} were used, it would have the data type declared for the
2809 terminal symbol @code{'+'}, whatever that might be.
2810
2811 Alternatively, you can specify the data type when you refer to the value,
2812 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
2813 reference. For example, if you have defined types as shown here:
2814
2815 @example
2816 @group
2817 %union @{
2818 int itype;
2819 double dtype;
2820 @}
2821 @end group
2822 @end example
2823
2824 @noindent
2825 then you can write @code{$<itype>1} to refer to the first subunit of the
2826 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
2827
2828 @node Mid-Rule Actions
2829 @subsection Actions in Mid-Rule
2830 @cindex actions in mid-rule
2831 @cindex mid-rule actions
2832
2833 Occasionally it is useful to put an action in the middle of a rule.
2834 These actions are written just like usual end-of-rule actions, but they
2835 are executed before the parser even recognizes the following components.
2836
2837 A mid-rule action may refer to the components preceding it using
2838 @code{$@var{n}}, but it may not refer to subsequent components because
2839 it is run before they are parsed.
2840
2841 The mid-rule action itself counts as one of the components of the rule.
2842 This makes a difference when there is another action later in the same rule
2843 (and usually there is another at the end): you have to count the actions
2844 along with the symbols when working out which number @var{n} to use in
2845 @code{$@var{n}}.
2846
2847 The mid-rule action can also have a semantic value. The action can set
2848 its value with an assignment to @code{$$}, and actions later in the rule
2849 can refer to the value using @code{$@var{n}}. Since there is no symbol
2850 to name the action, there is no way to declare a data type for the value
2851 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
2852 specify a data type each time you refer to this value.
2853
2854 There is no way to set the value of the entire rule with a mid-rule
2855 action, because assignments to @code{$$} do not have that effect. The
2856 only way to set the value for the entire rule is with an ordinary action
2857 at the end of the rule.
2858
2859 Here is an example from a hypothetical compiler, handling a @code{let}
2860 statement that looks like @samp{let (@var{variable}) @var{statement}} and
2861 serves to create a variable named @var{variable} temporarily for the
2862 duration of @var{statement}. To parse this construct, we must put
2863 @var{variable} into the symbol table while @var{statement} is parsed, then
2864 remove it afterward. Here is how it is done:
2865
2866 @example
2867 @group
2868 stmt: LET '(' var ')'
2869 @{ $<context>$ = push_context ();
2870 declare_variable ($3); @}
2871 stmt @{ $$ = $6;
2872 pop_context ($<context>5); @}
2873 @end group
2874 @end example
2875
2876 @noindent
2877 As soon as @samp{let (@var{variable})} has been recognized, the first
2878 action is run. It saves a copy of the current semantic context (the
2879 list of accessible variables) as its semantic value, using alternative
2880 @code{context} in the data-type union. Then it calls
2881 @code{declare_variable} to add the new variable to that list. Once the
2882 first action is finished, the embedded statement @code{stmt} can be
2883 parsed. Note that the mid-rule action is component number 5, so the
2884 @samp{stmt} is component number 6.
2885
2886 After the embedded statement is parsed, its semantic value becomes the
2887 value of the entire @code{let}-statement. Then the semantic value from the
2888 earlier action is used to restore the prior list of variables. This
2889 removes the temporary @code{let}-variable from the list so that it won't
2890 appear to exist while the rest of the program is parsed.
2891
2892 Taking action before a rule is completely recognized often leads to
2893 conflicts since the parser must commit to a parse in order to execute the
2894 action. For example, the following two rules, without mid-rule actions,
2895 can coexist in a working parser because the parser can shift the open-brace
2896 token and look at what follows before deciding whether there is a
2897 declaration or not:
2898
2899 @example
2900 @group
2901 compound: '@{' declarations statements '@}'
2902 | '@{' statements '@}'
2903 ;
2904 @end group
2905 @end example
2906
2907 @noindent
2908 But when we add a mid-rule action as follows, the rules become nonfunctional:
2909
2910 @example
2911 @group
2912 compound: @{ prepare_for_local_variables (); @}
2913 '@{' declarations statements '@}'
2914 @end group
2915 @group
2916 | '@{' statements '@}'
2917 ;
2918 @end group
2919 @end example
2920
2921 @noindent
2922 Now the parser is forced to decide whether to run the mid-rule action
2923 when it has read no farther than the open-brace. In other words, it
2924 must commit to using one rule or the other, without sufficient
2925 information to do it correctly. (The open-brace token is what is called
2926 the @dfn{look-ahead} token at this time, since the parser is still
2927 deciding what to do about it. @xref{Look-Ahead, ,Look-Ahead Tokens}.)
2928
2929 You might think that you could correct the problem by putting identical
2930 actions into the two rules, like this:
2931
2932 @example
2933 @group
2934 compound: @{ prepare_for_local_variables (); @}
2935 '@{' declarations statements '@}'
2936 | @{ prepare_for_local_variables (); @}
2937 '@{' statements '@}'
2938 ;
2939 @end group
2940 @end example
2941
2942 @noindent
2943 But this does not help, because Bison does not realize that the two actions
2944 are identical. (Bison never tries to understand the C code in an action.)
2945
2946 If the grammar is such that a declaration can be distinguished from a
2947 statement by the first token (which is true in C), then one solution which
2948 does work is to put the action after the open-brace, like this:
2949
2950 @example
2951 @group
2952 compound: '@{' @{ prepare_for_local_variables (); @}
2953 declarations statements '@}'
2954 | '@{' statements '@}'
2955 ;
2956 @end group
2957 @end example
2958
2959 @noindent
2960 Now the first token of the following declaration or statement,
2961 which would in any case tell Bison which rule to use, can still do so.
2962
2963 Another solution is to bury the action inside a nonterminal symbol which
2964 serves as a subroutine:
2965
2966 @example
2967 @group
2968 subroutine: /* empty */
2969 @{ prepare_for_local_variables (); @}
2970 ;
2971
2972 @end group
2973
2974 @group
2975 compound: subroutine
2976 '@{' declarations statements '@}'
2977 | subroutine
2978 '@{' statements '@}'
2979 ;
2980 @end group
2981 @end example
2982
2983 @noindent
2984 Now Bison can execute the action in the rule for @code{subroutine} without
2985 deciding which rule for @code{compound} it will eventually use. Note that
2986 the action is now at the end of its rule. Any mid-rule action can be
2987 converted to an end-of-rule action in this way, and this is what Bison
2988 actually does to implement mid-rule actions.
2989
2990 @node Locations
2991 @section Tracking Locations
2992 @cindex location
2993 @cindex textual position
2994 @cindex position, textual
2995
2996 Though grammar rules and semantic actions are enough to write a fully
2997 functional parser, it can be useful to process some additional information,
2998 especially symbol locations.
2999
3000 @c (terminal or not) ?
3001
3002 The way locations are handled is defined by providing a data type, and
3003 actions to take when rules are matched.
3004
3005 @menu
3006 * Location Type:: Specifying a data type for locations.
3007 * Actions and Locations:: Using locations in actions.
3008 * Location Default Action:: Defining a general way to compute locations.
3009 @end menu
3010
3011 @node Location Type
3012 @subsection Data Type of Locations
3013 @cindex data type of locations
3014 @cindex default location type
3015
3016 Defining a data type for locations is much simpler than for semantic values,
3017 since all tokens and groupings always use the same type.
3018
3019 The type of locations is specified by defining a macro called @code{YYLTYPE}.
3020 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3021 four members:
3022
3023 @example
3024 struct
3025 @{
3026 int first_line;
3027 int first_column;
3028 int last_line;
3029 int last_column;
3030 @}
3031 @end example
3032
3033 @node Actions and Locations
3034 @subsection Actions and Locations
3035 @cindex location actions
3036 @cindex actions, location
3037 @vindex @@$
3038 @vindex @@@var{n}
3039
3040 Actions are not only useful for defining language semantics, but also for
3041 describing the behavior of the output parser with locations.
3042
3043 The most obvious way for building locations of syntactic groupings is very
3044 similar to the way semantic values are computed. In a given rule, several
3045 constructs can be used to access the locations of the elements being matched.
3046 The location of the @var{n}th component of the right hand side is
3047 @code{@@@var{n}}, while the location of the left hand side grouping is
3048 @code{@@$}.
3049
3050 Here is a basic example using the default data type for locations:
3051
3052 @example
3053 @group
3054 exp: @dots{}
3055 | exp '/' exp
3056 @{
3057 @@$.first_column = @@1.first_column;
3058 @@$.first_line = @@1.first_line;
3059 @@$.last_column = @@3.last_column;
3060 @@$.last_line = @@3.last_line;
3061 if ($3)
3062 $$ = $1 / $3;
3063 else
3064 @{
3065 $$ = 1;
3066 printf("Division by zero, l%d,c%d-l%d,c%d",
3067 @@3.first_line, @@3.first_column,
3068 @@3.last_line, @@3.last_column);
3069 @}
3070 @}
3071 @end group
3072 @end example
3073
3074 As for semantic values, there is a default action for locations that is
3075 run each time a rule is matched. It sets the beginning of @code{@@$} to the
3076 beginning of the first symbol, and the end of @code{@@$} to the end of the
3077 last symbol.
3078
3079 With this default action, the location tracking can be fully automatic. The
3080 example above simply rewrites this way:
3081
3082 @example
3083 @group
3084 exp: @dots{}
3085 | exp '/' exp
3086 @{
3087 if ($3)
3088 $$ = $1 / $3;
3089 else
3090 @{
3091 $$ = 1;
3092 printf("Division by zero, l%d,c%d-l%d,c%d",
3093 @@3.first_line, @@3.first_column,
3094 @@3.last_line, @@3.last_column);
3095 @}
3096 @}
3097 @end group
3098 @end example
3099
3100 @node Location Default Action
3101 @subsection Default Action for Locations
3102 @vindex YYLLOC_DEFAULT
3103
3104 Actually, actions are not the best place to compute locations. Since
3105 locations are much more general than semantic values, there is room in
3106 the output parser to redefine the default action to take for each
3107 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
3108 matched, before the associated action is run.
3109
3110 Most of the time, this macro is general enough to suppress location
3111 dedicated code from semantic actions.
3112
3113 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
3114 the location of the grouping (the result of the computation). The second one
3115 is an array holding locations of all right hand side elements of the rule
3116 being matched. The last one is the size of the right hand side rule.
3117
3118 By default, it is defined this way for simple @acronym{LALR}(1) parsers:
3119
3120 @example
3121 @group
3122 #define YYLLOC_DEFAULT(Current, Rhs, N) \
3123 Current.first_line = Rhs[1].first_line; \
3124 Current.first_column = Rhs[1].first_column; \
3125 Current.last_line = Rhs[N].last_line; \
3126 Current.last_column = Rhs[N].last_column;
3127 @end group
3128 @end example
3129
3130 @noindent
3131 and like this for @acronym{GLR} parsers:
3132
3133 @example
3134 @group
3135 #define YYLLOC_DEFAULT(Current, Rhs, N) \
3136 Current.first_line = YYRHSLOC(Rhs,1).first_line; \
3137 Current.first_column = YYRHSLOC(Rhs,1).first_column; \
3138 Current.last_line = YYRHSLOC(Rhs,N).last_line; \
3139 Current.last_column = YYRHSLOC(Rhs,N).last_column;
3140 @end group
3141 @end example
3142
3143 When defining @code{YYLLOC_DEFAULT}, you should consider that:
3144
3145 @itemize @bullet
3146 @item
3147 All arguments are free of side-effects. However, only the first one (the
3148 result) should be modified by @code{YYLLOC_DEFAULT}.
3149
3150 @item
3151 For consistency with semantic actions, valid indexes for the location
3152 array range from 1 to @var{n}.
3153 @end itemize
3154
3155 @node Declarations
3156 @section Bison Declarations
3157 @cindex declarations, Bison
3158 @cindex Bison declarations
3159
3160 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
3161 used in formulating the grammar and the data types of semantic values.
3162 @xref{Symbols}.
3163
3164 All token type names (but not single-character literal tokens such as
3165 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
3166 declared if you need to specify which data type to use for the semantic
3167 value (@pxref{Multiple Types, ,More Than One Value Type}).
3168
3169 The first rule in the file also specifies the start symbol, by default.
3170 If you want some other symbol to be the start symbol, you must declare
3171 it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free
3172 Grammars}).
3173
3174 @menu
3175 * Token Decl:: Declaring terminal symbols.
3176 * Precedence Decl:: Declaring terminals with precedence and associativity.
3177 * Union Decl:: Declaring the set of all semantic value types.
3178 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
3179 * Destructor Decl:: Declaring how symbols are freed.
3180 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
3181 * Start Decl:: Specifying the start symbol.
3182 * Pure Decl:: Requesting a reentrant parser.
3183 * Decl Summary:: Table of all Bison declarations.
3184 @end menu
3185
3186 @node Token Decl
3187 @subsection Token Type Names
3188 @cindex declaring token type names
3189 @cindex token type names, declaring
3190 @cindex declaring literal string tokens
3191 @findex %token
3192
3193 The basic way to declare a token type name (terminal symbol) is as follows:
3194
3195 @example
3196 %token @var{name}
3197 @end example
3198
3199 Bison will convert this into a @code{#define} directive in
3200 the parser, so that the function @code{yylex} (if it is in this file)
3201 can use the name @var{name} to stand for this token type's code.
3202
3203 Alternatively, you can use @code{%left}, @code{%right}, or
3204 @code{%nonassoc} instead of @code{%token}, if you wish to specify
3205 associativity and precedence. @xref{Precedence Decl, ,Operator
3206 Precedence}.
3207
3208 You can explicitly specify the numeric code for a token type by appending
3209 an integer value in the field immediately following the token name:
3210
3211 @example
3212 %token NUM 300
3213 @end example
3214
3215 @noindent
3216 It is generally best, however, to let Bison choose the numeric codes for
3217 all token types. Bison will automatically select codes that don't conflict
3218 with each other or with normal characters.
3219
3220 In the event that the stack type is a union, you must augment the
3221 @code{%token} or other token declaration to include the data type
3222 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
3223 Than One Value Type}).
3224
3225 For example:
3226
3227 @example
3228 @group
3229 %union @{ /* define stack type */
3230 double val;
3231 symrec *tptr;
3232 @}
3233 %token <val> NUM /* define token NUM and its type */
3234 @end group
3235 @end example
3236
3237 You can associate a literal string token with a token type name by
3238 writing the literal string at the end of a @code{%token}
3239 declaration which declares the name. For example:
3240
3241 @example
3242 %token arrow "=>"
3243 @end example
3244
3245 @noindent
3246 For example, a grammar for the C language might specify these names with
3247 equivalent literal string tokens:
3248
3249 @example
3250 %token <operator> OR "||"
3251 %token <operator> LE 134 "<="
3252 %left OR "<="
3253 @end example
3254
3255 @noindent
3256 Once you equate the literal string and the token name, you can use them
3257 interchangeably in further declarations or the grammar rules. The
3258 @code{yylex} function can use the token name or the literal string to
3259 obtain the token type code number (@pxref{Calling Convention}).
3260
3261 @node Precedence Decl
3262 @subsection Operator Precedence
3263 @cindex precedence declarations
3264 @cindex declaring operator precedence
3265 @cindex operator precedence, declaring
3266
3267 Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
3268 declare a token and specify its precedence and associativity, all at
3269 once. These are called @dfn{precedence declarations}.
3270 @xref{Precedence, ,Operator Precedence}, for general information on
3271 operator precedence.
3272
3273 The syntax of a precedence declaration is the same as that of
3274 @code{%token}: either
3275
3276 @example
3277 %left @var{symbols}@dots{}
3278 @end example
3279
3280 @noindent
3281 or
3282
3283 @example
3284 %left <@var{type}> @var{symbols}@dots{}
3285 @end example
3286
3287 And indeed any of these declarations serves the purposes of @code{%token}.
3288 But in addition, they specify the associativity and relative precedence for
3289 all the @var{symbols}:
3290
3291 @itemize @bullet
3292 @item
3293 The associativity of an operator @var{op} determines how repeated uses
3294 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
3295 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
3296 grouping @var{y} with @var{z} first. @code{%left} specifies
3297 left-associativity (grouping @var{x} with @var{y} first) and
3298 @code{%right} specifies right-associativity (grouping @var{y} with
3299 @var{z} first). @code{%nonassoc} specifies no associativity, which
3300 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
3301 considered a syntax error.
3302
3303 @item
3304 The precedence of an operator determines how it nests with other operators.
3305 All the tokens declared in a single precedence declaration have equal
3306 precedence and nest together according to their associativity.
3307 When two tokens declared in different precedence declarations associate,
3308 the one declared later has the higher precedence and is grouped first.
3309 @end itemize
3310
3311 @node Union Decl
3312 @subsection The Collection of Value Types
3313 @cindex declaring value types
3314 @cindex value types, declaring
3315 @findex %union
3316
3317 The @code{%union} declaration specifies the entire collection of possible
3318 data types for semantic values. The keyword @code{%union} is followed by a
3319 pair of braces containing the same thing that goes inside a @code{union} in
3320 C.
3321
3322 For example:
3323
3324 @example
3325 @group
3326 %union @{
3327 double val;
3328 symrec *tptr;
3329 @}
3330 @end group
3331 @end example
3332
3333 @noindent
3334 This says that the two alternative types are @code{double} and @code{symrec
3335 *}. They are given names @code{val} and @code{tptr}; these names are used
3336 in the @code{%token} and @code{%type} declarations to pick one of the types
3337 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
3338
3339 Note that, unlike making a @code{union} declaration in C, you do not write
3340 a semicolon after the closing brace.
3341
3342 @node Type Decl
3343 @subsection Nonterminal Symbols
3344 @cindex declaring value types, nonterminals
3345 @cindex value types, nonterminals, declaring
3346 @findex %type
3347
3348 @noindent
3349 When you use @code{%union} to specify multiple value types, you must
3350 declare the value type of each nonterminal symbol for which values are
3351 used. This is done with a @code{%type} declaration, like this:
3352
3353 @example
3354 %type <@var{type}> @var{nonterminal}@dots{}
3355 @end example
3356
3357 @noindent
3358 Here @var{nonterminal} is the name of a nonterminal symbol, and
3359 @var{type} is the name given in the @code{%union} to the alternative
3360 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
3361 can give any number of nonterminal symbols in the same @code{%type}
3362 declaration, if they have the same value type. Use spaces to separate
3363 the symbol names.
3364
3365 You can also declare the value type of a terminal symbol. To do this,
3366 use the same @code{<@var{type}>} construction in a declaration for the
3367 terminal symbol. All kinds of token declarations allow
3368 @code{<@var{type}>}.
3369
3370 @node Destructor Decl
3371 @subsection Freeing Discarded Symbols
3372 @cindex freeing discarded symbols
3373 @findex %destructor
3374
3375 Some symbols can be discarded by the parser, typically during error
3376 recovery (@pxref{Error Recovery}). Basically, during error recovery,
3377 embarrassing symbols already pushed on the stack, and embarrassing
3378 tokens coming from the rest of the file are thrown away until the parser
3379 falls on its feet. If these symbols convey heap based information, this
3380 memory is lost. While this behavior is tolerable for batch parsers,
3381 such as in compilers, it is unacceptable for parsers that can
3382 possibility ``never end'' such as shells, or implementations of
3383 communication protocols.
3384
3385 The @code{%destructor} directive allows for the definition of code that
3386 is called when a symbol is thrown away.
3387
3388 @deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
3389 @findex %destructor
3390 Declare that the @var{code} must be invoked for each of the
3391 @var{symbols} that will be discarded by the parser. The @var{code}
3392 should use @code{$$} to designate the semantic value associated to the
3393 @var{symbols}. The additional parser parameters are also avaible
3394 (@pxref{Parser Function, , The Parser Function @code{yyparse}}).
3395
3396 @strong{Warning:} as of Bison 1.875, this feature is still considered as
3397 experimental, as there was not enough users feedback. In particular,
3398 the syntax might still change.
3399 @end deffn
3400
3401 For instance:
3402
3403 @smallexample
3404 %union
3405 @{
3406 char *string;
3407 @}
3408 %token <string> STRING
3409 %type <string> string
3410 %destructor @{ free ($$); @} STRING string
3411 @end smallexample
3412
3413 @noindent
3414 guarantees that when a @code{STRING} or a @code{string} will be discarded,
3415 its associated memory will be freed.
3416
3417 Note that in the future, Bison might also consider that right hand side
3418 members that are not mentioned in the action can be destroyed. For
3419 instance, in:
3420
3421 @smallexample
3422 comment: "/*" STRING "*/";
3423 @end smallexample
3424
3425 @noindent
3426 the parser is entitled to destroy the semantic value of the
3427 @code{string}. Of course, this will not apply to the default action;
3428 compare:
3429
3430 @smallexample
3431 typeless: string; // $$ = $1 does not apply; $1 is destroyed.
3432 typefull: string; // $$ = $1 applies, $1 is not destroyed.
3433 @end smallexample
3434
3435 @node Expect Decl
3436 @subsection Suppressing Conflict Warnings
3437 @cindex suppressing conflict warnings
3438 @cindex preventing warnings about conflicts
3439 @cindex warnings, preventing
3440 @cindex conflicts, suppressing warnings of
3441 @findex %expect
3442
3443 Bison normally warns if there are any conflicts in the grammar
3444 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
3445 have harmless shift/reduce conflicts which are resolved in a predictable
3446 way and would be difficult to eliminate. It is desirable to suppress
3447 the warning about these conflicts unless the number of conflicts
3448 changes. You can do this with the @code{%expect} declaration.
3449
3450 The declaration looks like this:
3451
3452 @example
3453 %expect @var{n}
3454 @end example
3455
3456 Here @var{n} is a decimal integer. The declaration says there should be
3457 no warning if there are @var{n} shift/reduce conflicts and no
3458 reduce/reduce conflicts. An error, instead of the usual warning, is
3459 given if there are either more or fewer conflicts, or if there are any
3460 reduce/reduce conflicts.
3461
3462 In general, using @code{%expect} involves these steps:
3463
3464 @itemize @bullet
3465 @item
3466 Compile your grammar without @code{%expect}. Use the @samp{-v} option
3467 to get a verbose list of where the conflicts occur. Bison will also
3468 print the number of conflicts.
3469
3470 @item
3471 Check each of the conflicts to make sure that Bison's default
3472 resolution is what you really want. If not, rewrite the grammar and
3473 go back to the beginning.
3474
3475 @item
3476 Add an @code{%expect} declaration, copying the number @var{n} from the
3477 number which Bison printed.
3478 @end itemize
3479
3480 Now Bison will stop annoying you about the conflicts you have checked, but
3481 it will warn you again if changes in the grammar result in additional
3482 conflicts.
3483
3484 @node Start Decl
3485 @subsection The Start-Symbol
3486 @cindex declaring the start symbol
3487 @cindex start symbol, declaring
3488 @cindex default start symbol
3489 @findex %start
3490
3491 Bison assumes by default that the start symbol for the grammar is the first
3492 nonterminal specified in the grammar specification section. The programmer
3493 may override this restriction with the @code{%start} declaration as follows:
3494
3495 @example
3496 %start @var{symbol}
3497 @end example
3498
3499 @node Pure Decl
3500 @subsection A Pure (Reentrant) Parser
3501 @cindex reentrant parser
3502 @cindex pure parser
3503 @findex %pure-parser
3504
3505 A @dfn{reentrant} program is one which does not alter in the course of
3506 execution; in other words, it consists entirely of @dfn{pure} (read-only)
3507 code. Reentrancy is important whenever asynchronous execution is possible;
3508 for example, a non-reentrant program may not be safe to call from a signal
3509 handler. In systems with multiple threads of control, a non-reentrant
3510 program must be called only within interlocks.
3511
3512 Normally, Bison generates a parser which is not reentrant. This is
3513 suitable for most uses, and it permits compatibility with Yacc. (The
3514 standard Yacc interfaces are inherently nonreentrant, because they use
3515 statically allocated variables for communication with @code{yylex},
3516 including @code{yylval} and @code{yylloc}.)
3517
3518 Alternatively, you can generate a pure, reentrant parser. The Bison
3519 declaration @code{%pure-parser} says that you want the parser to be
3520 reentrant. It looks like this:
3521
3522 @example
3523 %pure-parser
3524 @end example
3525
3526 The result is that the communication variables @code{yylval} and
3527 @code{yylloc} become local variables in @code{yyparse}, and a different
3528 calling convention is used for the lexical analyzer function
3529 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
3530 Parsers}, for the details of this. The variable @code{yynerrs} also
3531 becomes local in @code{yyparse} (@pxref{Error Reporting, ,The Error
3532 Reporting Function @code{yyerror}}). The convention for calling
3533 @code{yyparse} itself is unchanged.
3534
3535 Whether the parser is pure has nothing to do with the grammar rules.
3536 You can generate either a pure parser or a nonreentrant parser from any
3537 valid grammar.
3538
3539 @node Decl Summary
3540 @subsection Bison Declaration Summary
3541 @cindex Bison declaration summary
3542 @cindex declaration summary
3543 @cindex summary, Bison declaration
3544
3545 Here is a summary of the declarations used to define a grammar:
3546
3547 @table @code
3548 @item %union
3549 Declare the collection of data types that semantic values may have
3550 (@pxref{Union Decl, ,The Collection of Value Types}).
3551
3552 @item %token
3553 Declare a terminal symbol (token type name) with no precedence
3554 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
3555
3556 @item %right
3557 Declare a terminal symbol (token type name) that is right-associative
3558 (@pxref{Precedence Decl, ,Operator Precedence}).
3559
3560 @item %left
3561 Declare a terminal symbol (token type name) that is left-associative
3562 (@pxref{Precedence Decl, ,Operator Precedence}).
3563
3564 @item %nonassoc
3565 Declare a terminal symbol (token type name) that is nonassociative
3566 (using it in a way that would be associative is a syntax error)
3567 (@pxref{Precedence Decl, ,Operator Precedence}).
3568
3569 @item %type
3570 Declare the type of semantic values for a nonterminal symbol
3571 (@pxref{Type Decl, ,Nonterminal Symbols}).
3572
3573 @item %start
3574 Specify the grammar's start symbol (@pxref{Start Decl, ,The
3575 Start-Symbol}).
3576
3577 @item %expect
3578 Declare the expected number of shift-reduce conflicts
3579 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
3580 @end table
3581
3582 @sp 1
3583 @noindent
3584 In order to change the behavior of @command{bison}, use the following
3585 directives:
3586
3587 @table @code
3588 @item %debug
3589 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
3590 already defined, so that the debugging facilities are compiled.
3591 @xref{Tracing, ,Tracing Your Parser}.
3592
3593 @item %defines
3594 Write an extra output file containing macro definitions for the token
3595 type names defined in the grammar and the semantic value type
3596 @code{YYSTYPE}, as well as a few @code{extern} variable declarations.
3597
3598 If the parser output file is named @file{@var{name}.c} then this file
3599 is named @file{@var{name}.h}.
3600
3601 This output file is essential if you wish to put the definition of
3602 @code{yylex} in a separate source file, because @code{yylex} needs to
3603 be able to refer to token type codes and the variable
3604 @code{yylval}. @xref{Token Values, ,Semantic Values of Tokens}.
3605
3606 @item %destructor
3607 Specifying how the parser should reclaim the memory associated to
3608 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
3609
3610 @item %file-prefix="@var{prefix}"
3611 Specify a prefix to use for all Bison output file names. The names are
3612 chosen as if the input file were named @file{@var{prefix}.y}.
3613
3614 @c @item %header-extension
3615 @c Specify the extension of the parser header file generated when
3616 @c @code{%define} or @samp{-d} are used.
3617 @c
3618 @c For example, a grammar file named @file{foo.ypp} and containing a
3619 @c @code{%header-extension .hh} directive will produce a header file
3620 @c named @file{foo.tab.hh}
3621
3622 @item %locations
3623 Generate the code processing the locations (@pxref{Action Features,
3624 ,Special Features for Use in Actions}). This mode is enabled as soon as
3625 the grammar uses the special @samp{@@@var{n}} tokens, but if your
3626 grammar does not use it, using @samp{%locations} allows for more
3627 accurate parse error messages.
3628
3629 @item %name-prefix="@var{prefix}"
3630 Rename the external symbols used in the parser so that they start with
3631 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
3632 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
3633 @code{yylval}, @code{yylloc}, @code{yychar}, @code{yydebug}, and
3634 possible @code{yylloc}. For example, if you use
3635 @samp{%name-prefix="c_"}, the names become @code{c_parse}, @code{c_lex},
3636 and so on. @xref{Multiple Parsers, ,Multiple Parsers in the Same
3637 Program}.
3638
3639 @item %no-parser
3640 Do not include any C code in the parser file; generate tables only. The
3641 parser file contains just @code{#define} directives and static variable
3642 declarations.
3643
3644 This option also tells Bison to write the C code for the grammar actions
3645 into a file named @file{@var{filename}.act}, in the form of a
3646 brace-surrounded body fit for a @code{switch} statement.
3647
3648 @item %no-lines
3649 Don't generate any @code{#line} preprocessor commands in the parser
3650 file. Ordinarily Bison writes these commands in the parser file so that
3651 the C compiler and debuggers will associate errors and object code with
3652 your source file (the grammar file). This directive causes them to
3653 associate errors with the parser file, treating it an independent source
3654 file in its own right.
3655
3656 @item %output="@var{filename}"
3657 Specify the @var{filename} for the parser file.
3658
3659 @item %pure-parser
3660 Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure
3661 (Reentrant) Parser}).
3662
3663 @c @item %source-extension
3664 @c Specify the extension of the parser output file.
3665 @c
3666 @c For example, a grammar file named @file{foo.yy} and containing a
3667 @c @code{%source-extension .cpp} directive will produce a parser file
3668 @c named @file{foo.tab.cpp}
3669
3670 @item %token-table
3671 Generate an array of token names in the parser file. The name of the
3672 array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
3673 token whose internal Bison token code number is @var{i}. The first
3674 three elements of @code{yytname} are always @code{"$end"},
3675 @code{"error"}, and @code{"$undefined"}; after these come the symbols
3676 defined in the grammar file.
3677
3678 For single-character literal tokens and literal string tokens, the name
3679 in the table includes the single-quote or double-quote characters: for
3680 example, @code{"'+'"} is a single-character literal and @code{"\"<=\""}
3681 is a literal string token. All the characters of the literal string
3682 token appear verbatim in the string found in the table; even
3683 double-quote characters are not escaped. For example, if the token
3684 consists of three characters @samp{*"*}, its string in @code{yytname}
3685 contains @samp{"*"*"}. (In C, that would be written as
3686 @code{"\"*\"*\""}).
3687
3688 When you specify @code{%token-table}, Bison also generates macro
3689 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
3690 @code{YYNRULES}, and @code{YYNSTATES}:
3691
3692 @table @code
3693 @item YYNTOKENS
3694 The highest token number, plus one.
3695 @item YYNNTS
3696 The number of nonterminal symbols.
3697 @item YYNRULES
3698 The number of grammar rules,
3699 @item YYNSTATES
3700 The number of parser states (@pxref{Parser States}).
3701 @end table
3702
3703 @item %verbose
3704 Write an extra output file containing verbose descriptions of the
3705 parser states and what is done for each type of look-ahead token in
3706 that state. @xref{Understanding, , Understanding Your Parser}, for more
3707 information.
3708
3709 @item %yacc
3710 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
3711 including its naming conventions. @xref{Bison Options}, for more.
3712 @end table
3713
3714
3715
3716
3717 @node Multiple Parsers
3718 @section Multiple Parsers in the Same Program
3719
3720 Most programs that use Bison parse only one language and therefore contain
3721 only one Bison parser. But what if you want to parse more than one
3722 language with the same program? Then you need to avoid a name conflict
3723 between different definitions of @code{yyparse}, @code{yylval}, and so on.
3724
3725 The easy way to do this is to use the option @samp{-p @var{prefix}}
3726 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
3727 functions and variables of the Bison parser to start with @var{prefix}
3728 instead of @samp{yy}. You can use this to give each parser distinct
3729 names that do not conflict.
3730
3731 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
3732 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
3733 @code{yychar} and @code{yydebug}. For example, if you use @samp{-p c},
3734 the names become @code{cparse}, @code{clex}, and so on.
3735
3736 @strong{All the other variables and macros associated with Bison are not
3737 renamed.} These others are not global; there is no conflict if the same
3738 name is used in different parsers. For example, @code{YYSTYPE} is not
3739 renamed, but defining this in different ways in different parsers causes
3740 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
3741
3742 The @samp{-p} option works by adding macro definitions to the beginning
3743 of the parser source file, defining @code{yyparse} as
3744 @code{@var{prefix}parse}, and so on. This effectively substitutes one
3745 name for the other in the entire parser file.
3746
3747 @node Interface
3748 @chapter Parser C-Language Interface
3749 @cindex C-language interface
3750 @cindex interface
3751
3752 The Bison parser is actually a C function named @code{yyparse}. Here we
3753 describe the interface conventions of @code{yyparse} and the other
3754 functions that it needs to use.
3755
3756 Keep in mind that the parser uses many C identifiers starting with
3757 @samp{yy} and @samp{YY} for internal purposes. If you use such an
3758 identifier (aside from those in this manual) in an action or in epilogue
3759 in the grammar file, you are likely to run into trouble.
3760
3761 @menu
3762 * Parser Function:: How to call @code{yyparse} and what it returns.
3763 * Lexical:: You must supply a function @code{yylex}
3764 which reads tokens.
3765 * Error Reporting:: You must supply a function @code{yyerror}.
3766 * Action Features:: Special features for use in actions.
3767 @end menu
3768
3769 @node Parser Function
3770 @section The Parser Function @code{yyparse}
3771 @findex yyparse
3772
3773 You call the function @code{yyparse} to cause parsing to occur. This
3774 function reads tokens, executes actions, and ultimately returns when it
3775 encounters end-of-input or an unrecoverable syntax error. You can also
3776 write an action which directs @code{yyparse} to return immediately
3777 without reading further.
3778
3779
3780 @deftypefun int yyparse (void)
3781 The value returned by @code{yyparse} is 0 if parsing was successful (return
3782 is due to end-of-input).
3783
3784 The value is 1 if parsing failed (return is due to a syntax error).
3785 @end deftypefun
3786
3787 In an action, you can cause immediate return from @code{yyparse} by using
3788 these macros:
3789
3790 @defmac YYACCEPT
3791 @findex YYACCEPT
3792 Return immediately with value 0 (to report success).
3793 @end defmac
3794
3795 @defmac YYABORT
3796 @findex YYABORT
3797 Return immediately with value 1 (to report failure).
3798 @end defmac
3799
3800 If you use a reentrant parser, you can optionally pass additional
3801 parameter information to it in a reentrant way. To do so, use the
3802 declaration @code{%parse-param}:
3803
3804 @deffn {Directive} %parse-param @var{argument-declaration} @var{argument-name}
3805 @findex %parse-param
3806 Declare that @code{argument-name} is an additional @code{yyparse}
3807 argument. This argument is also passed to @code{yyerror}. The
3808 @var{argument-declaration} is used when declaring functions or
3809 prototypes.
3810 @end deffn
3811
3812 Here's an example. Write this in the parser:
3813
3814 @example
3815 %parse-param "int *nastiness" "nastiness"
3816 %parse-param "int *randomness" "randomness"
3817 @end example
3818
3819 @noindent
3820 Then call the parser like this:
3821
3822 @example
3823 @{
3824 int nastiness, randomness;
3825 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
3826 value = yyparse (&nastiness, &randomness);
3827 @dots{}
3828 @}
3829 @end example
3830
3831 @noindent
3832 In the grammar actions, use expressions like this to refer to the data:
3833
3834 @example
3835 exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
3836 @end example
3837
3838
3839 @node Lexical
3840 @section The Lexical Analyzer Function @code{yylex}
3841 @findex yylex
3842 @cindex lexical analyzer
3843
3844 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
3845 the input stream and returns them to the parser. Bison does not create
3846 this function automatically; you must write it so that @code{yyparse} can
3847 call it. The function is sometimes referred to as a lexical scanner.
3848
3849 In simple programs, @code{yylex} is often defined at the end of the Bison
3850 grammar file. If @code{yylex} is defined in a separate source file, you
3851 need to arrange for the token-type macro definitions to be available there.
3852 To do this, use the @samp{-d} option when you run Bison, so that it will
3853 write these macro definitions into a separate header file
3854 @file{@var{name}.tab.h} which you can include in the other source files
3855 that need it. @xref{Invocation, ,Invoking Bison}.
3856
3857 @menu
3858 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
3859 * Token Values:: How @code{yylex} must return the semantic value
3860 of the token it has read.
3861 * Token Positions:: How @code{yylex} must return the text position
3862 (line number, etc.) of the token, if the
3863 actions want that.
3864 * Pure Calling:: How the calling convention differs
3865 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
3866 @end menu
3867
3868 @node Calling Convention
3869 @subsection Calling Convention for @code{yylex}
3870
3871 The value that @code{yylex} returns must be the positive numeric code
3872 for the type of token it has just found; a zero or negative value
3873 signifies end-of-input.
3874
3875 When a token is referred to in the grammar rules by a name, that name
3876 in the parser file becomes a C macro whose definition is the proper
3877 numeric code for that token type. So @code{yylex} can use the name
3878 to indicate that type. @xref{Symbols}.
3879
3880 When a token is referred to in the grammar rules by a character literal,
3881 the numeric code for that character is also the code for the token type.
3882 So @code{yylex} can simply return that character code, possibly converted
3883 to @code{unsigned char} to avoid sign-extension. The null character
3884 must not be used this way, because its code is zero and that
3885 signifies end-of-input.
3886
3887 Here is an example showing these things:
3888
3889 @example
3890 int
3891 yylex (void)
3892 @{
3893 @dots{}
3894 if (c == EOF) /* Detect end-of-input. */
3895 return 0;
3896 @dots{}
3897 if (c == '+' || c == '-')
3898 return c; /* Assume token type for `+' is '+'. */
3899 @dots{}
3900 return INT; /* Return the type of the token. */
3901 @dots{}
3902 @}
3903 @end example
3904
3905 @noindent
3906 This interface has been designed so that the output from the @code{lex}
3907 utility can be used without change as the definition of @code{yylex}.
3908
3909 If the grammar uses literal string tokens, there are two ways that
3910 @code{yylex} can determine the token type codes for them:
3911
3912 @itemize @bullet
3913 @item
3914 If the grammar defines symbolic token names as aliases for the
3915 literal string tokens, @code{yylex} can use these symbolic names like
3916 all others. In this case, the use of the literal string tokens in
3917 the grammar file has no effect on @code{yylex}.
3918
3919 @item
3920 @code{yylex} can find the multicharacter token in the @code{yytname}
3921 table. The index of the token in the table is the token type's code.
3922 The name of a multicharacter token is recorded in @code{yytname} with a
3923 double-quote, the token's characters, and another double-quote. The
3924 token's characters are not escaped in any way; they appear verbatim in
3925 the contents of the string in the table.
3926
3927 Here's code for looking up a token in @code{yytname}, assuming that the
3928 characters of the token are stored in @code{token_buffer}.
3929
3930 @smallexample
3931 for (i = 0; i < YYNTOKENS; i++)
3932 @{
3933 if (yytname[i] != 0
3934 && yytname[i][0] == '"'
3935 && ! strncmp (yytname[i] + 1, token_buffer,
3936 strlen (token_buffer))
3937 && yytname[i][strlen (token_buffer) + 1] == '"'
3938 && yytname[i][strlen (token_buffer) + 2] == 0)
3939 break;
3940 @}
3941 @end smallexample
3942
3943 The @code{yytname} table is generated only if you use the
3944 @code{%token-table} declaration. @xref{Decl Summary}.
3945 @end itemize
3946
3947 @node Token Values
3948 @subsection Semantic Values of Tokens
3949
3950 @vindex yylval
3951 In an ordinary (non-reentrant) parser, the semantic value of the token must
3952 be stored into the global variable @code{yylval}. When you are using
3953 just one data type for semantic values, @code{yylval} has that type.
3954 Thus, if the type is @code{int} (the default), you might write this in
3955 @code{yylex}:
3956
3957 @example
3958 @group
3959 @dots{}
3960 yylval = value; /* Put value onto Bison stack. */
3961 return INT; /* Return the type of the token. */
3962 @dots{}
3963 @end group
3964 @end example
3965
3966 When you are using multiple data types, @code{yylval}'s type is a union
3967 made from the @code{%union} declaration (@pxref{Union Decl, ,The
3968 Collection of Value Types}). So when you store a token's value, you
3969 must use the proper member of the union. If the @code{%union}
3970 declaration looks like this:
3971
3972 @example
3973 @group
3974 %union @{
3975 int intval;
3976 double val;
3977 symrec *tptr;
3978 @}
3979 @end group
3980 @end example
3981
3982 @noindent
3983 then the code in @code{yylex} might look like this:
3984
3985 @example
3986 @group
3987 @dots{}
3988 yylval.intval = value; /* Put value onto Bison stack. */
3989 return INT; /* Return the type of the token. */
3990 @dots{}
3991 @end group
3992 @end example
3993
3994 @node Token Positions
3995 @subsection Textual Positions of Tokens
3996
3997 @vindex yylloc
3998 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
3999 Tracking Locations}) in actions to keep track of the
4000 textual locations of tokens and groupings, then you must provide this
4001 information in @code{yylex}. The function @code{yyparse} expects to
4002 find the textual location of a token just parsed in the global variable
4003 @code{yylloc}. So @code{yylex} must store the proper data in that
4004 variable.
4005
4006 By default, the value of @code{yylloc} is a structure and you need only
4007 initialize the members that are going to be used by the actions. The
4008 four members are called @code{first_line}, @code{first_column},
4009 @code{last_line} and @code{last_column}. Note that the use of this
4010 feature makes the parser noticeably slower.
4011
4012 @tindex YYLTYPE
4013 The data type of @code{yylloc} has the name @code{YYLTYPE}.
4014
4015 @node Pure Calling
4016 @subsection Calling Conventions for Pure Parsers
4017
4018 When you use the Bison declaration @code{%pure-parser} to request a
4019 pure, reentrant parser, the global communication variables @code{yylval}
4020 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
4021 Parser}.) In such parsers the two global variables are replaced by
4022 pointers passed as arguments to @code{yylex}. You must declare them as
4023 shown here, and pass the information back by storing it through those
4024 pointers.
4025
4026 @example
4027 int
4028 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
4029 @{
4030 @dots{}
4031 *lvalp = value; /* Put value onto Bison stack. */
4032 return INT; /* Return the type of the token. */
4033 @dots{}
4034 @}
4035 @end example
4036
4037 If the grammar file does not use the @samp{@@} constructs to refer to
4038 textual positions, then the type @code{YYLTYPE} will not be defined. In
4039 this case, omit the second argument; @code{yylex} will be called with
4040 only one argument.
4041
4042
4043 If you wish to pass the additional parameter data to @code{yylex}, use
4044 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
4045 Function}).
4046
4047 @deffn {Directive} lex-param @var{argument-declaration} @var{argument-name}
4048 @findex %lex-param
4049 Declare that @code{argument-name} is an additional @code{yylex}
4050 argument.
4051 @end deffn
4052
4053 For instance:
4054
4055 @example
4056 %parse-param "int *nastiness" "nastiness"
4057 %lex-param "int *nastiness" "nastiness"
4058 %parse-param "int *randomness" "randomness"
4059 @end example
4060
4061 @noindent
4062 results in the following signature:
4063
4064 @example
4065 int yylex (int *nastiness);
4066 int yyparse (int *nastiness, int *randomness);
4067 @end example
4068
4069 If @code{%pure-parser} is added:
4070
4071 @example
4072 int yylex (YYSTYPE *lvalp, int *nastiness);
4073 int yyparse (int *nastiness, int *randomness);
4074 @end example
4075
4076 @noindent
4077 and finally, if both @code{%pure-parser} and @code{%locations} are used:
4078
4079 @example
4080 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
4081 int yyparse (int *nastiness, int *randomness);
4082 @end example
4083
4084 @node Error Reporting
4085 @section The Error Reporting Function @code{yyerror}
4086 @cindex error reporting function
4087 @findex yyerror
4088 @cindex parse error
4089 @cindex syntax error
4090
4091 The Bison parser detects a @dfn{parse error} or @dfn{syntax error}
4092 whenever it reads a token which cannot satisfy any syntax rule. An
4093 action in the grammar can also explicitly proclaim an error, using the
4094 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
4095 in Actions}).
4096
4097 The Bison parser expects to report the error by calling an error
4098 reporting function named @code{yyerror}, which you must supply. It is
4099 called by @code{yyparse} whenever a syntax error is found, and it
4100 receives one argument. For a parse error, the string is normally
4101 @w{@code{"parse error"}}.
4102
4103 @findex %error-verbose
4104 If you invoke the directive @code{%error-verbose} in the Bison
4105 declarations section (@pxref{Bison Declarations, ,The Bison Declarations
4106 Section}), then Bison provides a more verbose and specific error message
4107 string instead of just plain @w{@code{"parse error"}}.
4108
4109 The parser can detect one other kind of error: stack overflow. This
4110 happens when the input contains constructions that are very deeply
4111 nested. It isn't likely you will encounter this, since the Bison
4112 parser extends its stack automatically up to a very large limit. But
4113 if overflow happens, @code{yyparse} calls @code{yyerror} in the usual
4114 fashion, except that the argument string is @w{@code{"parser stack
4115 overflow"}}.
4116
4117 The following definition suffices in simple programs:
4118
4119 @example
4120 @group
4121 void
4122 yyerror (const char *s)
4123 @{
4124 @end group
4125 @group
4126 fprintf (stderr, "%s\n", s);
4127 @}
4128 @end group
4129 @end example
4130
4131 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
4132 error recovery if you have written suitable error recovery grammar rules
4133 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
4134 immediately return 1.
4135
4136 Obviously, in location tracking pure parsers, @code{yyerror} should have
4137 an access to the current location. This is indeed the case for the GLR
4138 parsers, but not for the Yacc parser, for historical reasons. I.e., if
4139 @samp{%locations %pure-parser} is passed then the prototypes for
4140 @code{yyerror} are:
4141
4142 @example
4143 void yyerror (const char *msg); /* Yacc parsers. */
4144 void yyerror (YYLTYPE *locp, const char *msg); /* GLR parsers. */
4145 @end example
4146
4147 If @samp{%parse-param "int *nastiness" "nastiness"} is used, then:
4148
4149 @example
4150 void yyerror (int *randomness, const char *msg); /* Yacc parsers. */
4151 void yyerror (int *randomness, const char *msg); /* GLR parsers. */
4152 @end example
4153
4154 Finally, GLR and Yacc parsers share the same @code{yyerror} calling
4155 convention for absolutely pure parsers, i.e., when the calling
4156 convention of @code{yylex} @emph{and} the calling convention of
4157 @code{%pure-parser} are pure. I.e.:
4158
4159 @example
4160 /* Location tracking. */
4161 %locations
4162 /* Pure yylex. */
4163 %pure-parser
4164 %lex-param "int *nastiness" "nastiness"
4165 /* Pure yyparse. */
4166 %parse-param "int *nastiness" "nastiness"
4167 %parse-param "int *randomness" "randomness"
4168 @end example
4169
4170 @noindent
4171 results in the following signatures for all the parser kinds:
4172
4173 @example
4174 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
4175 int yyparse (int *nastiness, int *randomness);
4176 void yyerror (YYLTYPE *locp,
4177 int *nastiness, int *randomness,
4178 const char *msg);
4179 @end example
4180
4181 @noindent
4182 Please, note that the prototypes are only indications of how the code
4183 produced by Bison will use @code{yyerror}; you still have freedom on the
4184 exit value, and even on making @code{yyerror} a variadic function. It
4185 is precisely to enable this that the message is always passed last.
4186
4187 @vindex yynerrs
4188 The variable @code{yynerrs} contains the number of syntax errors
4189 encountered so far. Normally this variable is global; but if you
4190 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
4191 then it is a local variable which only the actions can access.
4192
4193 @node Action Features
4194 @section Special Features for Use in Actions
4195 @cindex summary, action features
4196 @cindex action features summary
4197
4198 Here is a table of Bison constructs, variables and macros that
4199 are useful in actions.
4200
4201 @table @samp
4202 @item $$
4203 Acts like a variable that contains the semantic value for the
4204 grouping made by the current rule. @xref{Actions}.
4205
4206 @item $@var{n}
4207 Acts like a variable that contains the semantic value for the
4208 @var{n}th component of the current rule. @xref{Actions}.
4209
4210 @item $<@var{typealt}>$
4211 Like @code{$$} but specifies alternative @var{typealt} in the union
4212 specified by the @code{%union} declaration. @xref{Action Types, ,Data
4213 Types of Values in Actions}.
4214
4215 @item $<@var{typealt}>@var{n}
4216 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
4217 union specified by the @code{%union} declaration.
4218 @xref{Action Types, ,Data Types of Values in Actions}.
4219
4220 @item YYABORT;
4221 Return immediately from @code{yyparse}, indicating failure.
4222 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
4223
4224 @item YYACCEPT;
4225 Return immediately from @code{yyparse}, indicating success.
4226 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
4227
4228 @item YYBACKUP (@var{token}, @var{value});
4229 @findex YYBACKUP
4230 Unshift a token. This macro is allowed only for rules that reduce
4231 a single value, and only when there is no look-ahead token.
4232 It is also disallowed in @acronym{GLR} parsers.
4233 It installs a look-ahead token with token type @var{token} and
4234 semantic value @var{value}; then it discards the value that was
4235 going to be reduced by this rule.
4236
4237 If the macro is used when it is not valid, such as when there is
4238 a look-ahead token already, then it reports a syntax error with
4239 a message @samp{cannot back up} and performs ordinary error
4240 recovery.
4241
4242 In either case, the rest of the action is not executed.
4243
4244 @item YYEMPTY
4245 @vindex YYEMPTY
4246 Value stored in @code{yychar} when there is no look-ahead token.
4247
4248 @item YYERROR;
4249 @findex YYERROR
4250 Cause an immediate syntax error. This statement initiates error
4251 recovery just as if the parser itself had detected an error; however, it
4252 does not call @code{yyerror}, and does not print any message. If you
4253 want to print an error message, call @code{yyerror} explicitly before
4254 the @samp{YYERROR;} statement. @xref{Error Recovery}.
4255
4256 @item YYRECOVERING
4257 This macro stands for an expression that has the value 1 when the parser
4258 is recovering from a syntax error, and 0 the rest of the time.
4259 @xref{Error Recovery}.
4260
4261 @item yychar
4262 Variable containing the current look-ahead token. (In a pure parser,
4263 this is actually a local variable within @code{yyparse}.) When there is
4264 no look-ahead token, the value @code{YYEMPTY} is stored in the variable.
4265 @xref{Look-Ahead, ,Look-Ahead Tokens}.
4266
4267 @item yyclearin;
4268 Discard the current look-ahead token. This is useful primarily in
4269 error rules. @xref{Error Recovery}.
4270
4271 @item yyerrok;
4272 Resume generating error messages immediately for subsequent syntax
4273 errors. This is useful primarily in error rules.
4274 @xref{Error Recovery}.
4275
4276 @item @@$
4277 @findex @@$
4278 Acts like a structure variable containing information on the textual position
4279 of the grouping made by the current rule. @xref{Locations, ,
4280 Tracking Locations}.
4281
4282 @c Check if those paragraphs are still useful or not.
4283
4284 @c @example
4285 @c struct @{
4286 @c int first_line, last_line;
4287 @c int first_column, last_column;
4288 @c @};
4289 @c @end example
4290
4291 @c Thus, to get the starting line number of the third component, you would
4292 @c use @samp{@@3.first_line}.
4293
4294 @c In order for the members of this structure to contain valid information,
4295 @c you must make @code{yylex} supply this information about each token.
4296 @c If you need only certain members, then @code{yylex} need only fill in
4297 @c those members.
4298
4299 @c The use of this feature makes the parser noticeably slower.
4300
4301 @item @@@var{n}
4302 @findex @@@var{n}
4303 Acts like a structure variable containing information on the textual position
4304 of the @var{n}th component of the current rule. @xref{Locations, ,
4305 Tracking Locations}.
4306
4307 @end table
4308
4309 @node Algorithm
4310 @chapter The Bison Parser Algorithm
4311 @cindex Bison parser algorithm
4312 @cindex algorithm of parser
4313 @cindex shifting
4314 @cindex reduction
4315 @cindex parser stack
4316 @cindex stack, parser
4317
4318 As Bison reads tokens, it pushes them onto a stack along with their
4319 semantic values. The stack is called the @dfn{parser stack}. Pushing a
4320 token is traditionally called @dfn{shifting}.
4321
4322 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
4323 @samp{3} to come. The stack will have four elements, one for each token
4324 that was shifted.
4325
4326 But the stack does not always have an element for each token read. When
4327 the last @var{n} tokens and groupings shifted match the components of a
4328 grammar rule, they can be combined according to that rule. This is called
4329 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
4330 single grouping whose symbol is the result (left hand side) of that rule.
4331 Running the rule's action is part of the process of reduction, because this
4332 is what computes the semantic value of the resulting grouping.
4333
4334 For example, if the infix calculator's parser stack contains this:
4335
4336 @example
4337 1 + 5 * 3
4338 @end example
4339
4340 @noindent
4341 and the next input token is a newline character, then the last three
4342 elements can be reduced to 15 via the rule:
4343
4344 @example
4345 expr: expr '*' expr;
4346 @end example
4347
4348 @noindent
4349 Then the stack contains just these three elements:
4350
4351 @example
4352 1 + 15
4353 @end example
4354
4355 @noindent
4356 At this point, another reduction can be made, resulting in the single value
4357 16. Then the newline token can be shifted.
4358
4359 The parser tries, by shifts and reductions, to reduce the entire input down
4360 to a single grouping whose symbol is the grammar's start-symbol
4361 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
4362
4363 This kind of parser is known in the literature as a bottom-up parser.
4364
4365 @menu
4366 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
4367 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
4368 * Precedence:: Operator precedence works by resolving conflicts.
4369 * Contextual Precedence:: When an operator's precedence depends on context.
4370 * Parser States:: The parser is a finite-state-machine with stack.
4371 * Reduce/Reduce:: When two rules are applicable in the same situation.
4372 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
4373 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
4374 * Stack Overflow:: What happens when stack gets full. How to avoid it.
4375 @end menu
4376
4377 @node Look-Ahead
4378 @section Look-Ahead Tokens
4379 @cindex look-ahead token
4380
4381 The Bison parser does @emph{not} always reduce immediately as soon as the
4382 last @var{n} tokens and groupings match a rule. This is because such a
4383 simple strategy is inadequate to handle most languages. Instead, when a
4384 reduction is possible, the parser sometimes ``looks ahead'' at the next
4385 token in order to decide what to do.
4386
4387 When a token is read, it is not immediately shifted; first it becomes the
4388 @dfn{look-ahead token}, which is not on the stack. Now the parser can
4389 perform one or more reductions of tokens and groupings on the stack, while
4390 the look-ahead token remains off to the side. When no more reductions
4391 should take place, the look-ahead token is shifted onto the stack. This
4392 does not mean that all possible reductions have been done; depending on the
4393 token type of the look-ahead token, some rules may choose to delay their
4394 application.
4395
4396 Here is a simple case where look-ahead is needed. These three rules define
4397 expressions which contain binary addition operators and postfix unary
4398 factorial operators (@samp{!}), and allow parentheses for grouping.
4399
4400 @example
4401 @group
4402 expr: term '+' expr
4403 | term
4404 ;
4405 @end group
4406
4407 @group
4408 term: '(' expr ')'
4409 | term '!'
4410 | NUMBER
4411 ;
4412 @end group
4413 @end example
4414
4415 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
4416 should be done? If the following token is @samp{)}, then the first three
4417 tokens must be reduced to form an @code{expr}. This is the only valid
4418 course, because shifting the @samp{)} would produce a sequence of symbols
4419 @w{@code{term ')'}}, and no rule allows this.
4420
4421 If the following token is @samp{!}, then it must be shifted immediately so
4422 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
4423 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
4424 @code{expr}. It would then be impossible to shift the @samp{!} because
4425 doing so would produce on the stack the sequence of symbols @code{expr
4426 '!'}. No rule allows that sequence.
4427
4428 @vindex yychar
4429 The current look-ahead token is stored in the variable @code{yychar}.
4430 @xref{Action Features, ,Special Features for Use in Actions}.
4431
4432 @node Shift/Reduce
4433 @section Shift/Reduce Conflicts
4434 @cindex conflicts
4435 @cindex shift/reduce conflicts
4436 @cindex dangling @code{else}
4437 @cindex @code{else}, dangling
4438
4439 Suppose we are parsing a language which has if-then and if-then-else
4440 statements, with a pair of rules like this:
4441
4442 @example
4443 @group
4444 if_stmt:
4445 IF expr THEN stmt
4446 | IF expr THEN stmt ELSE stmt
4447 ;
4448 @end group
4449 @end example
4450
4451 @noindent
4452 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
4453 terminal symbols for specific keyword tokens.
4454
4455 When the @code{ELSE} token is read and becomes the look-ahead token, the
4456 contents of the stack (assuming the input is valid) are just right for
4457 reduction by the first rule. But it is also legitimate to shift the
4458 @code{ELSE}, because that would lead to eventual reduction by the second
4459 rule.
4460
4461 This situation, where either a shift or a reduction would be valid, is
4462 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
4463 these conflicts by choosing to shift, unless otherwise directed by
4464 operator precedence declarations. To see the reason for this, let's
4465 contrast it with the other alternative.
4466
4467 Since the parser prefers to shift the @code{ELSE}, the result is to attach
4468 the else-clause to the innermost if-statement, making these two inputs
4469 equivalent:
4470
4471 @example
4472 if x then if y then win (); else lose;
4473
4474 if x then do; if y then win (); else lose; end;
4475 @end example
4476
4477 But if the parser chose to reduce when possible rather than shift, the
4478 result would be to attach the else-clause to the outermost if-statement,
4479 making these two inputs equivalent:
4480
4481 @example
4482 if x then if y then win (); else lose;
4483
4484 if x then do; if y then win (); end; else lose;
4485 @end example
4486
4487 The conflict exists because the grammar as written is ambiguous: either
4488 parsing of the simple nested if-statement is legitimate. The established
4489 convention is that these ambiguities are resolved by attaching the
4490 else-clause to the innermost if-statement; this is what Bison accomplishes
4491 by choosing to shift rather than reduce. (It would ideally be cleaner to
4492 write an unambiguous grammar, but that is very hard to do in this case.)
4493 This particular ambiguity was first encountered in the specifications of
4494 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
4495
4496 To avoid warnings from Bison about predictable, legitimate shift/reduce
4497 conflicts, use the @code{%expect @var{n}} declaration. There will be no
4498 warning as long as the number of shift/reduce conflicts is exactly @var{n}.
4499 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
4500
4501 The definition of @code{if_stmt} above is solely to blame for the
4502 conflict, but the conflict does not actually appear without additional
4503 rules. Here is a complete Bison input file that actually manifests the
4504 conflict:
4505
4506 @example
4507 @group
4508 %token IF THEN ELSE variable
4509 %%
4510 @end group
4511 @group
4512 stmt: expr
4513 | if_stmt
4514 ;
4515 @end group
4516
4517 @group
4518 if_stmt:
4519 IF expr THEN stmt
4520 | IF expr THEN stmt ELSE stmt
4521 ;
4522 @end group
4523
4524 expr: variable
4525 ;
4526 @end example
4527
4528 @node Precedence
4529 @section Operator Precedence
4530 @cindex operator precedence
4531 @cindex precedence of operators
4532
4533 Another situation where shift/reduce conflicts appear is in arithmetic
4534 expressions. Here shifting is not always the preferred resolution; the
4535 Bison declarations for operator precedence allow you to specify when to
4536 shift and when to reduce.
4537
4538 @menu
4539 * Why Precedence:: An example showing why precedence is needed.
4540 * Using Precedence:: How to specify precedence in Bison grammars.
4541 * Precedence Examples:: How these features are used in the previous example.
4542 * How Precedence:: How they work.
4543 @end menu
4544
4545 @node Why Precedence
4546 @subsection When Precedence is Needed
4547
4548 Consider the following ambiguous grammar fragment (ambiguous because the
4549 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
4550
4551 @example
4552 @group
4553 expr: expr '-' expr
4554 | expr '*' expr
4555 | expr '<' expr
4556 | '(' expr ')'
4557 @dots{}
4558 ;
4559 @end group
4560 @end example
4561
4562 @noindent
4563 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
4564 should it reduce them via the rule for the subtraction operator? It
4565 depends on the next token. Of course, if the next token is @samp{)}, we
4566 must reduce; shifting is invalid because no single rule can reduce the
4567 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
4568 the next token is @samp{*} or @samp{<}, we have a choice: either
4569 shifting or reduction would allow the parse to complete, but with
4570 different results.
4571
4572 To decide which one Bison should do, we must consider the results. If
4573 the next operator token @var{op} is shifted, then it must be reduced
4574 first in order to permit another opportunity to reduce the difference.
4575 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
4576 hand, if the subtraction is reduced before shifting @var{op}, the result
4577 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
4578 reduce should depend on the relative precedence of the operators
4579 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
4580 @samp{<}.
4581
4582 @cindex associativity
4583 What about input such as @w{@samp{1 - 2 - 5}}; should this be
4584 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
4585 operators we prefer the former, which is called @dfn{left association}.
4586 The latter alternative, @dfn{right association}, is desirable for
4587 assignment operators. The choice of left or right association is a
4588 matter of whether the parser chooses to shift or reduce when the stack
4589 contains @w{@samp{1 - 2}} and the look-ahead token is @samp{-}: shifting
4590 makes right-associativity.
4591
4592 @node Using Precedence
4593 @subsection Specifying Operator Precedence
4594 @findex %left
4595 @findex %right
4596 @findex %nonassoc
4597
4598 Bison allows you to specify these choices with the operator precedence
4599 declarations @code{%left} and @code{%right}. Each such declaration
4600 contains a list of tokens, which are operators whose precedence and
4601 associativity is being declared. The @code{%left} declaration makes all
4602 those operators left-associative and the @code{%right} declaration makes
4603 them right-associative. A third alternative is @code{%nonassoc}, which
4604 declares that it is a syntax error to find the same operator twice ``in a
4605 row''.
4606
4607 The relative precedence of different operators is controlled by the
4608 order in which they are declared. The first @code{%left} or
4609 @code{%right} declaration in the file declares the operators whose
4610 precedence is lowest, the next such declaration declares the operators
4611 whose precedence is a little higher, and so on.
4612
4613 @node Precedence Examples
4614 @subsection Precedence Examples
4615
4616 In our example, we would want the following declarations:
4617
4618 @example
4619 %left '<'
4620 %left '-'
4621 %left '*'
4622 @end example
4623
4624 In a more complete example, which supports other operators as well, we
4625 would declare them in groups of equal precedence. For example, @code{'+'} is
4626 declared with @code{'-'}:
4627
4628 @example
4629 %left '<' '>' '=' NE LE GE
4630 %left '+' '-'
4631 %left '*' '/'
4632 @end example
4633
4634 @noindent
4635 (Here @code{NE} and so on stand for the operators for ``not equal''
4636 and so on. We assume that these tokens are more than one character long
4637 and therefore are represented by names, not character literals.)
4638
4639 @node How Precedence
4640 @subsection How Precedence Works
4641
4642 The first effect of the precedence declarations is to assign precedence
4643 levels to the terminal symbols declared. The second effect is to assign
4644 precedence levels to certain rules: each rule gets its precedence from
4645 the last terminal symbol mentioned in the components. (You can also
4646 specify explicitly the precedence of a rule. @xref{Contextual
4647 Precedence, ,Context-Dependent Precedence}.)
4648
4649 Finally, the resolution of conflicts works by comparing the precedence
4650 of the rule being considered with that of the look-ahead token. If the
4651 token's precedence is higher, the choice is to shift. If the rule's
4652 precedence is higher, the choice is to reduce. If they have equal
4653 precedence, the choice is made based on the associativity of that
4654 precedence level. The verbose output file made by @samp{-v}
4655 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
4656 resolved.
4657
4658 Not all rules and not all tokens have precedence. If either the rule or
4659 the look-ahead token has no precedence, then the default is to shift.
4660
4661 @node Contextual Precedence
4662 @section Context-Dependent Precedence
4663 @cindex context-dependent precedence
4664 @cindex unary operator precedence
4665 @cindex precedence, context-dependent
4666 @cindex precedence, unary operator
4667 @findex %prec
4668
4669 Often the precedence of an operator depends on the context. This sounds
4670 outlandish at first, but it is really very common. For example, a minus
4671 sign typically has a very high precedence as a unary operator, and a
4672 somewhat lower precedence (lower than multiplication) as a binary operator.
4673
4674 The Bison precedence declarations, @code{%left}, @code{%right} and
4675 @code{%nonassoc}, can only be used once for a given token; so a token has
4676 only one precedence declared in this way. For context-dependent
4677 precedence, you need to use an additional mechanism: the @code{%prec}
4678 modifier for rules.
4679
4680 The @code{%prec} modifier declares the precedence of a particular rule by
4681 specifying a terminal symbol whose precedence should be used for that rule.
4682 It's not necessary for that symbol to appear otherwise in the rule. The
4683 modifier's syntax is:
4684
4685 @example
4686 %prec @var{terminal-symbol}
4687 @end example
4688
4689 @noindent
4690 and it is written after the components of the rule. Its effect is to
4691 assign the rule the precedence of @var{terminal-symbol}, overriding
4692 the precedence that would be deduced for it in the ordinary way. The
4693 altered rule precedence then affects how conflicts involving that rule
4694 are resolved (@pxref{Precedence, ,Operator Precedence}).
4695
4696 Here is how @code{%prec} solves the problem of unary minus. First, declare
4697 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
4698 are no tokens of this type, but the symbol serves to stand for its
4699 precedence:
4700
4701 @example
4702 @dots{}
4703 %left '+' '-'
4704 %left '*'
4705 %left UMINUS
4706 @end example
4707
4708 Now the precedence of @code{UMINUS} can be used in specific rules:
4709
4710 @example
4711 @group
4712 exp: @dots{}
4713 | exp '-' exp
4714 @dots{}
4715 | '-' exp %prec UMINUS
4716 @end group
4717 @end example
4718
4719 @node Parser States
4720 @section Parser States
4721 @cindex finite-state machine
4722 @cindex parser state
4723 @cindex state (of parser)
4724
4725 The function @code{yyparse} is implemented using a finite-state machine.
4726 The values pushed on the parser stack are not simply token type codes; they
4727 represent the entire sequence of terminal and nonterminal symbols at or
4728 near the top of the stack. The current state collects all the information
4729 about previous input which is relevant to deciding what to do next.
4730
4731 Each time a look-ahead token is read, the current parser state together
4732 with the type of look-ahead token are looked up in a table. This table
4733 entry can say, ``Shift the look-ahead token.'' In this case, it also
4734 specifies the new parser state, which is pushed onto the top of the
4735 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
4736 This means that a certain number of tokens or groupings are taken off
4737 the top of the stack, and replaced by one grouping. In other words,
4738 that number of states are popped from the stack, and one new state is
4739 pushed.
4740
4741 There is one other alternative: the table can say that the look-ahead token
4742 is erroneous in the current state. This causes error processing to begin
4743 (@pxref{Error Recovery}).
4744
4745 @node Reduce/Reduce
4746 @section Reduce/Reduce Conflicts
4747 @cindex reduce/reduce conflict
4748 @cindex conflicts, reduce/reduce
4749
4750 A reduce/reduce conflict occurs if there are two or more rules that apply
4751 to the same sequence of input. This usually indicates a serious error
4752 in the grammar.
4753
4754 For example, here is an erroneous attempt to define a sequence
4755 of zero or more @code{word} groupings.
4756
4757 @example
4758 sequence: /* empty */
4759 @{ printf ("empty sequence\n"); @}
4760 | maybeword
4761 | sequence word
4762 @{ printf ("added word %s\n", $2); @}
4763 ;
4764
4765 maybeword: /* empty */
4766 @{ printf ("empty maybeword\n"); @}
4767 | word
4768 @{ printf ("single word %s\n", $1); @}
4769 ;
4770 @end example
4771
4772 @noindent
4773 The error is an ambiguity: there is more than one way to parse a single
4774 @code{word} into a @code{sequence}. It could be reduced to a
4775 @code{maybeword} and then into a @code{sequence} via the second rule.
4776 Alternatively, nothing-at-all could be reduced into a @code{sequence}
4777 via the first rule, and this could be combined with the @code{word}
4778 using the third rule for @code{sequence}.
4779
4780 There is also more than one way to reduce nothing-at-all into a
4781 @code{sequence}. This can be done directly via the first rule,
4782 or indirectly via @code{maybeword} and then the second rule.
4783
4784 You might think that this is a distinction without a difference, because it
4785 does not change whether any particular input is valid or not. But it does
4786 affect which actions are run. One parsing order runs the second rule's
4787 action; the other runs the first rule's action and the third rule's action.
4788 In this example, the output of the program changes.
4789
4790 Bison resolves a reduce/reduce conflict by choosing to use the rule that
4791 appears first in the grammar, but it is very risky to rely on this. Every
4792 reduce/reduce conflict must be studied and usually eliminated. Here is the
4793 proper way to define @code{sequence}:
4794
4795 @example
4796 sequence: /* empty */
4797 @{ printf ("empty sequence\n"); @}
4798 | sequence word
4799 @{ printf ("added word %s\n", $2); @}
4800 ;
4801 @end example
4802
4803 Here is another common error that yields a reduce/reduce conflict:
4804
4805 @example
4806 sequence: /* empty */
4807 | sequence words
4808 | sequence redirects
4809 ;
4810
4811 words: /* empty */
4812 | words word
4813 ;
4814
4815 redirects:/* empty */
4816 | redirects redirect
4817 ;
4818 @end example
4819
4820 @noindent
4821 The intention here is to define a sequence which can contain either
4822 @code{word} or @code{redirect} groupings. The individual definitions of
4823 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
4824 three together make a subtle ambiguity: even an empty input can be parsed
4825 in infinitely many ways!
4826
4827 Consider: nothing-at-all could be a @code{words}. Or it could be two
4828 @code{words} in a row, or three, or any number. It could equally well be a
4829 @code{redirects}, or two, or any number. Or it could be a @code{words}
4830 followed by three @code{redirects} and another @code{words}. And so on.
4831
4832 Here are two ways to correct these rules. First, to make it a single level
4833 of sequence:
4834
4835 @example
4836 sequence: /* empty */
4837 | sequence word
4838 | sequence redirect
4839 ;
4840 @end example
4841
4842 Second, to prevent either a @code{words} or a @code{redirects}
4843 from being empty:
4844
4845 @example
4846 sequence: /* empty */
4847 | sequence words
4848 | sequence redirects
4849 ;
4850
4851 words: word
4852 | words word
4853 ;
4854
4855 redirects:redirect
4856 | redirects redirect
4857 ;
4858 @end example
4859
4860 @node Mystery Conflicts
4861 @section Mysterious Reduce/Reduce Conflicts
4862
4863 Sometimes reduce/reduce conflicts can occur that don't look warranted.
4864 Here is an example:
4865
4866 @example
4867 @group
4868 %token ID
4869
4870 %%
4871 def: param_spec return_spec ','
4872 ;
4873 param_spec:
4874 type
4875 | name_list ':' type
4876 ;
4877 @end group
4878 @group
4879 return_spec:
4880 type
4881 | name ':' type
4882 ;
4883 @end group
4884 @group
4885 type: ID
4886 ;
4887 @end group
4888 @group
4889 name: ID
4890 ;
4891 name_list:
4892 name
4893 | name ',' name_list
4894 ;
4895 @end group
4896 @end example
4897
4898 It would seem that this grammar can be parsed with only a single token
4899 of look-ahead: when a @code{param_spec} is being read, an @code{ID} is
4900 a @code{name} if a comma or colon follows, or a @code{type} if another
4901 @code{ID} follows. In other words, this grammar is @acronym{LR}(1).
4902
4903 @cindex @acronym{LR}(1)
4904 @cindex @acronym{LALR}(1)
4905 However, Bison, like most parser generators, cannot actually handle all
4906 @acronym{LR}(1) grammars. In this grammar, two contexts, that after
4907 an @code{ID}
4908 at the beginning of a @code{param_spec} and likewise at the beginning of
4909 a @code{return_spec}, are similar enough that Bison assumes they are the
4910 same. They appear similar because the same set of rules would be
4911 active---the rule for reducing to a @code{name} and that for reducing to
4912 a @code{type}. Bison is unable to determine at that stage of processing
4913 that the rules would require different look-ahead tokens in the two
4914 contexts, so it makes a single parser state for them both. Combining
4915 the two contexts causes a conflict later. In parser terminology, this
4916 occurrence means that the grammar is not @acronym{LALR}(1).
4917
4918 In general, it is better to fix deficiencies than to document them. But
4919 this particular deficiency is intrinsically hard to fix; parser
4920 generators that can handle @acronym{LR}(1) grammars are hard to write
4921 and tend to
4922 produce parsers that are very large. In practice, Bison is more useful
4923 as it is now.
4924
4925 When the problem arises, you can often fix it by identifying the two
4926 parser states that are being confused, and adding something to make them
4927 look distinct. In the above example, adding one rule to
4928 @code{return_spec} as follows makes the problem go away:
4929
4930 @example
4931 @group
4932 %token BOGUS
4933 @dots{}
4934 %%
4935 @dots{}
4936 return_spec:
4937 type
4938 | name ':' type
4939 /* This rule is never used. */
4940 | ID BOGUS
4941 ;
4942 @end group
4943 @end example
4944
4945 This corrects the problem because it introduces the possibility of an
4946 additional active rule in the context after the @code{ID} at the beginning of
4947 @code{return_spec}. This rule is not active in the corresponding context
4948 in a @code{param_spec}, so the two contexts receive distinct parser states.
4949 As long as the token @code{BOGUS} is never generated by @code{yylex},
4950 the added rule cannot alter the way actual input is parsed.
4951
4952 In this particular example, there is another way to solve the problem:
4953 rewrite the rule for @code{return_spec} to use @code{ID} directly
4954 instead of via @code{name}. This also causes the two confusing
4955 contexts to have different sets of active rules, because the one for
4956 @code{return_spec} activates the altered rule for @code{return_spec}
4957 rather than the one for @code{name}.
4958
4959 @example
4960 param_spec:
4961 type
4962 | name_list ':' type
4963 ;
4964 return_spec:
4965 type
4966 | ID ':' type
4967 ;
4968 @end example
4969
4970 @node Generalized LR Parsing
4971 @section Generalized @acronym{LR} (@acronym{GLR}) Parsing
4972 @cindex @acronym{GLR} parsing
4973 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
4974 @cindex ambiguous grammars
4975 @cindex non-deterministic parsing
4976
4977 Bison produces @emph{deterministic} parsers that choose uniquely
4978 when to reduce and which reduction to apply
4979 based on a summary of the preceding input and on one extra token of lookahead.
4980 As a result, normal Bison handles a proper subset of the family of
4981 context-free languages.
4982 Ambiguous grammars, since they have strings with more than one possible
4983 sequence of reductions cannot have deterministic parsers in this sense.
4984 The same is true of languages that require more than one symbol of
4985 lookahead, since the parser lacks the information necessary to make a
4986 decision at the point it must be made in a shift-reduce parser.
4987 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
4988 there are languages where Bison's particular choice of how to
4989 summarize the input seen so far loses necessary information.
4990
4991 When you use the @samp{%glr-parser} declaration in your grammar file,
4992 Bison generates a parser that uses a different algorithm, called
4993 Generalized @acronym{LR} (or @acronym{GLR}). A Bison @acronym{GLR}
4994 parser uses the same basic
4995 algorithm for parsing as an ordinary Bison parser, but behaves
4996 differently in cases where there is a shift-reduce conflict that has not
4997 been resolved by precedence rules (@pxref{Precedence}) or a
4998 reduce-reduce conflict. When a @acronym{GLR} parser encounters such a
4999 situation, it
5000 effectively @emph{splits} into a several parsers, one for each possible
5001 shift or reduction. These parsers then proceed as usual, consuming
5002 tokens in lock-step. Some of the stacks may encounter other conflicts
5003 and split further, with the result that instead of a sequence of states,
5004 a Bison @acronym{GLR} parsing stack is what is in effect a tree of states.
5005
5006 In effect, each stack represents a guess as to what the proper parse
5007 is. Additional input may indicate that a guess was wrong, in which case
5008 the appropriate stack silently disappears. Otherwise, the semantics
5009 actions generated in each stack are saved, rather than being executed
5010 immediately. When a stack disappears, its saved semantic actions never
5011 get executed. When a reduction causes two stacks to become equivalent,
5012 their sets of semantic actions are both saved with the state that
5013 results from the reduction. We say that two stacks are equivalent
5014 when they both represent the same sequence of states,
5015 and each pair of corresponding states represents a
5016 grammar symbol that produces the same segment of the input token
5017 stream.
5018
5019 Whenever the parser makes a transition from having multiple
5020 states to having one, it reverts to the normal @acronym{LALR}(1) parsing
5021 algorithm, after resolving and executing the saved-up actions.
5022 At this transition, some of the states on the stack will have semantic
5023 values that are sets (actually multisets) of possible actions. The
5024 parser tries to pick one of the actions by first finding one whose rule
5025 has the highest dynamic precedence, as set by the @samp{%dprec}
5026 declaration. Otherwise, if the alternative actions are not ordered by
5027 precedence, but there the same merging function is declared for both
5028 rules by the @samp{%merge} declaration,
5029 Bison resolves and evaluates both and then calls the merge function on
5030 the result. Otherwise, it reports an ambiguity.
5031
5032 It is possible to use a data structure for the @acronym{GLR} parsing tree that
5033 permits the processing of any @acronym{LALR}(1) grammar in linear time (in the
5034 size of the input), any unambiguous (not necessarily
5035 @acronym{LALR}(1)) grammar in
5036 quadratic worst-case time, and any general (possibly ambiguous)
5037 context-free grammar in cubic worst-case time. However, Bison currently
5038 uses a simpler data structure that requires time proportional to the
5039 length of the input times the maximum number of stacks required for any
5040 prefix of the input. Thus, really ambiguous or non-deterministic
5041 grammars can require exponential time and space to process. Such badly
5042 behaving examples, however, are not generally of practical interest.
5043 Usually, non-determinism in a grammar is local---the parser is ``in
5044 doubt'' only for a few tokens at a time. Therefore, the current data
5045 structure should generally be adequate. On @acronym{LALR}(1) portions of a
5046 grammar, in particular, it is only slightly slower than with the default
5047 Bison parser.
5048
5049 @node Stack Overflow
5050 @section Stack Overflow, and How to Avoid It
5051 @cindex stack overflow
5052 @cindex parser stack overflow
5053 @cindex overflow of parser stack
5054
5055 The Bison parser stack can overflow if too many tokens are shifted and
5056 not reduced. When this happens, the parser function @code{yyparse}
5057 returns a nonzero value, pausing only to call @code{yyerror} to report
5058 the overflow.
5059
5060 Because Bison parsers have growing stacks, hitting the upper limit
5061 usually results from using a right recursion instead of a left
5062 recursion, @xref{Recursion, ,Recursive Rules}.
5063
5064 @vindex YYMAXDEPTH
5065 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
5066 parser stack can become before a stack overflow occurs. Define the
5067 macro with a value that is an integer. This value is the maximum number
5068 of tokens that can be shifted (and not reduced) before overflow.
5069 It must be a constant expression whose value is known at compile time.
5070
5071 The stack space allowed is not necessarily allocated. If you specify a
5072 large value for @code{YYMAXDEPTH}, the parser actually allocates a small
5073 stack at first, and then makes it bigger by stages as needed. This
5074 increasing allocation happens automatically and silently. Therefore,
5075 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
5076 space for ordinary inputs that do not need much stack.
5077
5078 @cindex default stack limit
5079 The default value of @code{YYMAXDEPTH}, if you do not define it, is
5080 10000.
5081
5082 @vindex YYINITDEPTH
5083 You can control how much stack is allocated initially by defining the
5084 macro @code{YYINITDEPTH}. This value too must be a compile-time
5085 constant integer. The default is 200.
5086
5087 @c FIXME: C++ output.
5088 Because of semantical differences between C and C++, the
5089 @acronym{LALR}(1) parsers
5090 in C produced by Bison by compiled as C++ cannot grow. In this precise
5091 case (compiling a C parser as C++) you are suggested to grow
5092 @code{YYINITDEPTH}. In the near future, a C++ output output will be
5093 provided which addresses this issue.
5094
5095 @node Error Recovery
5096 @chapter Error Recovery
5097 @cindex error recovery
5098 @cindex recovery from errors
5099
5100 It is not usually acceptable to have a program terminate on a parse
5101 error. For example, a compiler should recover sufficiently to parse the
5102 rest of the input file and check it for errors; a calculator should accept
5103 another expression.
5104
5105 In a simple interactive command parser where each input is one line, it may
5106 be sufficient to allow @code{yyparse} to return 1 on error and have the
5107 caller ignore the rest of the input line when that happens (and then call
5108 @code{yyparse} again). But this is inadequate for a compiler, because it
5109 forgets all the syntactic context leading up to the error. A syntax error
5110 deep within a function in the compiler input should not cause the compiler
5111 to treat the following line like the beginning of a source file.
5112
5113 @findex error
5114 You can define how to recover from a syntax error by writing rules to
5115 recognize the special token @code{error}. This is a terminal symbol that
5116 is always defined (you need not declare it) and reserved for error
5117 handling. The Bison parser generates an @code{error} token whenever a
5118 syntax error happens; if you have provided a rule to recognize this token
5119 in the current context, the parse can continue.
5120
5121 For example:
5122
5123 @example
5124 stmnts: /* empty string */
5125 | stmnts '\n'
5126 | stmnts exp '\n'
5127 | stmnts error '\n'
5128 @end example
5129
5130 The fourth rule in this example says that an error followed by a newline
5131 makes a valid addition to any @code{stmnts}.
5132
5133 What happens if a syntax error occurs in the middle of an @code{exp}? The
5134 error recovery rule, interpreted strictly, applies to the precise sequence
5135 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
5136 the middle of an @code{exp}, there will probably be some additional tokens
5137 and subexpressions on the stack after the last @code{stmnts}, and there
5138 will be tokens to read before the next newline. So the rule is not
5139 applicable in the ordinary way.
5140
5141 But Bison can force the situation to fit the rule, by discarding part of
5142 the semantic context and part of the input. First it discards states
5143 and objects from the stack until it gets back to a state in which the
5144 @code{error} token is acceptable. (This means that the subexpressions
5145 already parsed are discarded, back to the last complete @code{stmnts}.)
5146 At this point the @code{error} token can be shifted. Then, if the old
5147 look-ahead token is not acceptable to be shifted next, the parser reads
5148 tokens and discards them until it finds a token which is acceptable. In
5149 this example, Bison reads and discards input until the next newline so
5150 that the fourth rule can apply. Note that discarded symbols are
5151 possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
5152 Discarded Symbols}, for a means to reclaim this memory.
5153
5154 The choice of error rules in the grammar is a choice of strategies for
5155 error recovery. A simple and useful strategy is simply to skip the rest of
5156 the current input line or current statement if an error is detected:
5157
5158 @example
5159 stmnt: error ';' /* On error, skip until ';' is read. */
5160 @end example
5161
5162 It is also useful to recover to the matching close-delimiter of an
5163 opening-delimiter that has already been parsed. Otherwise the
5164 close-delimiter will probably appear to be unmatched, and generate another,
5165 spurious error message:
5166
5167 @example
5168 primary: '(' expr ')'
5169 | '(' error ')'
5170 @dots{}
5171 ;
5172 @end example
5173
5174 Error recovery strategies are necessarily guesses. When they guess wrong,
5175 one syntax error often leads to another. In the above example, the error
5176 recovery rule guesses that an error is due to bad input within one
5177 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
5178 middle of a valid @code{stmnt}. After the error recovery rule recovers
5179 from the first error, another syntax error will be found straightaway,
5180 since the text following the spurious semicolon is also an invalid
5181 @code{stmnt}.
5182
5183 To prevent an outpouring of error messages, the parser will output no error
5184 message for another syntax error that happens shortly after the first; only
5185 after three consecutive input tokens have been successfully shifted will
5186 error messages resume.
5187
5188 Note that rules which accept the @code{error} token may have actions, just
5189 as any other rules can.
5190
5191 @findex yyerrok
5192 You can make error messages resume immediately by using the macro
5193 @code{yyerrok} in an action. If you do this in the error rule's action, no
5194 error messages will be suppressed. This macro requires no arguments;
5195 @samp{yyerrok;} is a valid C statement.
5196
5197 @findex yyclearin
5198 The previous look-ahead token is reanalyzed immediately after an error. If
5199 this is unacceptable, then the macro @code{yyclearin} may be used to clear
5200 this token. Write the statement @samp{yyclearin;} in the error rule's
5201 action.
5202
5203 For example, suppose that on a parse error, an error handling routine is
5204 called that advances the input stream to some point where parsing should
5205 once again commence. The next symbol returned by the lexical scanner is
5206 probably correct. The previous look-ahead token ought to be discarded
5207 with @samp{yyclearin;}.
5208
5209 @vindex YYRECOVERING
5210 The macro @code{YYRECOVERING} stands for an expression that has the
5211 value 1 when the parser is recovering from a syntax error, and 0 the
5212 rest of the time. A value of 1 indicates that error messages are
5213 currently suppressed for new syntax errors.
5214
5215 @node Context Dependency
5216 @chapter Handling Context Dependencies
5217
5218 The Bison paradigm is to parse tokens first, then group them into larger
5219 syntactic units. In many languages, the meaning of a token is affected by
5220 its context. Although this violates the Bison paradigm, certain techniques
5221 (known as @dfn{kludges}) may enable you to write Bison parsers for such
5222 languages.
5223
5224 @menu
5225 * Semantic Tokens:: Token parsing can depend on the semantic context.
5226 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
5227 * Tie-in Recovery:: Lexical tie-ins have implications for how
5228 error recovery rules must be written.
5229 @end menu
5230
5231 (Actually, ``kludge'' means any technique that gets its job done but is
5232 neither clean nor robust.)
5233
5234 @node Semantic Tokens
5235 @section Semantic Info in Token Types
5236
5237 The C language has a context dependency: the way an identifier is used
5238 depends on what its current meaning is. For example, consider this:
5239
5240 @example
5241 foo (x);
5242 @end example
5243
5244 This looks like a function call statement, but if @code{foo} is a typedef
5245 name, then this is actually a declaration of @code{x}. How can a Bison
5246 parser for C decide how to parse this input?
5247
5248 The method used in @acronym{GNU} C is to have two different token types,
5249 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
5250 identifier, it looks up the current declaration of the identifier in order
5251 to decide which token type to return: @code{TYPENAME} if the identifier is
5252 declared as a typedef, @code{IDENTIFIER} otherwise.
5253
5254 The grammar rules can then express the context dependency by the choice of
5255 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
5256 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
5257 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
5258 is @emph{not} significant, such as in declarations that can shadow a
5259 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
5260 accepted---there is one rule for each of the two token types.
5261
5262 This technique is simple to use if the decision of which kinds of
5263 identifiers to allow is made at a place close to where the identifier is
5264 parsed. But in C this is not always so: C allows a declaration to
5265 redeclare a typedef name provided an explicit type has been specified
5266 earlier:
5267
5268 @example
5269 typedef int foo, bar, lose;
5270 static foo (bar); /* @r{redeclare @code{bar} as static variable} */
5271 static int foo (lose); /* @r{redeclare @code{foo} as function} */
5272 @end example
5273
5274 Unfortunately, the name being declared is separated from the declaration
5275 construct itself by a complicated syntactic structure---the ``declarator''.
5276
5277 As a result, part of the Bison parser for C needs to be duplicated, with
5278 all the nonterminal names changed: once for parsing a declaration in
5279 which a typedef name can be redefined, and once for parsing a
5280 declaration in which that can't be done. Here is a part of the
5281 duplication, with actions omitted for brevity:
5282
5283 @example
5284 initdcl:
5285 declarator maybeasm '='
5286 init
5287 | declarator maybeasm
5288 ;
5289
5290 notype_initdcl:
5291 notype_declarator maybeasm '='
5292 init
5293 | notype_declarator maybeasm
5294 ;
5295 @end example
5296
5297 @noindent
5298 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
5299 cannot. The distinction between @code{declarator} and
5300 @code{notype_declarator} is the same sort of thing.
5301
5302 There is some similarity between this technique and a lexical tie-in
5303 (described next), in that information which alters the lexical analysis is
5304 changed during parsing by other parts of the program. The difference is
5305 here the information is global, and is used for other purposes in the
5306 program. A true lexical tie-in has a special-purpose flag controlled by
5307 the syntactic context.
5308
5309 @node Lexical Tie-ins
5310 @section Lexical Tie-ins
5311 @cindex lexical tie-in
5312
5313 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
5314 which is set by Bison actions, whose purpose is to alter the way tokens are
5315 parsed.
5316
5317 For example, suppose we have a language vaguely like C, but with a special
5318 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
5319 an expression in parentheses in which all integers are hexadecimal. In
5320 particular, the token @samp{a1b} must be treated as an integer rather than
5321 as an identifier if it appears in that context. Here is how you can do it:
5322
5323 @example
5324 @group
5325 %@{
5326 int hexflag;
5327 %@}
5328 %%
5329 @dots{}
5330 @end group
5331 @group
5332 expr: IDENTIFIER
5333 | constant
5334 | HEX '('
5335 @{ hexflag = 1; @}
5336 expr ')'
5337 @{ hexflag = 0;
5338 $$ = $4; @}
5339 | expr '+' expr
5340 @{ $$ = make_sum ($1, $3); @}
5341 @dots{}
5342 ;
5343 @end group
5344
5345 @group
5346 constant:
5347 INTEGER
5348 | STRING
5349 ;
5350 @end group
5351 @end example
5352
5353 @noindent
5354 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
5355 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
5356 with letters are parsed as integers if possible.
5357
5358 The declaration of @code{hexflag} shown in the prologue of the parser file
5359 is needed to make it accessible to the actions (@pxref{Prologue, ,The Prologue}).
5360 You must also write the code in @code{yylex} to obey the flag.
5361
5362 @node Tie-in Recovery
5363 @section Lexical Tie-ins and Error Recovery
5364
5365 Lexical tie-ins make strict demands on any error recovery rules you have.
5366 @xref{Error Recovery}.
5367
5368 The reason for this is that the purpose of an error recovery rule is to
5369 abort the parsing of one construct and resume in some larger construct.
5370 For example, in C-like languages, a typical error recovery rule is to skip
5371 tokens until the next semicolon, and then start a new statement, like this:
5372
5373 @example
5374 stmt: expr ';'
5375 | IF '(' expr ')' stmt @{ @dots{} @}
5376 @dots{}
5377 error ';'
5378 @{ hexflag = 0; @}
5379 ;
5380 @end example
5381
5382 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
5383 construct, this error rule will apply, and then the action for the
5384 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
5385 remain set for the entire rest of the input, or until the next @code{hex}
5386 keyword, causing identifiers to be misinterpreted as integers.
5387
5388 To avoid this problem the error recovery rule itself clears @code{hexflag}.
5389
5390 There may also be an error recovery rule that works within expressions.
5391 For example, there could be a rule which applies within parentheses
5392 and skips to the close-parenthesis:
5393
5394 @example
5395 @group
5396 expr: @dots{}
5397 | '(' expr ')'
5398 @{ $$ = $2; @}
5399 | '(' error ')'
5400 @dots{}
5401 @end group
5402 @end example
5403
5404 If this rule acts within the @code{hex} construct, it is not going to abort
5405 that construct (since it applies to an inner level of parentheses within
5406 the construct). Therefore, it should not clear the flag: the rest of
5407 the @code{hex} construct should be parsed with the flag still in effect.
5408
5409 What if there is an error recovery rule which might abort out of the
5410 @code{hex} construct or might not, depending on circumstances? There is no
5411 way you can write the action to determine whether a @code{hex} construct is
5412 being aborted or not. So if you are using a lexical tie-in, you had better
5413 make sure your error recovery rules are not of this kind. Each rule must
5414 be such that you can be sure that it always will, or always won't, have to
5415 clear the flag.
5416
5417 @c ================================================== Debugging Your Parser
5418
5419 @node Debugging
5420 @chapter Debugging Your Parser
5421
5422 Developing a parser can be a challenge, especially if you don't
5423 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
5424 Algorithm}). Even so, sometimes a detailed description of the automaton
5425 can help (@pxref{Understanding, , Understanding Your Parser}), or
5426 tracing the execution of the parser can give some insight on why it
5427 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
5428
5429 @menu
5430 * Understanding:: Understanding the structure of your parser.
5431 * Tracing:: Tracing the execution of your parser.
5432 @end menu
5433
5434 @node Understanding
5435 @section Understanding Your Parser
5436
5437 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
5438 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
5439 frequent than one would hope), looking at this automaton is required to
5440 tune or simply fix a parser. Bison provides two different
5441 representation of it, either textually or graphically (as a @acronym{VCG}
5442 file).
5443
5444 The textual file is generated when the options @option{--report} or
5445 @option{--verbose} are specified, see @xref{Invocation, , Invoking
5446 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
5447 the parser output file name, and adding @samp{.output} instead.
5448 Therefore, if the input file is @file{foo.y}, then the parser file is
5449 called @file{foo.tab.c} by default. As a consequence, the verbose
5450 output file is called @file{foo.output}.
5451
5452 The following grammar file, @file{calc.y}, will be used in the sequel:
5453
5454 @example
5455 %token NUM STR
5456 %left '+' '-'
5457 %left '*'
5458 %%
5459 exp: exp '+' exp
5460 | exp '-' exp
5461 | exp '*' exp
5462 | exp '/' exp
5463 | NUM
5464 ;
5465 useless: STR;
5466 %%
5467 @end example
5468
5469 @command{bison} reports:
5470
5471 @example
5472 calc.y: warning: 1 useless nonterminal and 1 useless rule
5473 calc.y:11.1-7: warning: useless nonterminal: useless
5474 calc.y:11.8-12: warning: useless rule: useless: STR
5475 calc.y contains 7 shift/reduce conflicts.
5476 @end example
5477
5478 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
5479 creates a file @file{calc.output} with contents detailed below. The
5480 order of the output and the exact presentation might vary, but the
5481 interpretation is the same.
5482
5483 The first section includes details on conflicts that were solved thanks
5484 to precedence and/or associativity:
5485
5486 @example
5487 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
5488 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
5489 Conflict in state 8 between rule 2 and token '*' resolved as shift.
5490 @exdent @dots{}
5491 @end example
5492
5493 @noindent
5494 The next section lists states that still have conflicts.
5495
5496 @example
5497 State 8 contains 1 shift/reduce conflict.
5498 State 9 contains 1 shift/reduce conflict.
5499 State 10 contains 1 shift/reduce conflict.
5500 State 11 contains 4 shift/reduce conflicts.
5501 @end example
5502
5503 @noindent
5504 @cindex token, useless
5505 @cindex useless token
5506 @cindex nonterminal, useless
5507 @cindex useless nonterminal
5508 @cindex rule, useless
5509 @cindex useless rule
5510 The next section reports useless tokens, nonterminal and rules. Useless
5511 nonterminals and rules are removed in order to produce a smaller parser,
5512 but useless tokens are preserved, since they might be used by the
5513 scanner (note the difference between ``useless'' and ``not used''
5514 below):
5515
5516 @example
5517 Useless nonterminals:
5518 useless
5519
5520 Terminals which are not used:
5521 STR
5522
5523 Useless rules:
5524 #6 useless: STR;
5525 @end example
5526
5527 @noindent
5528 The next section reproduces the exact grammar that Bison used:
5529
5530 @example
5531 Grammar
5532
5533 Number, Line, Rule
5534 0 5 $accept -> exp $end
5535 1 5 exp -> exp '+' exp
5536 2 6 exp -> exp '-' exp
5537 3 7 exp -> exp '*' exp
5538 4 8 exp -> exp '/' exp
5539 5 9 exp -> NUM
5540 @end example
5541
5542 @noindent
5543 and reports the uses of the symbols:
5544
5545 @example
5546 Terminals, with rules where they appear
5547
5548 $end (0) 0
5549 '*' (42) 3
5550 '+' (43) 1
5551 '-' (45) 2
5552 '/' (47) 4
5553 error (256)
5554 NUM (258) 5
5555
5556 Nonterminals, with rules where they appear
5557
5558 $accept (8)
5559 on left: 0
5560 exp (9)
5561 on left: 1 2 3 4 5, on right: 0 1 2 3 4
5562 @end example
5563
5564 @noindent
5565 @cindex item
5566 @cindex pointed rule
5567 @cindex rule, pointed
5568 Bison then proceeds onto the automaton itself, describing each state
5569 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
5570 item is a production rule together with a point (marked by @samp{.})
5571 that the input cursor.
5572
5573 @example
5574 state 0
5575
5576 $accept -> . exp $ (rule 0)
5577
5578 NUM shift, and go to state 1
5579
5580 exp go to state 2
5581 @end example
5582
5583 This reads as follows: ``state 0 corresponds to being at the very
5584 beginning of the parsing, in the initial rule, right before the start
5585 symbol (here, @code{exp}). When the parser returns to this state right
5586 after having reduced a rule that produced an @code{exp}, the control
5587 flow jumps to state 2. If there is no such transition on a nonterminal
5588 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
5589 the parse stack, and the control flow jumps to state 1. Any other
5590 lookahead triggers a parse error.''
5591
5592 @cindex core, item set
5593 @cindex item set core
5594 @cindex kernel, item set
5595 @cindex item set core
5596 Even though the only active rule in state 0 seems to be rule 0, the
5597 report lists @code{NUM} as a lookahead symbol because @code{NUM} can be
5598 at the beginning of any rule deriving an @code{exp}. By default Bison
5599 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
5600 you want to see more detail you can invoke @command{bison} with
5601 @option{--report=itemset} to list all the items, include those that can
5602 be derived:
5603
5604 @example
5605 state 0
5606
5607 $accept -> . exp $ (rule 0)
5608 exp -> . exp '+' exp (rule 1)
5609 exp -> . exp '-' exp (rule 2)
5610 exp -> . exp '*' exp (rule 3)
5611 exp -> . exp '/' exp (rule 4)
5612 exp -> . NUM (rule 5)
5613
5614 NUM shift, and go to state 1
5615
5616 exp go to state 2
5617 @end example
5618
5619 @noindent
5620 In the state 1...
5621
5622 @example
5623 state 1
5624
5625 exp -> NUM . (rule 5)
5626
5627 $default reduce using rule 5 (exp)
5628 @end example
5629
5630 @noindent
5631 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead
5632 (@samp{$default}), the parser will reduce it. If it was coming from
5633 state 0, then, after this reduction it will return to state 0, and will
5634 jump to state 2 (@samp{exp: go to state 2}).
5635
5636 @example
5637 state 2
5638
5639 $accept -> exp . $ (rule 0)
5640 exp -> exp . '+' exp (rule 1)
5641 exp -> exp . '-' exp (rule 2)
5642 exp -> exp . '*' exp (rule 3)
5643 exp -> exp . '/' exp (rule 4)
5644
5645 $ shift, and go to state 3
5646 '+' shift, and go to state 4
5647 '-' shift, and go to state 5
5648 '*' shift, and go to state 6
5649 '/' shift, and go to state 7
5650 @end example
5651
5652 @noindent
5653 In state 2, the automaton can only shift a symbol. For instance,
5654 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
5655 @samp{+}, it will be shifted on the parse stack, and the automaton
5656 control will jump to state 4, corresponding to the item @samp{exp -> exp
5657 '+' . exp}. Since there is no default action, any other token than
5658 those listed above will trigger a parse error.
5659
5660 The state 3 is named the @dfn{final state}, or the @dfn{accepting
5661 state}:
5662
5663 @example
5664 state 3
5665
5666 $accept -> exp $ . (rule 0)
5667
5668 $default accept
5669 @end example
5670
5671 @noindent
5672 the initial rule is completed (the start symbol and the end
5673 of input were read), the parsing exits successfully.
5674
5675 The interpretation of states 4 to 7 is straightforward, and is left to
5676 the reader.
5677
5678 @example
5679 state 4
5680
5681 exp -> exp '+' . exp (rule 1)
5682
5683 NUM shift, and go to state 1
5684
5685 exp go to state 8
5686
5687 state 5
5688
5689 exp -> exp '-' . exp (rule 2)
5690
5691 NUM shift, and go to state 1
5692
5693 exp go to state 9
5694
5695 state 6
5696
5697 exp -> exp '*' . exp (rule 3)
5698
5699 NUM shift, and go to state 1
5700
5701 exp go to state 10
5702
5703 state 7
5704
5705 exp -> exp '/' . exp (rule 4)
5706
5707 NUM shift, and go to state 1
5708
5709 exp go to state 11
5710 @end example
5711
5712 As was announced in beginning of the report, @samp{State 8 contains 1
5713 shift/reduce conflict}:
5714
5715 @example
5716 state 8
5717
5718 exp -> exp . '+' exp (rule 1)
5719 exp -> exp '+' exp . (rule 1)
5720 exp -> exp . '-' exp (rule 2)
5721 exp -> exp . '*' exp (rule 3)
5722 exp -> exp . '/' exp (rule 4)
5723
5724 '*' shift, and go to state 6
5725 '/' shift, and go to state 7
5726
5727 '/' [reduce using rule 1 (exp)]
5728 $default reduce using rule 1 (exp)
5729 @end example
5730
5731 Indeed, there are two actions associated to the lookahead @samp{/}:
5732 either shifting (and going to state 7), or reducing rule 1. The
5733 conflict means that either the grammar is ambiguous, or the parser lacks
5734 information to make the right decision. Indeed the grammar is
5735 ambiguous, as, since we did not specify the precedence of @samp{/}, the
5736 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
5737 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
5738 NUM}, which corresponds to reducing rule 1.
5739
5740 Because in @acronym{LALR}(1) parsing a single decision can be made, Bison
5741 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
5742 Shift/Reduce Conflicts}. Discarded actions are reported in between
5743 square brackets.
5744
5745 Note that all the previous states had a single possible action: either
5746 shifting the next token and going to the corresponding state, or
5747 reducing a single rule. In the other cases, i.e., when shifting
5748 @emph{and} reducing is possible or when @emph{several} reductions are
5749 possible, the lookahead is required to select the action. State 8 is
5750 one such state: if the lookahead is @samp{*} or @samp{/} then the action
5751 is shifting, otherwise the action is reducing rule 1. In other words,
5752 the first two items, corresponding to rule 1, are not eligible when the
5753 lookahead is @samp{*}, since we specified that @samp{*} has higher
5754 precedence that @samp{+}. More generally, some items are eligible only
5755 with some set of possible lookaheads. When run with
5756 @option{--report=lookahead}, Bison specifies these lookaheads:
5757
5758 @example
5759 state 8
5760
5761 exp -> exp . '+' exp [$, '+', '-', '/'] (rule 1)
5762 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
5763 exp -> exp . '-' exp (rule 2)
5764 exp -> exp . '*' exp (rule 3)
5765 exp -> exp . '/' exp (rule 4)
5766
5767 '*' shift, and go to state 6
5768 '/' shift, and go to state 7
5769
5770 '/' [reduce using rule 1 (exp)]
5771 $default reduce using rule 1 (exp)
5772 @end example
5773
5774 The remaining states are similar:
5775
5776 @example
5777 state 9
5778
5779 exp -> exp . '+' exp (rule 1)
5780 exp -> exp . '-' exp (rule 2)
5781 exp -> exp '-' exp . (rule 2)
5782 exp -> exp . '*' exp (rule 3)
5783 exp -> exp . '/' exp (rule 4)
5784
5785 '*' shift, and go to state 6
5786 '/' shift, and go to state 7
5787
5788 '/' [reduce using rule 2 (exp)]
5789 $default reduce using rule 2 (exp)
5790
5791 state 10
5792
5793 exp -> exp . '+' exp (rule 1)
5794 exp -> exp . '-' exp (rule 2)
5795 exp -> exp . '*' exp (rule 3)
5796 exp -> exp '*' exp . (rule 3)
5797 exp -> exp . '/' exp (rule 4)
5798
5799 '/' shift, and go to state 7
5800
5801 '/' [reduce using rule 3 (exp)]
5802 $default reduce using rule 3 (exp)
5803
5804 state 11
5805
5806 exp -> exp . '+' exp (rule 1)
5807 exp -> exp . '-' exp (rule 2)
5808 exp -> exp . '*' exp (rule 3)
5809 exp -> exp . '/' exp (rule 4)
5810 exp -> exp '/' exp . (rule 4)
5811
5812 '+' shift, and go to state 4
5813 '-' shift, and go to state 5
5814 '*' shift, and go to state 6
5815 '/' shift, and go to state 7
5816
5817 '+' [reduce using rule 4 (exp)]
5818 '-' [reduce using rule 4 (exp)]
5819 '*' [reduce using rule 4 (exp)]
5820 '/' [reduce using rule 4 (exp)]
5821 $default reduce using rule 4 (exp)
5822 @end example
5823
5824 @noindent
5825 Observe that state 11 contains conflicts due to the lack of precedence
5826 of @samp{/} wrt @samp{+}, @samp{-}, and @samp{*}, but also because the
5827 associativity of @samp{/} is not specified.
5828
5829
5830 @node Tracing
5831 @section Tracing Your Parser
5832 @findex yydebug
5833 @cindex debugging
5834 @cindex tracing the parser
5835
5836 If a Bison grammar compiles properly but doesn't do what you want when it
5837 runs, the @code{yydebug} parser-trace feature can help you figure out why.
5838
5839 There are several means to enable compilation of trace facilities:
5840
5841 @table @asis
5842 @item the macro @code{YYDEBUG}
5843 @findex YYDEBUG
5844 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
5845 parser. This is compliant with @acronym{POSIX} Yacc. You could use
5846 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
5847 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
5848 Prologue}).
5849
5850 @item the option @option{-t}, @option{--debug}
5851 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
5852 ,Invoking Bison}). This is @acronym{POSIX} compliant too.
5853
5854 @item the directive @samp{%debug}
5855 @findex %debug
5856 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison
5857 Declaration Summary}). This is a Bison extension, which will prove
5858 useful when Bison will output parsers for languages that don't use a
5859 preprocessor. Unless @acronym{POSIX} and Yacc portability matter to
5860 you, this is
5861 the preferred solution.
5862 @end table
5863
5864 We suggest that you always enable the debug option so that debugging is
5865 always possible.
5866
5867 The trace facility outputs messages with macro calls of the form
5868 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
5869 @var{format} and @var{args} are the usual @code{printf} format and
5870 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
5871 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
5872 and @code{YYPRINTF} is defined to @code{fprintf}.
5873
5874 Once you have compiled the program with trace facilities, the way to
5875 request a trace is to store a nonzero value in the variable @code{yydebug}.
5876 You can do this by making the C code do it (in @code{main}, perhaps), or
5877 you can alter the value with a C debugger.
5878
5879 Each step taken by the parser when @code{yydebug} is nonzero produces a
5880 line or two of trace information, written on @code{stderr}. The trace
5881 messages tell you these things:
5882
5883 @itemize @bullet
5884 @item
5885 Each time the parser calls @code{yylex}, what kind of token was read.
5886
5887 @item
5888 Each time a token is shifted, the depth and complete contents of the
5889 state stack (@pxref{Parser States}).
5890
5891 @item
5892 Each time a rule is reduced, which rule it is, and the complete contents
5893 of the state stack afterward.
5894 @end itemize
5895
5896 To make sense of this information, it helps to refer to the listing file
5897 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
5898 Bison}). This file shows the meaning of each state in terms of
5899 positions in various rules, and also what each state will do with each
5900 possible input token. As you read the successive trace messages, you
5901 can see that the parser is functioning according to its specification in
5902 the listing file. Eventually you will arrive at the place where
5903 something undesirable happens, and you will see which parts of the
5904 grammar are to blame.
5905
5906 The parser file is a C program and you can use C debuggers on it, but it's
5907 not easy to interpret what it is doing. The parser function is a
5908 finite-state machine interpreter, and aside from the actions it executes
5909 the same code over and over. Only the values of variables show where in
5910 the grammar it is working.
5911
5912 @findex YYPRINT
5913 The debugging information normally gives the token type of each token
5914 read, but not its semantic value. You can optionally define a macro
5915 named @code{YYPRINT} to provide a way to print the value. If you define
5916 @code{YYPRINT}, it should take three arguments. The parser will pass a
5917 standard I/O stream, the numeric code for the token type, and the token
5918 value (from @code{yylval}).
5919
5920 Here is an example of @code{YYPRINT} suitable for the multi-function
5921 calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
5922
5923 @smallexample
5924 #define YYPRINT(file, type, value) yyprint (file, type, value)
5925
5926 static void
5927 yyprint (FILE *file, int type, YYSTYPE value)
5928 @{
5929 if (type == VAR)
5930 fprintf (file, " %s", value.tptr->name);
5931 else if (type == NUM)
5932 fprintf (file, " %d", value.val);
5933 @}
5934 @end smallexample
5935
5936 @c ================================================= Invoking Bison
5937
5938 @node Invocation
5939 @chapter Invoking Bison
5940 @cindex invoking Bison
5941 @cindex Bison invocation
5942 @cindex options for invoking Bison
5943
5944 The usual way to invoke Bison is as follows:
5945
5946 @example
5947 bison @var{infile}
5948 @end example
5949
5950 Here @var{infile} is the grammar file name, which usually ends in
5951 @samp{.y}. The parser file's name is made by replacing the @samp{.y}
5952 with @samp{.tab.c}. Thus, the @samp{bison foo.y} filename yields
5953 @file{foo.tab.c}, and the @samp{bison hack/foo.y} filename yields
5954 @file{hack/foo.tab.c}. It's also possible, in case you are writing
5955 C++ code instead of C in your grammar file, to name it @file{foo.ypp}
5956 or @file{foo.y++}. Then, the output files will take an extension like
5957 the given one as input (respectively @file{foo.tab.cpp} and
5958 @file{foo.tab.c++}).
5959 This feature takes effect with all options that manipulate filenames like
5960 @samp{-o} or @samp{-d}.
5961
5962 For example :
5963
5964 @example
5965 bison -d @var{infile.yxx}
5966 @end example
5967 @noindent
5968 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
5969
5970 @example
5971 bison -d -o @var{output.c++} @var{infile.y}
5972 @end example
5973 @noindent
5974 will produce @file{output.c++} and @file{outfile.h++}.
5975
5976 @menu
5977 * Bison Options:: All the options described in detail,
5978 in alphabetical order by short options.
5979 * Option Cross Key:: Alphabetical list of long options.
5980 @end menu
5981
5982 @node Bison Options
5983 @section Bison Options
5984
5985 Bison supports both traditional single-letter options and mnemonic long
5986 option names. Long option names are indicated with @samp{--} instead of
5987 @samp{-}. Abbreviations for option names are allowed as long as they
5988 are unique. When a long option takes an argument, like
5989 @samp{--file-prefix}, connect the option name and the argument with
5990 @samp{=}.
5991
5992 Here is a list of options that can be used with Bison, alphabetized by
5993 short option. It is followed by a cross key alphabetized by long
5994 option.
5995
5996 @c Please, keep this ordered as in `bison --help'.
5997 @noindent
5998 Operations modes:
5999 @table @option
6000 @item -h
6001 @itemx --help
6002 Print a summary of the command-line options to Bison and exit.
6003
6004 @item -V
6005 @itemx --version
6006 Print the version number of Bison and exit.
6007
6008 @need 1750
6009 @item -y
6010 @itemx --yacc
6011 Equivalent to @samp{-o y.tab.c}; the parser output file is called
6012 @file{y.tab.c}, and the other outputs are called @file{y.output} and
6013 @file{y.tab.h}. The purpose of this option is to imitate Yacc's output
6014 file name conventions. Thus, the following shell script can substitute
6015 for Yacc:
6016
6017 @example
6018 bison -y $*
6019 @end example
6020 @end table
6021
6022 @noindent
6023 Tuning the parser:
6024
6025 @table @option
6026 @item -S @var{file}
6027 @itemx --skeleton=@var{file}
6028 Specify the skeleton to use. You probably don't need this option unless
6029 you are developing Bison.
6030
6031 @item -t
6032 @itemx --debug
6033 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
6034 already defined, so that the debugging facilities are compiled.
6035 @xref{Tracing, ,Tracing Your Parser}.
6036
6037 @item --locations
6038 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
6039
6040 @item -p @var{prefix}
6041 @itemx --name-prefix=@var{prefix}
6042 Pretend that @code{%name-prefix="@var{prefix}"} was specified.
6043 @xref{Decl Summary}.
6044
6045 @item -l
6046 @itemx --no-lines
6047 Don't put any @code{#line} preprocessor commands in the parser file.
6048 Ordinarily Bison puts them in the parser file so that the C compiler
6049 and debuggers will associate errors with your source file, the
6050 grammar file. This option causes them to associate errors with the
6051 parser file, treating it as an independent source file in its own right.
6052
6053 @item -n
6054 @itemx --no-parser
6055 Pretend that @code{%no-parser} was specified. @xref{Decl Summary}.
6056
6057 @item -k
6058 @itemx --token-table
6059 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
6060 @end table
6061
6062 @noindent
6063 Adjust the output:
6064
6065 @table @option
6066 @item -d
6067 @itemx --defines
6068 Pretend that @code{%defines} was specified, i.e., write an extra output
6069 file containing macro definitions for the token type names defined in
6070 the grammar and the semantic value type @code{YYSTYPE}, as well as a few
6071 @code{extern} variable declarations. @xref{Decl Summary}.
6072
6073 @item --defines=@var{defines-file}
6074 Same as above, but save in the file @var{defines-file}.
6075
6076 @item -b @var{file-prefix}
6077 @itemx --file-prefix=@var{prefix}
6078 Pretend that @code{%verbose} was specified, i.e, specify prefix to use
6079 for all Bison output file names. @xref{Decl Summary}.
6080
6081 @item -r @var{things}
6082 @itemx --report=@var{things}
6083 Write an extra output file containing verbose description of the comma
6084 separated list of @var{things} among:
6085
6086 @table @code
6087 @item state
6088 Description of the grammar, conflicts (resolved and unresolved), and
6089 @acronym{LALR} automaton.
6090
6091 @item lookahead
6092 Implies @code{state} and augments the description of the automaton with
6093 each rule's lookahead set.
6094
6095 @item itemset
6096 Implies @code{state} and augments the description of the automaton with
6097 the full set of items for each state, instead of its core only.
6098 @end table
6099
6100 For instance, on the following grammar
6101
6102 @item -v
6103 @itemx --verbose
6104 Pretend that @code{%verbose} was specified, i.e, write an extra output
6105 file containing verbose descriptions of the grammar and
6106 parser. @xref{Decl Summary}.
6107
6108 @item -o @var{filename}
6109 @itemx --output=@var{filename}
6110 Specify the @var{filename} for the parser file.
6111
6112 The other output files' names are constructed from @var{filename} as
6113 described under the @samp{-v} and @samp{-d} options.
6114
6115 @item -g
6116 Output a @acronym{VCG} definition of the @acronym{LALR}(1) grammar
6117 automaton computed by Bison. If the grammar file is @file{foo.y}, the
6118 @acronym{VCG} output file will
6119 be @file{foo.vcg}.
6120
6121 @item --graph=@var{graph-file}
6122 The behavior of @var{--graph} is the same than @samp{-g}. The only
6123 difference is that it has an optional argument which is the name of
6124 the output graph filename.
6125 @end table
6126
6127 @node Option Cross Key
6128 @section Option Cross Key
6129
6130 Here is a list of options, alphabetized by long option, to help you find
6131 the corresponding short option.
6132
6133 @tex
6134 \def\leaderfill{\leaders\hbox to 1em{\hss.\hss}\hfill}
6135
6136 {\tt
6137 \line{ --debug \leaderfill -t}
6138 \line{ --defines \leaderfill -d}
6139 \line{ --file-prefix \leaderfill -b}
6140 \line{ --graph \leaderfill -g}
6141 \line{ --help \leaderfill -h}
6142 \line{ --name-prefix \leaderfill -p}
6143 \line{ --no-lines \leaderfill -l}
6144 \line{ --no-parser \leaderfill -n}
6145 \line{ --output \leaderfill -o}
6146 \line{ --token-table \leaderfill -k}
6147 \line{ --verbose \leaderfill -v}
6148 \line{ --version \leaderfill -V}
6149 \line{ --yacc \leaderfill -y}
6150 }
6151 @end tex
6152
6153 @ifinfo
6154 @example
6155 --debug -t
6156 --defines=@var{defines-file} -d
6157 --file-prefix=@var{prefix} -b @var{file-prefix}
6158 --graph=@var{graph-file} -d
6159 --help -h
6160 --name-prefix=@var{prefix} -p @var{name-prefix}
6161 --no-lines -l
6162 --no-parser -n
6163 --output=@var{outfile} -o @var{outfile}
6164 --token-table -k
6165 --verbose -v
6166 --version -V
6167 --yacc -y
6168 @end example
6169 @end ifinfo
6170
6171 @c ================================================= Invoking Bison
6172
6173 @node FAQ
6174 @chapter Frequently Asked Questions
6175 @cindex frequently asked questions
6176 @cindex questions
6177
6178 Several questions about Bison come up occasionally. Here some of them
6179 are addressed.
6180
6181 @menu
6182 * Parser Stack Overflow:: Breaking the Stack Limits
6183 @end menu
6184
6185 @node Parser Stack Overflow
6186 @section Parser Stack Overflow
6187
6188 @display
6189 My parser returns with error with a @samp{parser stack overflow}
6190 message. What can I do?
6191 @end display
6192
6193 This question is already addressed elsewhere, @xref{Recursion,
6194 ,Recursive Rules}.
6195
6196 @c ================================================= Table of Symbols
6197
6198 @node Table of Symbols
6199 @appendix Bison Symbols
6200 @cindex Bison symbols, table of
6201 @cindex symbols in Bison, table of
6202
6203 @table @code
6204 @item @@$
6205 In an action, the location of the left-hand side of the rule.
6206 @xref{Locations, , Locations Overview}.
6207
6208 @item @@@var{n}
6209 In an action, the location of the @var{n}-th symbol of the right-hand
6210 side of the rule. @xref{Locations, , Locations Overview}.
6211
6212 @item $$
6213 In an action, the semantic value of the left-hand side of the rule.
6214 @xref{Actions}.
6215
6216 @item $@var{n}
6217 In an action, the semantic value of the @var{n}-th symbol of the
6218 right-hand side of the rule. @xref{Actions}.
6219
6220 @item $accept
6221 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
6222 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
6223 Start-Symbol}. It cannot be used in the grammar.
6224
6225 @item $end
6226 The predefined token marking the end of the token stream. It cannot be
6227 used in the grammar.
6228
6229 @item $undefined
6230 The predefined token onto which all undefined values returned by
6231 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
6232 @code{error}.
6233
6234 @item error
6235 A token name reserved for error recovery. This token may be used in
6236 grammar rules so as to allow the Bison parser to recognize an error in
6237 the grammar without halting the process. In effect, a sentence
6238 containing an error may be recognized as valid. On a parse error, the
6239 token @code{error} becomes the current look-ahead token. Actions
6240 corresponding to @code{error} are then executed, and the look-ahead
6241 token is reset to the token that originally caused the violation.
6242 @xref{Error Recovery}.
6243
6244 @item YYABORT
6245 Macro to pretend that an unrecoverable syntax error has occurred, by
6246 making @code{yyparse} return 1 immediately. The error reporting
6247 function @code{yyerror} is not called. @xref{Parser Function, ,The
6248 Parser Function @code{yyparse}}.
6249
6250 @item YYACCEPT
6251 Macro to pretend that a complete utterance of the language has been
6252 read, by making @code{yyparse} return 0 immediately.
6253 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6254
6255 @item YYBACKUP
6256 Macro to discard a value from the parser stack and fake a look-ahead
6257 token. @xref{Action Features, ,Special Features for Use in Actions}.
6258
6259 @item YYDEBUG
6260 Macro to define to equip the parser with tracing code. @xref{Tracing,
6261 ,Tracing Your Parser}.
6262
6263 @item YYERROR
6264 Macro to pretend that a syntax error has just been detected: call
6265 @code{yyerror} and then perform normal error recovery if possible
6266 (@pxref{Error Recovery}), or (if recovery is impossible) make
6267 @code{yyparse} return 1. @xref{Error Recovery}.
6268
6269 @item YYERROR_VERBOSE
6270 An obsolete macro that you define with @code{#define} in the Bison
6271 declarations section to request verbose, specific error message strings
6272 when @code{yyerror} is called. It doesn't matter what definition you
6273 use for @code{YYERROR_VERBOSE}, just whether you define it. Using
6274 @code{%error-verbose} is preferred.
6275
6276 @item YYINITDEPTH
6277 Macro for specifying the initial size of the parser stack.
6278 @xref{Stack Overflow}.
6279
6280 @item YYLEX_PARAM
6281 An obsolete macro for specifying an extra argument (or list of extra
6282 arguments) for @code{yyparse} to pass to @code{yylex}. he use of this
6283 macro is deprecated, and is supported only for Yacc like parsers.
6284 @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
6285
6286 @item YYLTYPE
6287 Macro for the data type of @code{yylloc}; a structure with four
6288 members. @xref{Location Type, , Data Types of Locations}.
6289
6290 @item yyltype
6291 Default value for YYLTYPE.
6292
6293 @item YYMAXDEPTH
6294 Macro for specifying the maximum size of the parser stack.
6295 @xref{Stack Overflow}.
6296
6297 @item YYPARSE_PARAM
6298 An obsolete macro for specifying the name of a parameter that
6299 @code{yyparse} should accept. The use of this macro is deprecated, and
6300 is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
6301 Conventions for Pure Parsers}.
6302
6303 @item YYRECOVERING
6304 Macro whose value indicates whether the parser is recovering from a
6305 syntax error. @xref{Action Features, ,Special Features for Use in Actions}.
6306
6307 @item YYSTACK_USE_ALLOCA
6308 Macro used to control the use of @code{alloca}. If defined to @samp{0},
6309 the parser will not use @code{alloca} but @code{malloc} when trying to
6310 grow its internal stacks. Do @emph{not} define @code{YYSTACK_USE_ALLOCA}
6311 to anything else.
6312
6313 @item YYSTYPE
6314 Macro for the data type of semantic values; @code{int} by default.
6315 @xref{Value Type, ,Data Types of Semantic Values}.
6316
6317 @item yychar
6318 External integer variable that contains the integer value of the current
6319 look-ahead token. (In a pure parser, it is a local variable within
6320 @code{yyparse}.) Error-recovery rule actions may examine this variable.
6321 @xref{Action Features, ,Special Features for Use in Actions}.
6322
6323 @item yyclearin
6324 Macro used in error-recovery rule actions. It clears the previous
6325 look-ahead token. @xref{Error Recovery}.
6326
6327 @item yydebug
6328 External integer variable set to zero by default. If @code{yydebug}
6329 is given a nonzero value, the parser will output information on input
6330 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
6331
6332 @item yyerrok
6333 Macro to cause parser to recover immediately to its normal mode
6334 after a parse error. @xref{Error Recovery}.
6335
6336 @item yyerror
6337 User-supplied function to be called by @code{yyparse} on error. The
6338 function receives one argument, a pointer to a character string
6339 containing an error message. @xref{Error Reporting, ,The Error
6340 Reporting Function @code{yyerror}}.
6341
6342 @item yylex
6343 User-supplied lexical analyzer function, called with no arguments to get
6344 the next token. @xref{Lexical, ,The Lexical Analyzer Function
6345 @code{yylex}}.
6346
6347 @item yylval
6348 External variable in which @code{yylex} should place the semantic
6349 value associated with a token. (In a pure parser, it is a local
6350 variable within @code{yyparse}, and its address is passed to
6351 @code{yylex}.) @xref{Token Values, ,Semantic Values of Tokens}.
6352
6353 @item yylloc
6354 External variable in which @code{yylex} should place the line and column
6355 numbers associated with a token. (In a pure parser, it is a local
6356 variable within @code{yyparse}, and its address is passed to
6357 @code{yylex}.) You can ignore this variable if you don't use the
6358 @samp{@@} feature in the grammar actions. @xref{Token Positions,
6359 ,Textual Positions of Tokens}.
6360
6361 @item yynerrs
6362 Global variable which Bison increments each time there is a parse error.
6363 (In a pure parser, it is a local variable within @code{yyparse}.)
6364 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
6365
6366 @item yyparse
6367 The parser function produced by Bison; call this function to start
6368 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6369
6370 @item %debug
6371 Equip the parser for debugging. @xref{Decl Summary}.
6372
6373 @item %defines
6374 Bison declaration to create a header file meant for the scanner.
6375 @xref{Decl Summary}.
6376
6377 @item %destructor
6378 Specifying how the parser should reclaim the memory associated to
6379 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
6380
6381 @item %dprec
6382 Bison declaration to assign a precedence to a rule that is used at parse
6383 time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
6384 @acronym{GLR} Parsers}.
6385
6386 @item %error-verbose
6387 Bison declaration to request verbose, specific error message strings
6388 when @code{yyerror} is called.
6389
6390 @item %file-prefix="@var{prefix}"
6391 Bison declaration to set the prefix of the output files. @xref{Decl
6392 Summary}.
6393
6394 @item %glr-parser
6395 Bison declaration to produce a @acronym{GLR} parser. @xref{GLR
6396 Parsers, ,Writing @acronym{GLR} Parsers}.
6397
6398 @c @item %source-extension
6399 @c Bison declaration to specify the generated parser output file extension.
6400 @c @xref{Decl Summary}.
6401 @c
6402 @c @item %header-extension
6403 @c Bison declaration to specify the generated parser header file extension
6404 @c if required. @xref{Decl Summary}.
6405
6406 @item %left
6407 Bison declaration to assign left associativity to token(s).
6408 @xref{Precedence Decl, ,Operator Precedence}.
6409
6410 @item %lex-param "@var{argument-declaration}" "@var{argument-name}"
6411 Bison declaration to specifying an additional parameter that
6412 @code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
6413 for Pure Parsers}.
6414
6415 @item %merge
6416 Bison declaration to assign a merging function to a rule. If there is a
6417 reduce/reduce conflict with a rule having the same merging function, the
6418 function is applied to the two semantic values to get a single result.
6419 @xref{GLR Parsers, ,Writing @acronym{GLR} Parsers}.
6420
6421 @item %name-prefix="@var{prefix}"
6422 Bison declaration to rename the external symbols. @xref{Decl Summary}.
6423
6424 @item %no-lines
6425 Bison declaration to avoid generating @code{#line} directives in the
6426 parser file. @xref{Decl Summary}.
6427
6428 @item %nonassoc
6429 Bison declaration to assign non-associativity to token(s).
6430 @xref{Precedence Decl, ,Operator Precedence}.
6431
6432 @item %output="@var{filename}"
6433 Bison declaration to set the name of the parser file. @xref{Decl
6434 Summary}.
6435
6436 @item %parse-param "@var{argument-declaration}" "@var{argument-name}"
6437 Bison declaration to specifying an additional parameter that
6438 @code{yyparse} should accept. @xref{Parser Function,, The Parser
6439 Function @code{yyparse}}.
6440
6441 @item %prec
6442 Bison declaration to assign a precedence to a specific rule.
6443 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
6444
6445 @item %pure-parser
6446 Bison declaration to request a pure (reentrant) parser.
6447 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6448
6449 @item %right
6450 Bison declaration to assign right associativity to token(s).
6451 @xref{Precedence Decl, ,Operator Precedence}.
6452
6453 @item %start
6454 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
6455 Start-Symbol}.
6456
6457 @item %token
6458 Bison declaration to declare token(s) without specifying precedence.
6459 @xref{Token Decl, ,Token Type Names}.
6460
6461 @item %token-table
6462 Bison declaration to include a token name table in the parser file.
6463 @xref{Decl Summary}.
6464
6465 @item %type
6466 Bison declaration to declare nonterminals. @xref{Type Decl,
6467 ,Nonterminal Symbols}.
6468
6469 @item %union
6470 Bison declaration to specify several possible data types for semantic
6471 values. @xref{Union Decl, ,The Collection of Value Types}.
6472 @end table
6473
6474 @sp 1
6475
6476 These are the punctuation and delimiters used in Bison input:
6477
6478 @table @samp
6479 @item %%
6480 Delimiter used to separate the grammar rule section from the
6481 Bison declarations section or the epilogue.
6482 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
6483
6484 @item %@{ %@}
6485 All code listed between @samp{%@{} and @samp{%@}} is copied directly to
6486 the output file uninterpreted. Such code forms the prologue of the input
6487 file. @xref{Grammar Outline, ,Outline of a Bison
6488 Grammar}.
6489
6490 @item /*@dots{}*/
6491 Comment delimiters, as in C.
6492
6493 @item :
6494 Separates a rule's result from its components. @xref{Rules, ,Syntax of
6495 Grammar Rules}.
6496
6497 @item ;
6498 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
6499
6500 @item |
6501 Separates alternate rules for the same result nonterminal.
6502 @xref{Rules, ,Syntax of Grammar Rules}.
6503 @end table
6504
6505 @node Glossary
6506 @appendix Glossary
6507 @cindex glossary
6508
6509 @table @asis
6510 @item Backus-Naur Form (@acronym{BNF}; also called ``Backus Normal Form'')
6511 Formal method of specifying context-free grammars originally proposed
6512 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
6513 committee document contributing to what became the Algol 60 report.
6514 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6515
6516 @item Context-free grammars
6517 Grammars specified as rules that can be applied regardless of context.
6518 Thus, if there is a rule which says that an integer can be used as an
6519 expression, integers are allowed @emph{anywhere} an expression is
6520 permitted. @xref{Language and Grammar, ,Languages and Context-Free
6521 Grammars}.
6522
6523 @item Dynamic allocation
6524 Allocation of memory that occurs during execution, rather than at
6525 compile time or on entry to a function.
6526
6527 @item Empty string
6528 Analogous to the empty set in set theory, the empty string is a
6529 character string of length zero.
6530
6531 @item Finite-state stack machine
6532 A ``machine'' that has discrete states in which it is said to exist at
6533 each instant in time. As input to the machine is processed, the
6534 machine moves from state to state as specified by the logic of the
6535 machine. In the case of the parser, the input is the language being
6536 parsed, and the states correspond to various stages in the grammar
6537 rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
6538
6539 @item Generalized @acronym{LR} (@acronym{GLR})
6540 A parsing algorithm that can handle all context-free grammars, including those
6541 that are not @acronym{LALR}(1). It resolves situations that Bison's
6542 usual @acronym{LALR}(1)
6543 algorithm cannot by effectively splitting off multiple parsers, trying all
6544 possible parsers, and discarding those that fail in the light of additional
6545 right context. @xref{Generalized LR Parsing, ,Generalized
6546 @acronym{LR} Parsing}.
6547
6548 @item Grouping
6549 A language construct that is (in general) grammatically divisible;
6550 for example, `expression' or `declaration' in C@.
6551 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6552
6553 @item Infix operator
6554 An arithmetic operator that is placed between the operands on which it
6555 performs some operation.
6556
6557 @item Input stream
6558 A continuous flow of data between devices or programs.
6559
6560 @item Language construct
6561 One of the typical usage schemas of the language. For example, one of
6562 the constructs of the C language is the @code{if} statement.
6563 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6564
6565 @item Left associativity
6566 Operators having left associativity are analyzed from left to right:
6567 @samp{a+b+c} first computes @samp{a+b} and then combines with
6568 @samp{c}. @xref{Precedence, ,Operator Precedence}.
6569
6570 @item Left recursion
6571 A rule whose result symbol is also its first component symbol; for
6572 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
6573 Rules}.
6574
6575 @item Left-to-right parsing
6576 Parsing a sentence of a language by analyzing it token by token from
6577 left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
6578
6579 @item Lexical analyzer (scanner)
6580 A function that reads an input stream and returns tokens one by one.
6581 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
6582
6583 @item Lexical tie-in
6584 A flag, set by actions in the grammar rules, which alters the way
6585 tokens are parsed. @xref{Lexical Tie-ins}.
6586
6587 @item Literal string token
6588 A token which consists of two or more fixed characters. @xref{Symbols}.
6589
6590 @item Look-ahead token
6591 A token already read but not yet shifted. @xref{Look-Ahead, ,Look-Ahead
6592 Tokens}.
6593
6594 @item @acronym{LALR}(1)
6595 The class of context-free grammars that Bison (like most other parser
6596 generators) can handle; a subset of @acronym{LR}(1). @xref{Mystery
6597 Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
6598
6599 @item @acronym{LR}(1)
6600 The class of context-free grammars in which at most one token of
6601 look-ahead is needed to disambiguate the parsing of any piece of input.
6602
6603 @item Nonterminal symbol
6604 A grammar symbol standing for a grammatical construct that can
6605 be expressed through rules in terms of smaller constructs; in other
6606 words, a construct that is not a token. @xref{Symbols}.
6607
6608 @item Parse error
6609 An error encountered during parsing of an input stream due to invalid
6610 syntax. @xref{Error Recovery}.
6611
6612 @item Parser
6613 A function that recognizes valid sentences of a language by analyzing
6614 the syntax structure of a set of tokens passed to it from a lexical
6615 analyzer.
6616
6617 @item Postfix operator
6618 An arithmetic operator that is placed after the operands upon which it
6619 performs some operation.
6620
6621 @item Reduction
6622 Replacing a string of nonterminals and/or terminals with a single
6623 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
6624 Parser Algorithm}.
6625
6626 @item Reentrant
6627 A reentrant subprogram is a subprogram which can be in invoked any
6628 number of times in parallel, without interference between the various
6629 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6630
6631 @item Reverse polish notation
6632 A language in which all operators are postfix operators.
6633
6634 @item Right recursion
6635 A rule whose result symbol is also its last component symbol; for
6636 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
6637 Rules}.
6638
6639 @item Semantics
6640 In computer languages, the semantics are specified by the actions
6641 taken for each instance of the language, i.e., the meaning of
6642 each statement. @xref{Semantics, ,Defining Language Semantics}.
6643
6644 @item Shift
6645 A parser is said to shift when it makes the choice of analyzing
6646 further input from the stream rather than reducing immediately some
6647 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
6648
6649 @item Single-character literal
6650 A single character that is recognized and interpreted as is.
6651 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
6652
6653 @item Start symbol
6654 The nonterminal symbol that stands for a complete valid utterance in
6655 the language being parsed. The start symbol is usually listed as the
6656 first nonterminal symbol in a language specification.
6657 @xref{Start Decl, ,The Start-Symbol}.
6658
6659 @item Symbol table
6660 A data structure where symbol names and associated data are stored
6661 during parsing to allow for recognition and use of existing
6662 information in repeated uses of a symbol. @xref{Multi-function Calc}.
6663
6664 @item Token
6665 A basic, grammatically indivisible unit of a language. The symbol
6666 that describes a token in the grammar is a terminal symbol.
6667 The input of the Bison parser is a stream of tokens which comes from
6668 the lexical analyzer. @xref{Symbols}.
6669
6670 @item Terminal symbol
6671 A grammar symbol that has no rules in the grammar and therefore is
6672 grammatically indivisible. The piece of text it represents is a token.
6673 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6674 @end table
6675
6676 @node Copying This Manual
6677 @appendix Copying This Manual
6678
6679 @menu
6680 * GNU Free Documentation License:: License for copying this manual.
6681 @end menu
6682
6683 @include fdl.texi
6684
6685 @node Index
6686 @unnumbered Index
6687
6688 @printindex cp
6689
6690 @bye