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