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