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