]> git.saurik.com Git - bison.git/blob - doc/bison.texinfo
Update to GPLv3.
[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 want to document %default-prec and %no-default-prec.
16 @c This feature is experimental and may change in future Bison versions.
17 @c @set defaultprec
18
19 @ifnotinfo
20 @syncodeindex fn cp
21 @syncodeindex vr cp
22 @syncodeindex tp cp
23 @end ifnotinfo
24 @ifinfo
25 @synindex fn cp
26 @synindex vr cp
27 @synindex tp cp
28 @end ifinfo
29 @comment %**end of header
30
31 @copying
32
33 This manual is for @acronym{GNU} Bison (version @value{VERSION},
34 @value{UPDATED}), the @acronym{GNU} parser generator.
35
36 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
37 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
38
39 @quotation
40 Permission is granted to copy, distribute and/or modify this document
41 under the terms of the @acronym{GNU} Free Documentation License,
42 Version 1.2 or any later version published by the Free Software
43 Foundation; with no Invariant Sections, with the Front-Cover texts
44 being ``A @acronym{GNU} Manual,'' and with the Back-Cover Texts as in
45 (a) below. A copy of the license is included in the section entitled
46 ``@acronym{GNU} Free Documentation License.''
47
48 (a) The @acronym{FSF}'s Back-Cover Text is: ``You have freedom to copy
49 and modify this @acronym{GNU} Manual, like @acronym{GNU} software.
50 Copies published by the Free Software Foundation raise funds for
51 @acronym{GNU} development.''
52 @end quotation
53 @end copying
54
55 @dircategory Software development
56 @direntry
57 * bison: (bison). @acronym{GNU} parser generator (Yacc replacement).
58 @end direntry
59
60 @titlepage
61 @title Bison
62 @subtitle The Yacc-compatible Parser Generator
63 @subtitle @value{UPDATED}, Bison Version @value{VERSION}
64
65 @author by Charles Donnelly and Richard Stallman
66
67 @page
68 @vskip 0pt plus 1filll
69 @insertcopying
70 @sp 2
71 Published by the Free Software Foundation @*
72 51 Franklin Street, Fifth Floor @*
73 Boston, MA 02110-1301 USA @*
74 Printed copies are available from the Free Software Foundation.@*
75 @acronym{ISBN} 1-882114-44-2
76 @sp 2
77 Cover art by Etienne Suvasa.
78 @end titlepage
79
80 @contents
81
82 @ifnottex
83 @node Top
84 @top Bison
85 @insertcopying
86 @end ifnottex
87
88 @menu
89 * Introduction::
90 * Conditions::
91 * Copying:: The @acronym{GNU} General Public License says
92 how you can copy and share Bison
93
94 Tutorial sections:
95 * Concepts:: Basic concepts for understanding Bison.
96 * Examples:: Three simple explained examples of using Bison.
97
98 Reference sections:
99 * Grammar File:: Writing Bison declarations and rules.
100 * Interface:: C-language interface to the parser function @code{yyparse}.
101 * Algorithm:: How the Bison parser works at run-time.
102 * Error Recovery:: Writing rules for error recovery.
103 * Context Dependency:: What to do if your language syntax is too
104 messy for Bison to handle straightforwardly.
105 * Debugging:: Understanding or debugging Bison parsers.
106 * Invocation:: How to run Bison (to produce the parser source file).
107 * Other Languages:: Creating C++ and Java parsers.
108 * FAQ:: Frequently Asked Questions
109 * Table of Symbols:: All the keywords of the Bison language are explained.
110 * Glossary:: Basic concepts are explained.
111 * Copying This Manual:: License for copying this manual.
112 * Index:: Cross-references to the text.
113
114 @detailmenu
115 --- The Detailed Node Listing ---
116
117 The Concepts of Bison
118
119 * Language and Grammar:: Languages and context-free grammars,
120 as mathematical ideas.
121 * Grammar in Bison:: How we represent grammars for Bison's sake.
122 * Semantic Values:: Each token or syntactic grouping can have
123 a semantic value (the value of an integer,
124 the name of an identifier, etc.).
125 * Semantic Actions:: Each rule can have an action containing C code.
126 * GLR Parsers:: Writing parsers for general context-free languages.
127 * Locations Overview:: Tracking Locations.
128 * Bison Parser:: What are Bison's input and output,
129 how is the output used?
130 * Stages:: Stages in writing and running Bison grammars.
131 * Grammar Layout:: Overall structure of a Bison grammar file.
132
133 Writing @acronym{GLR} Parsers
134
135 * Simple GLR Parsers:: Using @acronym{GLR} parsers on unambiguous grammars.
136 * Merging GLR Parses:: Using @acronym{GLR} parsers to resolve ambiguities.
137 * GLR Semantic Actions:: Deferred semantic actions have special concerns.
138 * Compiler Requirements:: @acronym{GLR} parsers require a modern C compiler.
139
140 Examples
141
142 * RPN Calc:: Reverse polish notation calculator;
143 a first example with no operator precedence.
144 * Infix Calc:: Infix (algebraic) notation calculator.
145 Operator precedence is introduced.
146 * Simple Error Recovery:: Continuing after syntax errors.
147 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
148 * Multi-function Calc:: Calculator with memory and trig functions.
149 It uses multiple data-types for semantic values.
150 * Exercises:: Ideas for improving the multi-function calculator.
151
152 Reverse Polish Notation Calculator
153
154 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
155 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
156 * Lexer: Rpcalc Lexer. The lexical analyzer.
157 * Main: Rpcalc Main. The controlling function.
158 * Error: Rpcalc Error. The error reporting function.
159 * Gen: Rpcalc Gen. Running Bison on the grammar file.
160 * Comp: Rpcalc Compile. Run the C compiler on the output code.
161
162 Grammar Rules for @code{rpcalc}
163
164 * Rpcalc Input::
165 * Rpcalc Line::
166 * Rpcalc Expr::
167
168 Location Tracking Calculator: @code{ltcalc}
169
170 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
171 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
172 * Lexer: Ltcalc Lexer. The lexical analyzer.
173
174 Multi-Function Calculator: @code{mfcalc}
175
176 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
177 * Rules: Mfcalc Rules. Grammar rules for the calculator.
178 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
179
180 Bison Grammar Files
181
182 * Grammar Outline:: Overall layout of the grammar file.
183 * Symbols:: Terminal and nonterminal symbols.
184 * Rules:: How to write grammar rules.
185 * Recursion:: Writing recursive rules.
186 * Semantics:: Semantic values and actions.
187 * Locations:: Locations and actions.
188 * Declarations:: All kinds of Bison declarations are described here.
189 * Multiple Parsers:: Putting more than one Bison parser in one program.
190
191 Outline of a Bison Grammar
192
193 * Prologue:: Syntax and usage of the prologue.
194 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
195 * Bison Declarations:: Syntax and usage of the Bison declarations section.
196 * Grammar Rules:: Syntax and usage of the grammar rules section.
197 * Epilogue:: Syntax and usage of the epilogue.
198
199 Defining Language Semantics
200
201 * Value Type:: Specifying one data type for all semantic values.
202 * Multiple Types:: Specifying several alternative data types.
203 * Actions:: An action is the semantic definition of a grammar rule.
204 * Action Types:: Specifying data types for actions to operate on.
205 * Mid-Rule Actions:: Most actions go at the end of a rule.
206 This says when, why and how to use the exceptional
207 action in the middle of a rule.
208
209 Tracking Locations
210
211 * Location Type:: Specifying a data type for locations.
212 * Actions and Locations:: Using locations in actions.
213 * Location Default Action:: Defining a general way to compute locations.
214
215 Bison Declarations
216
217 * Require Decl:: Requiring a Bison version.
218 * Token Decl:: Declaring terminal symbols.
219 * Precedence Decl:: Declaring terminals with precedence and associativity.
220 * Union Decl:: Declaring the set of all semantic value types.
221 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
222 * Initial Action Decl:: Code run before parsing starts.
223 * Destructor Decl:: Declaring how symbols are freed.
224 * Expect Decl:: Suppressing warnings about parsing conflicts.
225 * Start Decl:: Specifying the start symbol.
226 * Pure Decl:: Requesting a reentrant parser.
227 * Decl Summary:: Table of all Bison declarations.
228
229 Parser C-Language Interface
230
231 * Parser Function:: How to call @code{yyparse} and what it returns.
232 * Lexical:: You must supply a function @code{yylex}
233 which reads tokens.
234 * Error Reporting:: You must supply a function @code{yyerror}.
235 * Action Features:: Special features for use in actions.
236 * Internationalization:: How to let the parser speak in the user's
237 native language.
238
239 The Lexical Analyzer Function @code{yylex}
240
241 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
242 * Token Values:: How @code{yylex} must return the semantic value
243 of the token it has read.
244 * Token Locations:: How @code{yylex} must return the text location
245 (line number, etc.) of the token, if the
246 actions want that.
247 * Pure Calling:: How the calling convention differs
248 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
249
250 The Bison Parser Algorithm
251
252 * Lookahead:: Parser looks one token ahead when deciding what to do.
253 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
254 * Precedence:: Operator precedence works by resolving conflicts.
255 * Contextual Precedence:: When an operator's precedence depends on context.
256 * Parser States:: The parser is a finite-state-machine with stack.
257 * Reduce/Reduce:: When two rules are applicable in the same situation.
258 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
259 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
260 * Memory Management:: What happens when memory is exhausted. How to avoid it.
261
262 Operator Precedence
263
264 * Why Precedence:: An example showing why precedence is needed.
265 * Using Precedence:: How to specify precedence in Bison grammars.
266 * Precedence Examples:: How these features are used in the previous example.
267 * How Precedence:: How they work.
268
269 Handling Context Dependencies
270
271 * Semantic Tokens:: Token parsing can depend on the semantic context.
272 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
273 * Tie-in Recovery:: Lexical tie-ins have implications for how
274 error recovery rules must be written.
275
276 Debugging Your Parser
277
278 * Understanding:: Understanding the structure of your parser.
279 * Tracing:: Tracing the execution of your parser.
280
281 Invoking Bison
282
283 * Bison Options:: All the options described in detail,
284 in alphabetical order by short options.
285 * Option Cross Key:: Alphabetical list of long options.
286 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
287
288 Parsers Written In Other Languages
289
290 * C++ Parsers:: The interface to generate C++ parser classes
291 * Java Parsers:: The interface to generate Java parser classes
292
293 C++ Parsers
294
295 * C++ Bison Interface:: Asking for C++ parser generation
296 * C++ Semantic Values:: %union vs. C++
297 * C++ Location Values:: The position and location classes
298 * C++ Parser Interface:: Instantiating and running the parser
299 * C++ Scanner Interface:: Exchanges between yylex and parse
300 * A Complete C++ Example:: Demonstrating their use
301
302 A Complete C++ Example
303
304 * Calc++ --- C++ Calculator:: The specifications
305 * Calc++ Parsing Driver:: An active parsing context
306 * Calc++ Parser:: A parser class
307 * Calc++ Scanner:: A pure C++ Flex scanner
308 * Calc++ Top Level:: Conducting the band
309
310 Java Parsers
311
312 * Java Bison Interface:: Asking for Java parser generation
313 * Java Semantic Values:: %type and %token vs. Java
314 * Java Location Values:: The position and location classes
315 * Java Parser Interface:: Instantiating and running the parser
316 * Java Scanner Interface:: Java scanners, and pure parsers
317 * Java Differences:: Differences between C/C++ and Java Grammars
318
319 Frequently Asked Questions
320
321 * Memory Exhausted:: Breaking the Stack Limits
322 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
323 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
324 * Implementing Gotos/Loops:: Control Flow in the Calculator
325 * Multiple start-symbols:: Factoring closely related grammars
326 * Secure? Conform?:: Is Bison @acronym{POSIX} safe?
327 * I can't build Bison:: Troubleshooting
328 * Where can I find help?:: Troubleshouting
329 * Bug Reports:: Troublereporting
330 * Other Languages:: Parsers in Java and others
331 * Beta Testing:: Experimenting development versions
332 * Mailing Lists:: Meeting other Bison users
333
334 Copying This Manual
335
336 * Copying This Manual:: License for copying this manual.
337
338 @end detailmenu
339 @end menu
340
341 @node Introduction
342 @unnumbered Introduction
343 @cindex introduction
344
345 @dfn{Bison} is a general-purpose parser generator that converts an
346 annotated context-free grammar into an @acronym{LALR}(1) or
347 @acronym{GLR} parser for that grammar. Once you are proficient with
348 Bison, you can use it to develop a wide range of language parsers, from those
349 used in simple desk calculators to complex programming languages.
350
351 Bison is upward compatible with Yacc: all properly-written Yacc grammars
352 ought to work with Bison with no change. Anyone familiar with Yacc
353 should be able to use Bison with little trouble. You need to be fluent in
354 C or C++ programming in order to use Bison or to understand this manual.
355
356 We begin with tutorial chapters that explain the basic concepts of using
357 Bison and show three explained examples, each building on the last. If you
358 don't know Bison or Yacc, start by reading these chapters. Reference
359 chapters follow which describe specific aspects of Bison in detail.
360
361 Bison was written primarily by Robert Corbett; Richard Stallman made it
362 Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
363 multi-character string literals and other features.
364
365 This edition corresponds to version @value{VERSION} of Bison.
366
367 @node Conditions
368 @unnumbered Conditions for Using Bison
369
370 The distribution terms for Bison-generated parsers permit using the
371 parsers in nonfree programs. Before Bison version 2.2, these extra
372 permissions applied only when Bison was generating @acronym{LALR}(1)
373 parsers in C@. And before Bison version 1.24, Bison-generated
374 parsers could be used only in programs that were free software.
375
376 The other @acronym{GNU} programming tools, such as the @acronym{GNU} C
377 compiler, have never
378 had such a requirement. They could always be used for nonfree
379 software. The reason Bison was different was not due to a special
380 policy decision; it resulted from applying the usual General Public
381 License to all of the Bison source code.
382
383 The output of the Bison utility---the Bison parser file---contains a
384 verbatim copy of a sizable piece of Bison, which is the code for the
385 parser's implementation. (The actions from your grammar are inserted
386 into this implementation at one point, but most of the rest of the
387 implementation is not changed.) When we applied the @acronym{GPL}
388 terms to the skeleton code for the parser's implementation,
389 the effect was to restrict the use of Bison output to free software.
390
391 We didn't change the terms because of sympathy for people who want to
392 make software proprietary. @strong{Software should be free.} But we
393 concluded that limiting Bison's use to free software was doing little to
394 encourage people to make other software free. So we decided to make the
395 practical conditions for using Bison match the practical conditions for
396 using the other @acronym{GNU} tools.
397
398 This exception applies when Bison is generating code for a parser.
399 You can tell whether the exception applies to a Bison output file by
400 inspecting the file for text beginning with ``As a special
401 exception@dots{}''. The text spells out the exact terms of the
402 exception.
403
404 @node Copying
405 @unnumbered GNU GENERAL PUBLIC LICENSE
406 @include gpl-3.0.texi
407
408 @node Concepts
409 @chapter The Concepts of Bison
410
411 This chapter introduces many of the basic concepts without which the
412 details of Bison will not make sense. If you do not already know how to
413 use Bison or Yacc, we suggest you start by reading this chapter carefully.
414
415 @menu
416 * Language and Grammar:: Languages and context-free grammars,
417 as mathematical ideas.
418 * Grammar in Bison:: How we represent grammars for Bison's sake.
419 * Semantic Values:: Each token or syntactic grouping can have
420 a semantic value (the value of an integer,
421 the name of an identifier, etc.).
422 * Semantic Actions:: Each rule can have an action containing C code.
423 * GLR Parsers:: Writing parsers for general context-free languages.
424 * Locations Overview:: Tracking Locations.
425 * Bison Parser:: What are Bison's input and output,
426 how is the output used?
427 * Stages:: Stages in writing and running Bison grammars.
428 * Grammar Layout:: Overall structure of a Bison grammar file.
429 @end menu
430
431 @node Language and Grammar
432 @section Languages and Context-Free Grammars
433
434 @cindex context-free grammar
435 @cindex grammar, context-free
436 In order for Bison to parse a language, it must be described by a
437 @dfn{context-free grammar}. This means that you specify one or more
438 @dfn{syntactic groupings} and give rules for constructing them from their
439 parts. For example, in the C language, one kind of grouping is called an
440 `expression'. One rule for making an expression might be, ``An expression
441 can be made of a minus sign and another expression''. Another would be,
442 ``An expression can be an integer''. As you can see, rules are often
443 recursive, but there must be at least one rule which leads out of the
444 recursion.
445
446 @cindex @acronym{BNF}
447 @cindex Backus-Naur form
448 The most common formal system for presenting such rules for humans to read
449 is @dfn{Backus-Naur Form} or ``@acronym{BNF}'', which was developed in
450 order to specify the language Algol 60. Any grammar expressed in
451 @acronym{BNF} is a context-free grammar. The input to Bison is
452 essentially machine-readable @acronym{BNF}.
453
454 @cindex @acronym{LALR}(1) grammars
455 @cindex @acronym{LR}(1) grammars
456 There are various important subclasses of context-free grammar. Although it
457 can handle almost all context-free grammars, Bison is optimized for what
458 are called @acronym{LALR}(1) grammars.
459 In brief, in these grammars, it must be possible to
460 tell how to parse any portion of an input string with just a single
461 token of lookahead. Strictly speaking, that is a description of an
462 @acronym{LR}(1) grammar, and @acronym{LALR}(1) involves additional
463 restrictions that are
464 hard to explain simply; but it is rare in actual practice to find an
465 @acronym{LR}(1) grammar that fails to be @acronym{LALR}(1).
466 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}, for
467 more information on this.
468
469 @cindex @acronym{GLR} parsing
470 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
471 @cindex ambiguous grammars
472 @cindex nondeterministic parsing
473
474 Parsers for @acronym{LALR}(1) grammars are @dfn{deterministic}, meaning
475 roughly that the next grammar rule to apply at any point in the input is
476 uniquely determined by the preceding input and a fixed, finite portion
477 (called a @dfn{lookahead}) of the remaining input. A context-free
478 grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
479 apply the grammar rules to get the same inputs. Even unambiguous
480 grammars can be @dfn{nondeterministic}, meaning that no fixed
481 lookahead always suffices to determine the next grammar rule to apply.
482 With the proper declarations, Bison is also able to parse these more
483 general context-free grammars, using a technique known as @acronym{GLR}
484 parsing (for Generalized @acronym{LR}). Bison's @acronym{GLR} parsers
485 are able to handle any context-free grammar for which the number of
486 possible parses of any given string is finite.
487
488 @cindex symbols (abstract)
489 @cindex token
490 @cindex syntactic grouping
491 @cindex grouping, syntactic
492 In the formal grammatical rules for a language, each kind of syntactic
493 unit or grouping is named by a @dfn{symbol}. Those which are built by
494 grouping smaller constructs according to grammatical rules are called
495 @dfn{nonterminal symbols}; those which can't be subdivided are called
496 @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
497 corresponding to a single terminal symbol a @dfn{token}, and a piece
498 corresponding to a single nonterminal symbol a @dfn{grouping}.
499
500 We can use the C language as an example of what symbols, terminal and
501 nonterminal, mean. The tokens of C are identifiers, constants (numeric
502 and string), and the various keywords, arithmetic operators and
503 punctuation marks. So the terminal symbols of a grammar for C include
504 `identifier', `number', `string', plus one symbol for each keyword,
505 operator or punctuation mark: `if', `return', `const', `static', `int',
506 `char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
507 (These tokens can be subdivided into characters, but that is a matter of
508 lexicography, not grammar.)
509
510 Here is a simple C function subdivided into tokens:
511
512 @ifinfo
513 @example
514 int /* @r{keyword `int'} */
515 square (int x) /* @r{identifier, open-paren, keyword `int',}
516 @r{identifier, close-paren} */
517 @{ /* @r{open-brace} */
518 return x * x; /* @r{keyword `return', identifier, asterisk,}
519 @r{identifier, semicolon} */
520 @} /* @r{close-brace} */
521 @end example
522 @end ifinfo
523 @ifnotinfo
524 @example
525 int /* @r{keyword `int'} */
526 square (int x) /* @r{identifier, open-paren, keyword `int', identifier, close-paren} */
527 @{ /* @r{open-brace} */
528 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
529 @} /* @r{close-brace} */
530 @end example
531 @end ifnotinfo
532
533 The syntactic groupings of C include the expression, the statement, the
534 declaration, and the function definition. These are represented in the
535 grammar of C by nonterminal symbols `expression', `statement',
536 `declaration' and `function definition'. The full grammar uses dozens of
537 additional language constructs, each with its own nonterminal symbol, in
538 order to express the meanings of these four. The example above is a
539 function definition; it contains one declaration, and one statement. In
540 the statement, each @samp{x} is an expression and so is @samp{x * x}.
541
542 Each nonterminal symbol must have grammatical rules showing how it is made
543 out of simpler constructs. For example, one kind of C statement is the
544 @code{return} statement; this would be described with a grammar rule which
545 reads informally as follows:
546
547 @quotation
548 A `statement' can be made of a `return' keyword, an `expression' and a
549 `semicolon'.
550 @end quotation
551
552 @noindent
553 There would be many other rules for `statement', one for each kind of
554 statement in C.
555
556 @cindex start symbol
557 One nonterminal symbol must be distinguished as the special one which
558 defines a complete utterance in the language. It is called the @dfn{start
559 symbol}. In a compiler, this means a complete input program. In the C
560 language, the nonterminal symbol `sequence of definitions and declarations'
561 plays this role.
562
563 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
564 program---but it is not valid as an @emph{entire} C program. In the
565 context-free grammar of C, this follows from the fact that `expression' is
566 not the start symbol.
567
568 The Bison parser reads a sequence of tokens as its input, and groups the
569 tokens using the grammar rules. If the input is valid, the end result is
570 that the entire token sequence reduces to a single grouping whose symbol is
571 the grammar's start symbol. If we use a grammar for C, the entire input
572 must be a `sequence of definitions and declarations'. If not, the parser
573 reports a syntax error.
574
575 @node Grammar in Bison
576 @section From Formal Rules to Bison Input
577 @cindex Bison grammar
578 @cindex grammar, Bison
579 @cindex formal grammar
580
581 A formal grammar is a mathematical construct. To define the language
582 for Bison, you must write a file expressing the grammar in Bison syntax:
583 a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
584
585 A nonterminal symbol in the formal grammar is represented in Bison input
586 as an identifier, like an identifier in C@. By convention, it should be
587 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
588
589 The Bison representation for a terminal symbol is also called a @dfn{token
590 type}. Token types as well can be represented as C-like identifiers. By
591 convention, these identifiers should be upper case to distinguish them from
592 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
593 @code{RETURN}. A terminal symbol that stands for a particular keyword in
594 the language should be named after that keyword converted to upper case.
595 The terminal symbol @code{error} is reserved for error recovery.
596 @xref{Symbols}.
597
598 A terminal symbol can also be represented as a character literal, just like
599 a C character constant. You should do this whenever a token is just a
600 single character (parenthesis, plus-sign, etc.): use that same character in
601 a literal as the terminal symbol for that token.
602
603 A third way to represent a terminal symbol is with a C string constant
604 containing several characters. @xref{Symbols}, for more information.
605
606 The grammar rules also have an expression in Bison syntax. For example,
607 here is the Bison rule for a C @code{return} statement. The semicolon in
608 quotes is a literal character token, representing part of the C syntax for
609 the statement; the naked semicolon, and the colon, are Bison punctuation
610 used in every rule.
611
612 @example
613 stmt: RETURN expr ';'
614 ;
615 @end example
616
617 @noindent
618 @xref{Rules, ,Syntax of Grammar Rules}.
619
620 @node Semantic Values
621 @section Semantic Values
622 @cindex semantic value
623 @cindex value, semantic
624
625 A formal grammar selects tokens only by their classifications: for example,
626 if a rule mentions the terminal symbol `integer constant', it means that
627 @emph{any} integer constant is grammatically valid in that position. The
628 precise value of the constant is irrelevant to how to parse the input: if
629 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
630 grammatical.
631
632 But the precise value is very important for what the input means once it is
633 parsed. A compiler is useless if it fails to distinguish between 4, 1 and
634 3989 as constants in the program! Therefore, each token in a Bison grammar
635 has both a token type and a @dfn{semantic value}. @xref{Semantics,
636 ,Defining Language Semantics},
637 for details.
638
639 The token type is a terminal symbol defined in the grammar, such as
640 @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
641 you need to know to decide where the token may validly appear and how to
642 group it with other tokens. The grammar rules know nothing about tokens
643 except their types.
644
645 The semantic value has all the rest of the information about the
646 meaning of the token, such as the value of an integer, or the name of an
647 identifier. (A token such as @code{','} which is just punctuation doesn't
648 need to have any semantic value.)
649
650 For example, an input token might be classified as token type
651 @code{INTEGER} and have the semantic value 4. Another input token might
652 have the same token type @code{INTEGER} but value 3989. When a grammar
653 rule says that @code{INTEGER} is allowed, either of these tokens is
654 acceptable because each is an @code{INTEGER}. When the parser accepts the
655 token, it keeps track of the token's semantic value.
656
657 Each grouping can also have a semantic value as well as its nonterminal
658 symbol. For example, in a calculator, an expression typically has a
659 semantic value that is a number. In a compiler for a programming
660 language, an expression typically has a semantic value that is a tree
661 structure describing the meaning of the expression.
662
663 @node Semantic Actions
664 @section Semantic Actions
665 @cindex semantic actions
666 @cindex actions, semantic
667
668 In order to be useful, a program must do more than parse input; it must
669 also produce some output based on the input. In a Bison grammar, a grammar
670 rule can have an @dfn{action} made up of C statements. Each time the
671 parser recognizes a match for that rule, the action is executed.
672 @xref{Actions}.
673
674 Most of the time, the purpose of an action is to compute the semantic value
675 of the whole construct from the semantic values of its parts. For example,
676 suppose we have a rule which says an expression can be the sum of two
677 expressions. When the parser recognizes such a sum, each of the
678 subexpressions has a semantic value which describes how it was built up.
679 The action for this rule should create a similar sort of value for the
680 newly recognized larger expression.
681
682 For example, here is a rule that says an expression can be the sum of
683 two subexpressions:
684
685 @example
686 expr: expr '+' expr @{ $$ = $1 + $3; @}
687 ;
688 @end example
689
690 @noindent
691 The action says how to produce the semantic value of the sum expression
692 from the values of the two subexpressions.
693
694 @node GLR Parsers
695 @section Writing @acronym{GLR} Parsers
696 @cindex @acronym{GLR} parsing
697 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
698 @findex %glr-parser
699 @cindex conflicts
700 @cindex shift/reduce conflicts
701 @cindex reduce/reduce conflicts
702
703 In some grammars, Bison's standard
704 @acronym{LALR}(1) parsing algorithm cannot decide whether to apply a
705 certain grammar rule at a given point. That is, it may not be able to
706 decide (on the basis of the input read so far) which of two possible
707 reductions (applications of a grammar rule) applies, or whether to apply
708 a reduction or read more of the input and apply a reduction later in the
709 input. These are known respectively as @dfn{reduce/reduce} conflicts
710 (@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
711 (@pxref{Shift/Reduce}).
712
713 To use a grammar that is not easily modified to be @acronym{LALR}(1), a
714 more general parsing algorithm is sometimes necessary. If you include
715 @code{%glr-parser} among the Bison declarations in your file
716 (@pxref{Grammar Outline}), the result is a Generalized @acronym{LR}
717 (@acronym{GLR}) parser. These parsers handle Bison grammars that
718 contain no unresolved conflicts (i.e., after applying precedence
719 declarations) identically to @acronym{LALR}(1) parsers. However, when
720 faced with unresolved shift/reduce and reduce/reduce conflicts,
721 @acronym{GLR} parsers use the simple expedient of doing both,
722 effectively cloning the parser to follow both possibilities. Each of
723 the resulting parsers can again split, so that at any given time, there
724 can be any number of possible parses being explored. The parsers
725 proceed in lockstep; that is, all of them consume (shift) a given input
726 symbol before any of them proceed to the next. Each of the cloned
727 parsers eventually meets one of two possible fates: either it runs into
728 a parsing error, in which case it simply vanishes, or it merges with
729 another parser, because the two of them have reduced the input to an
730 identical set of symbols.
731
732 During the time that there are multiple parsers, semantic actions are
733 recorded, but not performed. When a parser disappears, its recorded
734 semantic actions disappear as well, and are never performed. When a
735 reduction makes two parsers identical, causing them to merge, Bison
736 records both sets of semantic actions. Whenever the last two parsers
737 merge, reverting to the single-parser case, Bison resolves all the
738 outstanding actions either by precedences given to the grammar rules
739 involved, or by performing both actions, and then calling a designated
740 user-defined function on the resulting values to produce an arbitrary
741 merged result.
742
743 @menu
744 * Simple GLR Parsers:: Using @acronym{GLR} parsers on unambiguous grammars.
745 * Merging GLR Parses:: Using @acronym{GLR} parsers to resolve ambiguities.
746 * GLR Semantic Actions:: Deferred semantic actions have special concerns.
747 * Compiler Requirements:: @acronym{GLR} parsers require a modern C compiler.
748 @end menu
749
750 @node Simple GLR Parsers
751 @subsection Using @acronym{GLR} on Unambiguous Grammars
752 @cindex @acronym{GLR} parsing, unambiguous grammars
753 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing, unambiguous grammars
754 @findex %glr-parser
755 @findex %expect-rr
756 @cindex conflicts
757 @cindex reduce/reduce conflicts
758 @cindex shift/reduce conflicts
759
760 In the simplest cases, you can use the @acronym{GLR} algorithm
761 to parse grammars that are unambiguous, but fail to be @acronym{LALR}(1).
762 Such grammars typically require more than one symbol of lookahead,
763 or (in rare cases) fall into the category of grammars in which the
764 @acronym{LALR}(1) algorithm throws away too much information (they are in
765 @acronym{LR}(1), but not @acronym{LALR}(1), @ref{Mystery Conflicts}).
766
767 Consider a problem that
768 arises in the declaration of enumerated and subrange types in the
769 programming language Pascal. Here are some examples:
770
771 @example
772 type subrange = lo .. hi;
773 type enum = (a, b, c);
774 @end example
775
776 @noindent
777 The original language standard allows only numeric
778 literals and constant identifiers for the subrange bounds (@samp{lo}
779 and @samp{hi}), but Extended Pascal (@acronym{ISO}/@acronym{IEC}
780 10206) and many other
781 Pascal implementations allow arbitrary expressions there. This gives
782 rise to the following situation, containing a superfluous pair of
783 parentheses:
784
785 @example
786 type subrange = (a) .. b;
787 @end example
788
789 @noindent
790 Compare this to the following declaration of an enumerated
791 type with only one value:
792
793 @example
794 type enum = (a);
795 @end example
796
797 @noindent
798 (These declarations are contrived, but they are syntactically
799 valid, and more-complicated cases can come up in practical programs.)
800
801 These two declarations look identical until the @samp{..} token.
802 With normal @acronym{LALR}(1) one-token lookahead it is not
803 possible to decide between the two forms when the identifier
804 @samp{a} is parsed. It is, however, desirable
805 for a parser to decide this, since in the latter case
806 @samp{a} must become a new identifier to represent the enumeration
807 value, while in the former case @samp{a} must be evaluated with its
808 current meaning, which may be a constant or even a function call.
809
810 You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
811 to be resolved later, but this typically requires substantial
812 contortions in both semantic actions and large parts of the
813 grammar, where the parentheses are nested in the recursive rules for
814 expressions.
815
816 You might think of using the lexer to distinguish between the two
817 forms by returning different tokens for currently defined and
818 undefined identifiers. But if these declarations occur in a local
819 scope, and @samp{a} is defined in an outer scope, then both forms
820 are possible---either locally redefining @samp{a}, or using the
821 value of @samp{a} from the outer scope. So this approach cannot
822 work.
823
824 A simple solution to this problem is to declare the parser to
825 use the @acronym{GLR} algorithm.
826 When the @acronym{GLR} parser reaches the critical state, it
827 merely splits into two branches and pursues both syntax rules
828 simultaneously. Sooner or later, one of them runs into a parsing
829 error. If there is a @samp{..} token before the next
830 @samp{;}, the rule for enumerated types fails since it cannot
831 accept @samp{..} anywhere; otherwise, the subrange type rule
832 fails since it requires a @samp{..} token. So one of the branches
833 fails silently, and the other one continues normally, performing
834 all the intermediate actions that were postponed during the split.
835
836 If the input is syntactically incorrect, both branches fail and the parser
837 reports a syntax error as usual.
838
839 The effect of all this is that the parser seems to ``guess'' the
840 correct branch to take, or in other words, it seems to use more
841 lookahead than the underlying @acronym{LALR}(1) algorithm actually allows
842 for. In this example, @acronym{LALR}(2) would suffice, but also some cases
843 that are not @acronym{LALR}(@math{k}) for any @math{k} can be handled this way.
844
845 In general, a @acronym{GLR} parser can take quadratic or cubic worst-case time,
846 and the current Bison parser even takes exponential time and space
847 for some grammars. In practice, this rarely happens, and for many
848 grammars it is possible to prove that it cannot happen.
849 The present example contains only one conflict between two
850 rules, and the type-declaration context containing the conflict
851 cannot be nested. So the number of
852 branches that can exist at any time is limited by the constant 2,
853 and the parsing time is still linear.
854
855 Here is a Bison grammar corresponding to the example above. It
856 parses a vastly simplified form of Pascal type declarations.
857
858 @example
859 %token TYPE DOTDOT ID
860
861 @group
862 %left '+' '-'
863 %left '*' '/'
864 @end group
865
866 %%
867
868 @group
869 type_decl : TYPE ID '=' type ';'
870 ;
871 @end group
872
873 @group
874 type : '(' id_list ')'
875 | expr DOTDOT expr
876 ;
877 @end group
878
879 @group
880 id_list : ID
881 | id_list ',' ID
882 ;
883 @end group
884
885 @group
886 expr : '(' expr ')'
887 | expr '+' expr
888 | expr '-' expr
889 | expr '*' expr
890 | expr '/' expr
891 | ID
892 ;
893 @end group
894 @end example
895
896 When used as a normal @acronym{LALR}(1) grammar, Bison correctly complains
897 about one reduce/reduce conflict. In the conflicting situation the
898 parser chooses one of the alternatives, arbitrarily the one
899 declared first. Therefore the following correct input is not
900 recognized:
901
902 @example
903 type t = (a) .. b;
904 @end example
905
906 The parser can be turned into a @acronym{GLR} parser, while also telling Bison
907 to be silent about the one known reduce/reduce conflict, by
908 adding these two declarations to the Bison input file (before the first
909 @samp{%%}):
910
911 @example
912 %glr-parser
913 %expect-rr 1
914 @end example
915
916 @noindent
917 No change in the grammar itself is required. Now the
918 parser recognizes all valid declarations, according to the
919 limited syntax above, transparently. In fact, the user does not even
920 notice when the parser splits.
921
922 So here we have a case where we can use the benefits of @acronym{GLR},
923 almost without disadvantages. Even in simple cases like this, however,
924 there are at least two potential problems to beware. First, always
925 analyze the conflicts reported by Bison to make sure that @acronym{GLR}
926 splitting is only done where it is intended. A @acronym{GLR} parser
927 splitting inadvertently may cause problems less obvious than an
928 @acronym{LALR} parser statically choosing the wrong alternative in a
929 conflict. Second, consider interactions with the lexer (@pxref{Semantic
930 Tokens}) with great care. Since a split parser consumes tokens without
931 performing any actions during the split, the lexer cannot obtain
932 information via parser actions. Some cases of lexer interactions can be
933 eliminated by using @acronym{GLR} to shift the complications from the
934 lexer to the parser. You must check the remaining cases for
935 correctness.
936
937 In our example, it would be safe for the lexer to return tokens based on
938 their current meanings in some symbol table, because no new symbols are
939 defined in the middle of a type declaration. Though it is possible for
940 a parser to define the enumeration constants as they are parsed, before
941 the type declaration is completed, it actually makes no difference since
942 they cannot be used within the same enumerated type declaration.
943
944 @node Merging GLR Parses
945 @subsection Using @acronym{GLR} to Resolve Ambiguities
946 @cindex @acronym{GLR} parsing, ambiguous grammars
947 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing, ambiguous grammars
948 @findex %dprec
949 @findex %merge
950 @cindex conflicts
951 @cindex reduce/reduce conflicts
952
953 Let's consider an example, vastly simplified from a C++ grammar.
954
955 @example
956 %@{
957 #include <stdio.h>
958 #define YYSTYPE char const *
959 int yylex (void);
960 void yyerror (char const *);
961 %@}
962
963 %token TYPENAME ID
964
965 %right '='
966 %left '+'
967
968 %glr-parser
969
970 %%
971
972 prog :
973 | prog stmt @{ printf ("\n"); @}
974 ;
975
976 stmt : expr ';' %dprec 1
977 | decl %dprec 2
978 ;
979
980 expr : ID @{ printf ("%s ", $$); @}
981 | TYPENAME '(' expr ')'
982 @{ printf ("%s <cast> ", $1); @}
983 | expr '+' expr @{ printf ("+ "); @}
984 | expr '=' expr @{ printf ("= "); @}
985 ;
986
987 decl : TYPENAME declarator ';'
988 @{ printf ("%s <declare> ", $1); @}
989 | TYPENAME declarator '=' expr ';'
990 @{ printf ("%s <init-declare> ", $1); @}
991 ;
992
993 declarator : ID @{ printf ("\"%s\" ", $1); @}
994 | '(' declarator ')'
995 ;
996 @end example
997
998 @noindent
999 This models a problematic part of the C++ grammar---the ambiguity between
1000 certain declarations and statements. For example,
1001
1002 @example
1003 T (x) = y+z;
1004 @end example
1005
1006 @noindent
1007 parses as either an @code{expr} or a @code{stmt}
1008 (assuming that @samp{T} is recognized as a @code{TYPENAME} and
1009 @samp{x} as an @code{ID}).
1010 Bison detects this as a reduce/reduce conflict between the rules
1011 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
1012 time it encounters @code{x} in the example above. Since this is a
1013 @acronym{GLR} parser, it therefore splits the problem into two parses, one for
1014 each choice of resolving the reduce/reduce conflict.
1015 Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1016 however, neither of these parses ``dies,'' because the grammar as it stands is
1017 ambiguous. One of the parsers eventually reduces @code{stmt : expr ';'} and
1018 the other reduces @code{stmt : decl}, after which both parsers are in an
1019 identical state: they've seen @samp{prog stmt} and have the same unprocessed
1020 input remaining. We say that these parses have @dfn{merged.}
1021
1022 At this point, the @acronym{GLR} parser requires a specification in the
1023 grammar of how to choose between the competing parses.
1024 In the example above, the two @code{%dprec}
1025 declarations specify that Bison is to give precedence
1026 to the parse that interprets the example as a
1027 @code{decl}, which implies that @code{x} is a declarator.
1028 The parser therefore prints
1029
1030 @example
1031 "x" y z + T <init-declare>
1032 @end example
1033
1034 The @code{%dprec} declarations only come into play when more than one
1035 parse survives. Consider a different input string for this parser:
1036
1037 @example
1038 T (x) + y;
1039 @end example
1040
1041 @noindent
1042 This is another example of using @acronym{GLR} to parse an unambiguous
1043 construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
1044 Here, there is no ambiguity (this cannot be parsed as a declaration).
1045 However, at the time the Bison parser encounters @code{x}, it does not
1046 have enough information to resolve the reduce/reduce conflict (again,
1047 between @code{x} as an @code{expr} or a @code{declarator}). In this
1048 case, no precedence declaration is used. Again, the parser splits
1049 into two, one assuming that @code{x} is an @code{expr}, and the other
1050 assuming @code{x} is a @code{declarator}. The second of these parsers
1051 then vanishes when it sees @code{+}, and the parser prints
1052
1053 @example
1054 x T <cast> y +
1055 @end example
1056
1057 Suppose that instead of resolving the ambiguity, you wanted to see all
1058 the possibilities. For this purpose, you must merge the semantic
1059 actions of the two possible parsers, rather than choosing one over the
1060 other. To do so, you could change the declaration of @code{stmt} as
1061 follows:
1062
1063 @example
1064 stmt : expr ';' %merge <stmtMerge>
1065 | decl %merge <stmtMerge>
1066 ;
1067 @end example
1068
1069 @noindent
1070 and define the @code{stmtMerge} function as:
1071
1072 @example
1073 static YYSTYPE
1074 stmtMerge (YYSTYPE x0, YYSTYPE x1)
1075 @{
1076 printf ("<OR> ");
1077 return "";
1078 @}
1079 @end example
1080
1081 @noindent
1082 with an accompanying forward declaration
1083 in the C declarations at the beginning of the file:
1084
1085 @example
1086 %@{
1087 #define YYSTYPE char const *
1088 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
1089 %@}
1090 @end example
1091
1092 @noindent
1093 With these declarations, the resulting parser parses the first example
1094 as both an @code{expr} and a @code{decl}, and prints
1095
1096 @example
1097 "x" y z + T <init-declare> x T <cast> y z + = <OR>
1098 @end example
1099
1100 Bison requires that all of the
1101 productions that participate in any particular merge have identical
1102 @samp{%merge} clauses. Otherwise, the ambiguity would be unresolvable,
1103 and the parser will report an error during any parse that results in
1104 the offending merge.
1105
1106 @node GLR Semantic Actions
1107 @subsection GLR Semantic Actions
1108
1109 @cindex deferred semantic actions
1110 By definition, a deferred semantic action is not performed at the same time as
1111 the associated reduction.
1112 This raises caveats for several Bison features you might use in a semantic
1113 action in a @acronym{GLR} parser.
1114
1115 @vindex yychar
1116 @cindex @acronym{GLR} parsers and @code{yychar}
1117 @vindex yylval
1118 @cindex @acronym{GLR} parsers and @code{yylval}
1119 @vindex yylloc
1120 @cindex @acronym{GLR} parsers and @code{yylloc}
1121 In any semantic action, you can examine @code{yychar} to determine the type of
1122 the lookahead token present at the time of the associated reduction.
1123 After checking that @code{yychar} is not set to @code{YYEMPTY} or @code{YYEOF},
1124 you can then examine @code{yylval} and @code{yylloc} to determine the
1125 lookahead token's semantic value and location, if any.
1126 In a nondeferred semantic action, you can also modify any of these variables to
1127 influence syntax analysis.
1128 @xref{Lookahead, ,Lookahead Tokens}.
1129
1130 @findex yyclearin
1131 @cindex @acronym{GLR} parsers and @code{yyclearin}
1132 In a deferred semantic action, it's too late to influence syntax analysis.
1133 In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1134 shallow copies of the values they had at the time of the associated reduction.
1135 For this reason alone, modifying them is dangerous.
1136 Moreover, the result of modifying them is undefined and subject to change with
1137 future versions of Bison.
1138 For example, if a semantic action might be deferred, you should never write it
1139 to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1140 memory referenced by @code{yylval}.
1141
1142 @findex YYERROR
1143 @cindex @acronym{GLR} parsers and @code{YYERROR}
1144 Another Bison feature requiring special consideration is @code{YYERROR}
1145 (@pxref{Action Features}), which you can invoke in a semantic action to
1146 initiate error recovery.
1147 During deterministic @acronym{GLR} operation, the effect of @code{YYERROR} is
1148 the same as its effect in an @acronym{LALR}(1) parser.
1149 In a deferred semantic action, its effect is undefined.
1150 @c The effect is probably a syntax error at the split point.
1151
1152 Also, see @ref{Location Default Action, ,Default Action for Locations}, which
1153 describes a special usage of @code{YYLLOC_DEFAULT} in @acronym{GLR} parsers.
1154
1155 @node Compiler Requirements
1156 @subsection Considerations when Compiling @acronym{GLR} Parsers
1157 @cindex @code{inline}
1158 @cindex @acronym{GLR} parsers and @code{inline}
1159
1160 The @acronym{GLR} parsers require a compiler for @acronym{ISO} C89 or
1161 later. In addition, they use the @code{inline} keyword, which is not
1162 C89, but is C99 and is a common extension in pre-C99 compilers. It is
1163 up to the user of these parsers to handle
1164 portability issues. For instance, if using Autoconf and the Autoconf
1165 macro @code{AC_C_INLINE}, a mere
1166
1167 @example
1168 %@{
1169 #include <config.h>
1170 %@}
1171 @end example
1172
1173 @noindent
1174 will suffice. Otherwise, we suggest
1175
1176 @example
1177 %@{
1178 #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
1179 #define inline
1180 #endif
1181 %@}
1182 @end example
1183
1184 @node Locations Overview
1185 @section Locations
1186 @cindex location
1187 @cindex textual location
1188 @cindex location, textual
1189
1190 Many applications, like interpreters or compilers, have to produce verbose
1191 and useful error messages. To achieve this, one must be able to keep track of
1192 the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
1193 Bison provides a mechanism for handling these locations.
1194
1195 Each token has a semantic value. In a similar fashion, each token has an
1196 associated location, but the type of locations is the same for all tokens and
1197 groupings. Moreover, the output parser is equipped with a default data
1198 structure for storing locations (@pxref{Locations}, for more details).
1199
1200 Like semantic values, locations can be reached in actions using a dedicated
1201 set of constructs. In the example above, the location of the whole grouping
1202 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1203 @code{@@3}.
1204
1205 When a rule is matched, a default action is used to compute the semantic value
1206 of its left hand side (@pxref{Actions}). In the same way, another default
1207 action is used for locations. However, the action for locations is general
1208 enough for most cases, meaning there is usually no need to describe for each
1209 rule how @code{@@$} should be formed. When building a new location for a given
1210 grouping, the default behavior of the output parser is to take the beginning
1211 of the first symbol, and the end of the last symbol.
1212
1213 @node Bison Parser
1214 @section Bison Output: the Parser File
1215 @cindex Bison parser
1216 @cindex Bison utility
1217 @cindex lexical analyzer, purpose
1218 @cindex parser
1219
1220 When you run Bison, you give it a Bison grammar file as input. The output
1221 is a C source file that parses the language described by the grammar.
1222 This file is called a @dfn{Bison parser}. Keep in mind that the Bison
1223 utility and the Bison parser are two distinct programs: the Bison utility
1224 is a program whose output is the Bison parser that becomes part of your
1225 program.
1226
1227 The job of the Bison parser is to group tokens into groupings according to
1228 the grammar rules---for example, to build identifiers and operators into
1229 expressions. As it does this, it runs the actions for the grammar rules it
1230 uses.
1231
1232 The tokens come from a function called the @dfn{lexical analyzer} that
1233 you must supply in some fashion (such as by writing it in C). The Bison
1234 parser calls the lexical analyzer each time it wants a new token. It
1235 doesn't know what is ``inside'' the tokens (though their semantic values
1236 may reflect this). Typically the lexical analyzer makes the tokens by
1237 parsing characters of text, but Bison does not depend on this.
1238 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
1239
1240 The Bison parser file is C code which defines a function named
1241 @code{yyparse} which implements that grammar. This function does not make
1242 a complete C program: you must supply some additional functions. One is
1243 the lexical analyzer. Another is an error-reporting function which the
1244 parser calls to report an error. In addition, a complete C program must
1245 start with a function called @code{main}; you have to provide this, and
1246 arrange for it to call @code{yyparse} or the parser will never run.
1247 @xref{Interface, ,Parser C-Language Interface}.
1248
1249 Aside from the token type names and the symbols in the actions you
1250 write, all symbols defined in the Bison parser file itself
1251 begin with @samp{yy} or @samp{YY}. This includes interface functions
1252 such as the lexical analyzer function @code{yylex}, the error reporting
1253 function @code{yyerror} and the parser function @code{yyparse} itself.
1254 This also includes numerous identifiers used for internal purposes.
1255 Therefore, you should avoid using C identifiers starting with @samp{yy}
1256 or @samp{YY} in the Bison grammar file except for the ones defined in
1257 this manual. Also, you should avoid using the C identifiers
1258 @samp{malloc} and @samp{free} for anything other than their usual
1259 meanings.
1260
1261 In some cases the Bison parser file includes system headers, and in
1262 those cases your code should respect the identifiers reserved by those
1263 headers. On some non-@acronym{GNU} hosts, @code{<alloca.h>}, @code{<malloc.h>},
1264 @code{<stddef.h>}, and @code{<stdlib.h>} are included as needed to
1265 declare memory allocators and related types. @code{<libintl.h>} is
1266 included if message translation is in use
1267 (@pxref{Internationalization}). Other system headers may
1268 be included if you define @code{YYDEBUG} to a nonzero value
1269 (@pxref{Tracing, ,Tracing Your Parser}).
1270
1271 @node Stages
1272 @section Stages in Using Bison
1273 @cindex stages in using Bison
1274 @cindex using Bison
1275
1276 The actual language-design process using Bison, from grammar specification
1277 to a working compiler or interpreter, has these parts:
1278
1279 @enumerate
1280 @item
1281 Formally specify the grammar in a form recognized by Bison
1282 (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
1283 in the language, describe the action that is to be taken when an
1284 instance of that rule is recognized. The action is described by a
1285 sequence of C statements.
1286
1287 @item
1288 Write a lexical analyzer to process input and pass tokens to the parser.
1289 The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
1290 Lexical Analyzer Function @code{yylex}}). It could also be produced
1291 using Lex, but the use of Lex is not discussed in this manual.
1292
1293 @item
1294 Write a controlling function that calls the Bison-produced parser.
1295
1296 @item
1297 Write error-reporting routines.
1298 @end enumerate
1299
1300 To turn this source code as written into a runnable program, you
1301 must follow these steps:
1302
1303 @enumerate
1304 @item
1305 Run Bison on the grammar to produce the parser.
1306
1307 @item
1308 Compile the code output by Bison, as well as any other source files.
1309
1310 @item
1311 Link the object files to produce the finished product.
1312 @end enumerate
1313
1314 @node Grammar Layout
1315 @section The Overall Layout of a Bison Grammar
1316 @cindex grammar file
1317 @cindex file format
1318 @cindex format of grammar file
1319 @cindex layout of Bison grammar
1320
1321 The input file for the Bison utility is a @dfn{Bison grammar file}. The
1322 general form of a Bison grammar file is as follows:
1323
1324 @example
1325 %@{
1326 @var{Prologue}
1327 %@}
1328
1329 @var{Bison declarations}
1330
1331 %%
1332 @var{Grammar rules}
1333 %%
1334 @var{Epilogue}
1335 @end example
1336
1337 @noindent
1338 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1339 in every Bison grammar file to separate the sections.
1340
1341 The prologue may define types and variables used in the actions. You can
1342 also use preprocessor commands to define macros used there, and use
1343 @code{#include} to include header files that do any of these things.
1344 You need to declare the lexical analyzer @code{yylex} and the error
1345 printer @code{yyerror} here, along with any other global identifiers
1346 used by the actions in the grammar rules.
1347
1348 The Bison declarations declare the names of the terminal and nonterminal
1349 symbols, and may also describe operator precedence and the data types of
1350 semantic values of various symbols.
1351
1352 The grammar rules define how to construct each nonterminal symbol from its
1353 parts.
1354
1355 The epilogue can contain any code you want to use. Often the
1356 definitions of functions declared in the prologue go here. In a
1357 simple program, all the rest of the program can go here.
1358
1359 @node Examples
1360 @chapter Examples
1361 @cindex simple examples
1362 @cindex examples, simple
1363
1364 Now we show and explain three sample programs written using Bison: a
1365 reverse polish notation calculator, an algebraic (infix) notation
1366 calculator, and a multi-function calculator. All three have been tested
1367 under BSD Unix 4.3; each produces a usable, though limited, interactive
1368 desk-top calculator.
1369
1370 These examples are simple, but Bison grammars for real programming
1371 languages are written the same way. You can copy these examples into a
1372 source file to try them.
1373
1374 @menu
1375 * RPN Calc:: Reverse polish notation calculator;
1376 a first example with no operator precedence.
1377 * Infix Calc:: Infix (algebraic) notation calculator.
1378 Operator precedence is introduced.
1379 * Simple Error Recovery:: Continuing after syntax errors.
1380 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1381 * Multi-function Calc:: Calculator with memory and trig functions.
1382 It uses multiple data-types for semantic values.
1383 * Exercises:: Ideas for improving the multi-function calculator.
1384 @end menu
1385
1386 @node RPN Calc
1387 @section Reverse Polish Notation Calculator
1388 @cindex reverse polish notation
1389 @cindex polish notation calculator
1390 @cindex @code{rpcalc}
1391 @cindex calculator, simple
1392
1393 The first example is that of a simple double-precision @dfn{reverse polish
1394 notation} calculator (a calculator using postfix operators). This example
1395 provides a good starting point, since operator precedence is not an issue.
1396 The second example will illustrate how operator precedence is handled.
1397
1398 The source code for this calculator is named @file{rpcalc.y}. The
1399 @samp{.y} extension is a convention used for Bison input files.
1400
1401 @menu
1402 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
1403 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1404 * Lexer: Rpcalc Lexer. The lexical analyzer.
1405 * Main: Rpcalc Main. The controlling function.
1406 * Error: Rpcalc Error. The error reporting function.
1407 * Gen: Rpcalc Gen. Running Bison on the grammar file.
1408 * Comp: Rpcalc Compile. Run the C compiler on the output code.
1409 @end menu
1410
1411 @node Rpcalc Decls
1412 @subsection Declarations for @code{rpcalc}
1413
1414 Here are the C and Bison declarations for the reverse polish notation
1415 calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1416
1417 @example
1418 /* Reverse polish notation calculator. */
1419
1420 %@{
1421 #define YYSTYPE double
1422 #include <math.h>
1423 int yylex (void);
1424 void yyerror (char const *);
1425 %@}
1426
1427 %token NUM
1428
1429 %% /* Grammar rules and actions follow. */
1430 @end example
1431
1432 The declarations section (@pxref{Prologue, , The prologue}) contains two
1433 preprocessor directives and two forward declarations.
1434
1435 The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1436 specifying the C data type for semantic values of both tokens and
1437 groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1438 Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1439 don't define it, @code{int} is the default. Because we specify
1440 @code{double}, each token and each expression has an associated value,
1441 which is a floating point number.
1442
1443 The @code{#include} directive is used to declare the exponentiation
1444 function @code{pow}.
1445
1446 The forward declarations for @code{yylex} and @code{yyerror} are
1447 needed because the C language requires that functions be declared
1448 before they are used. These functions will be defined in the
1449 epilogue, but the parser calls them so they must be declared in the
1450 prologue.
1451
1452 The second section, Bison declarations, provides information to Bison
1453 about the token types (@pxref{Bison Declarations, ,The Bison
1454 Declarations Section}). Each terminal symbol that is not a
1455 single-character literal must be declared here. (Single-character
1456 literals normally don't need to be declared.) In this example, all the
1457 arithmetic operators are designated by single-character literals, so the
1458 only terminal symbol that needs to be declared is @code{NUM}, the token
1459 type for numeric constants.
1460
1461 @node Rpcalc Rules
1462 @subsection Grammar Rules for @code{rpcalc}
1463
1464 Here are the grammar rules for the reverse polish notation calculator.
1465
1466 @example
1467 input: /* empty */
1468 | input line
1469 ;
1470
1471 line: '\n'
1472 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1473 ;
1474
1475 exp: NUM @{ $$ = $1; @}
1476 | exp exp '+' @{ $$ = $1 + $2; @}
1477 | exp exp '-' @{ $$ = $1 - $2; @}
1478 | exp exp '*' @{ $$ = $1 * $2; @}
1479 | exp exp '/' @{ $$ = $1 / $2; @}
1480 /* Exponentiation */
1481 | exp exp '^' @{ $$ = pow ($1, $2); @}
1482 /* Unary minus */
1483 | exp 'n' @{ $$ = -$1; @}
1484 ;
1485 %%
1486 @end example
1487
1488 The groupings of the rpcalc ``language'' defined here are the expression
1489 (given the name @code{exp}), the line of input (@code{line}), and the
1490 complete input transcript (@code{input}). Each of these nonterminal
1491 symbols has several alternate rules, joined by the vertical bar @samp{|}
1492 which is read as ``or''. The following sections explain what these rules
1493 mean.
1494
1495 The semantics of the language is determined by the actions taken when a
1496 grouping is recognized. The actions are the C code that appears inside
1497 braces. @xref{Actions}.
1498
1499 You must specify these actions in C, but Bison provides the means for
1500 passing semantic values between the rules. In each action, the
1501 pseudo-variable @code{$$} stands for the semantic value for the grouping
1502 that the rule is going to construct. Assigning a value to @code{$$} is the
1503 main job of most actions. The semantic values of the components of the
1504 rule are referred to as @code{$1}, @code{$2}, and so on.
1505
1506 @menu
1507 * Rpcalc Input::
1508 * Rpcalc Line::
1509 * Rpcalc Expr::
1510 @end menu
1511
1512 @node Rpcalc Input
1513 @subsubsection Explanation of @code{input}
1514
1515 Consider the definition of @code{input}:
1516
1517 @example
1518 input: /* empty */
1519 | input line
1520 ;
1521 @end example
1522
1523 This definition reads as follows: ``A complete input is either an empty
1524 string, or a complete input followed by an input line''. Notice that
1525 ``complete input'' is defined in terms of itself. This definition is said
1526 to be @dfn{left recursive} since @code{input} appears always as the
1527 leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1528
1529 The first alternative is empty because there are no symbols between the
1530 colon and the first @samp{|}; this means that @code{input} can match an
1531 empty string of input (no tokens). We write the rules this way because it
1532 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1533 It's conventional to put an empty alternative first and write the comment
1534 @samp{/* empty */} in it.
1535
1536 The second alternate rule (@code{input line}) handles all nontrivial input.
1537 It means, ``After reading any number of lines, read one more line if
1538 possible.'' The left recursion makes this rule into a loop. Since the
1539 first alternative matches empty input, the loop can be executed zero or
1540 more times.
1541
1542 The parser function @code{yyparse} continues to process input until a
1543 grammatical error is seen or the lexical analyzer says there are no more
1544 input tokens; we will arrange for the latter to happen at end-of-input.
1545
1546 @node Rpcalc Line
1547 @subsubsection Explanation of @code{line}
1548
1549 Now consider the definition of @code{line}:
1550
1551 @example
1552 line: '\n'
1553 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1554 ;
1555 @end example
1556
1557 The first alternative is a token which is a newline character; this means
1558 that rpcalc accepts a blank line (and ignores it, since there is no
1559 action). The second alternative is an expression followed by a newline.
1560 This is the alternative that makes rpcalc useful. The semantic value of
1561 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1562 question is the first symbol in the alternative. The action prints this
1563 value, which is the result of the computation the user asked for.
1564
1565 This action is unusual because it does not assign a value to @code{$$}. As
1566 a consequence, the semantic value associated with the @code{line} is
1567 uninitialized (its value will be unpredictable). This would be a bug if
1568 that value were ever used, but we don't use it: once rpcalc has printed the
1569 value of the user's input line, that value is no longer needed.
1570
1571 @node Rpcalc Expr
1572 @subsubsection Explanation of @code{expr}
1573
1574 The @code{exp} grouping has several rules, one for each kind of expression.
1575 The first rule handles the simplest expressions: those that are just numbers.
1576 The second handles an addition-expression, which looks like two expressions
1577 followed by a plus-sign. The third handles subtraction, and so on.
1578
1579 @example
1580 exp: NUM
1581 | exp exp '+' @{ $$ = $1 + $2; @}
1582 | exp exp '-' @{ $$ = $1 - $2; @}
1583 @dots{}
1584 ;
1585 @end example
1586
1587 We have used @samp{|} to join all the rules for @code{exp}, but we could
1588 equally well have written them separately:
1589
1590 @example
1591 exp: NUM ;
1592 exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1593 exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1594 @dots{}
1595 @end example
1596
1597 Most of the rules have actions that compute the value of the expression in
1598 terms of the value of its parts. For example, in the rule for addition,
1599 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1600 the second one. The third component, @code{'+'}, has no meaningful
1601 associated semantic value, but if it had one you could refer to it as
1602 @code{$3}. When @code{yyparse} recognizes a sum expression using this
1603 rule, the sum of the two subexpressions' values is produced as the value of
1604 the entire expression. @xref{Actions}.
1605
1606 You don't have to give an action for every rule. When a rule has no
1607 action, Bison by default copies the value of @code{$1} into @code{$$}.
1608 This is what happens in the first rule (the one that uses @code{NUM}).
1609
1610 The formatting shown here is the recommended convention, but Bison does
1611 not require it. You can add or change white space as much as you wish.
1612 For example, this:
1613
1614 @example
1615 exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
1616 @end example
1617
1618 @noindent
1619 means the same thing as this:
1620
1621 @example
1622 exp: NUM
1623 | exp exp '+' @{ $$ = $1 + $2; @}
1624 | @dots{}
1625 ;
1626 @end example
1627
1628 @noindent
1629 The latter, however, is much more readable.
1630
1631 @node Rpcalc Lexer
1632 @subsection The @code{rpcalc} Lexical Analyzer
1633 @cindex writing a lexical analyzer
1634 @cindex lexical analyzer, writing
1635
1636 The lexical analyzer's job is low-level parsing: converting characters
1637 or sequences of characters into tokens. The Bison parser gets its
1638 tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1639 Analyzer Function @code{yylex}}.
1640
1641 Only a simple lexical analyzer is needed for the @acronym{RPN}
1642 calculator. This
1643 lexical analyzer skips blanks and tabs, then reads in numbers as
1644 @code{double} and returns them as @code{NUM} tokens. Any other character
1645 that isn't part of a number is a separate token. Note that the token-code
1646 for such a single-character token is the character itself.
1647
1648 The return value of the lexical analyzer function is a numeric code which
1649 represents a token type. The same text used in Bison rules to stand for
1650 this token type is also a C expression for the numeric code for the type.
1651 This works in two ways. If the token type is a character literal, then its
1652 numeric code is that of the character; you can use the same
1653 character literal in the lexical analyzer to express the number. If the
1654 token type is an identifier, that identifier is defined by Bison as a C
1655 macro whose definition is the appropriate number. In this example,
1656 therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1657
1658 The semantic value of the token (if it has one) is stored into the
1659 global variable @code{yylval}, which is where the Bison parser will look
1660 for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1661 defined at the beginning of the grammar; @pxref{Rpcalc Decls,
1662 ,Declarations for @code{rpcalc}}.)
1663
1664 A token type code of zero is returned if the end-of-input is encountered.
1665 (Bison recognizes any nonpositive value as indicating end-of-input.)
1666
1667 Here is the code for the lexical analyzer:
1668
1669 @example
1670 @group
1671 /* The lexical analyzer returns a double floating point
1672 number on the stack and the token NUM, or the numeric code
1673 of the character read if not a number. It skips all blanks
1674 and tabs, and returns 0 for end-of-input. */
1675
1676 #include <ctype.h>
1677 @end group
1678
1679 @group
1680 int
1681 yylex (void)
1682 @{
1683 int c;
1684
1685 /* Skip white space. */
1686 while ((c = getchar ()) == ' ' || c == '\t')
1687 ;
1688 @end group
1689 @group
1690 /* Process numbers. */
1691 if (c == '.' || isdigit (c))
1692 @{
1693 ungetc (c, stdin);
1694 scanf ("%lf", &yylval);
1695 return NUM;
1696 @}
1697 @end group
1698 @group
1699 /* Return end-of-input. */
1700 if (c == EOF)
1701 return 0;
1702 /* Return a single char. */
1703 return c;
1704 @}
1705 @end group
1706 @end example
1707
1708 @node Rpcalc Main
1709 @subsection The Controlling Function
1710 @cindex controlling function
1711 @cindex main function in simple example
1712
1713 In keeping with the spirit of this example, the controlling function is
1714 kept to the bare minimum. The only requirement is that it call
1715 @code{yyparse} to start the process of parsing.
1716
1717 @example
1718 @group
1719 int
1720 main (void)
1721 @{
1722 return yyparse ();
1723 @}
1724 @end group
1725 @end example
1726
1727 @node Rpcalc Error
1728 @subsection The Error Reporting Routine
1729 @cindex error reporting routine
1730
1731 When @code{yyparse} detects a syntax error, it calls the error reporting
1732 function @code{yyerror} to print an error message (usually but not
1733 always @code{"syntax error"}). It is up to the programmer to supply
1734 @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1735 here is the definition we will use:
1736
1737 @example
1738 @group
1739 #include <stdio.h>
1740
1741 /* Called by yyparse on error. */
1742 void
1743 yyerror (char const *s)
1744 @{
1745 fprintf (stderr, "%s\n", s);
1746 @}
1747 @end group
1748 @end example
1749
1750 After @code{yyerror} returns, the Bison parser may recover from the error
1751 and continue parsing if the grammar contains a suitable error rule
1752 (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1753 have not written any error rules in this example, so any invalid input will
1754 cause the calculator program to exit. This is not clean behavior for a
1755 real calculator, but it is adequate for the first example.
1756
1757 @node Rpcalc Gen
1758 @subsection Running Bison to Make the Parser
1759 @cindex running Bison (introduction)
1760
1761 Before running Bison to produce a parser, we need to decide how to
1762 arrange all the source code in one or more source files. For such a
1763 simple example, the easiest thing is to put everything in one file. The
1764 definitions of @code{yylex}, @code{yyerror} and @code{main} go at the
1765 end, in the epilogue of the file
1766 (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1767
1768 For a large project, you would probably have several source files, and use
1769 @code{make} to arrange to recompile them.
1770
1771 With all the source in a single file, you use the following command to
1772 convert it into a parser file:
1773
1774 @example
1775 bison @var{file}.y
1776 @end example
1777
1778 @noindent
1779 In this example the file was called @file{rpcalc.y} (for ``Reverse Polish
1780 @sc{calc}ulator''). Bison produces a file named @file{@var{file}.tab.c},
1781 removing the @samp{.y} from the original file name. The file output by
1782 Bison contains the source code for @code{yyparse}. The additional
1783 functions in the input file (@code{yylex}, @code{yyerror} and @code{main})
1784 are copied verbatim to the output.
1785
1786 @node Rpcalc Compile
1787 @subsection Compiling the Parser File
1788 @cindex compiling the parser
1789
1790 Here is how to compile and run the parser file:
1791
1792 @example
1793 @group
1794 # @r{List files in current directory.}
1795 $ @kbd{ls}
1796 rpcalc.tab.c rpcalc.y
1797 @end group
1798
1799 @group
1800 # @r{Compile the Bison parser.}
1801 # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1802 $ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
1803 @end group
1804
1805 @group
1806 # @r{List files again.}
1807 $ @kbd{ls}
1808 rpcalc rpcalc.tab.c rpcalc.y
1809 @end group
1810 @end example
1811
1812 The file @file{rpcalc} now contains the executable code. Here is an
1813 example session using @code{rpcalc}.
1814
1815 @example
1816 $ @kbd{rpcalc}
1817 @kbd{4 9 +}
1818 13
1819 @kbd{3 7 + 3 4 5 *+-}
1820 -13
1821 @kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
1822 13
1823 @kbd{5 6 / 4 n +}
1824 -3.166666667
1825 @kbd{3 4 ^} @r{Exponentiation}
1826 81
1827 @kbd{^D} @r{End-of-file indicator}
1828 $
1829 @end example
1830
1831 @node Infix Calc
1832 @section Infix Notation Calculator: @code{calc}
1833 @cindex infix notation calculator
1834 @cindex @code{calc}
1835 @cindex calculator, infix notation
1836
1837 We now modify rpcalc to handle infix operators instead of postfix. Infix
1838 notation involves the concept of operator precedence and the need for
1839 parentheses nested to arbitrary depth. Here is the Bison code for
1840 @file{calc.y}, an infix desk-top calculator.
1841
1842 @example
1843 /* Infix notation calculator. */
1844
1845 %@{
1846 #define YYSTYPE double
1847 #include <math.h>
1848 #include <stdio.h>
1849 int yylex (void);
1850 void yyerror (char const *);
1851 %@}
1852
1853 /* Bison declarations. */
1854 %token NUM
1855 %left '-' '+'
1856 %left '*' '/'
1857 %left NEG /* negation--unary minus */
1858 %right '^' /* exponentiation */
1859
1860 %% /* The grammar follows. */
1861 input: /* empty */
1862 | input line
1863 ;
1864
1865 line: '\n'
1866 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1867 ;
1868
1869 exp: NUM @{ $$ = $1; @}
1870 | exp '+' exp @{ $$ = $1 + $3; @}
1871 | exp '-' exp @{ $$ = $1 - $3; @}
1872 | exp '*' exp @{ $$ = $1 * $3; @}
1873 | exp '/' exp @{ $$ = $1 / $3; @}
1874 | '-' exp %prec NEG @{ $$ = -$2; @}
1875 | exp '^' exp @{ $$ = pow ($1, $3); @}
1876 | '(' exp ')' @{ $$ = $2; @}
1877 ;
1878 %%
1879 @end example
1880
1881 @noindent
1882 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1883 same as before.
1884
1885 There are two important new features shown in this code.
1886
1887 In the second section (Bison declarations), @code{%left} declares token
1888 types and says they are left-associative operators. The declarations
1889 @code{%left} and @code{%right} (right associativity) take the place of
1890 @code{%token} which is used to declare a token type name without
1891 associativity. (These tokens are single-character literals, which
1892 ordinarily don't need to be declared. We declare them here to specify
1893 the associativity.)
1894
1895 Operator precedence is determined by the line ordering of the
1896 declarations; the higher the line number of the declaration (lower on
1897 the page or screen), the higher the precedence. Hence, exponentiation
1898 has the highest precedence, unary minus (@code{NEG}) is next, followed
1899 by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator
1900 Precedence}.
1901
1902 The other important new feature is the @code{%prec} in the grammar
1903 section for the unary minus operator. The @code{%prec} simply instructs
1904 Bison that the rule @samp{| '-' exp} has the same precedence as
1905 @code{NEG}---in this case the next-to-highest. @xref{Contextual
1906 Precedence, ,Context-Dependent Precedence}.
1907
1908 Here is a sample run of @file{calc.y}:
1909
1910 @need 500
1911 @example
1912 $ @kbd{calc}
1913 @kbd{4 + 4.5 - (34/(8*3+-3))}
1914 6.880952381
1915 @kbd{-56 + 2}
1916 -54
1917 @kbd{3 ^ 2}
1918 9
1919 @end example
1920
1921 @node Simple Error Recovery
1922 @section Simple Error Recovery
1923 @cindex error recovery, simple
1924
1925 Up to this point, this manual has not addressed the issue of @dfn{error
1926 recovery}---how to continue parsing after the parser detects a syntax
1927 error. All we have handled is error reporting with @code{yyerror}.
1928 Recall that by default @code{yyparse} returns after calling
1929 @code{yyerror}. This means that an erroneous input line causes the
1930 calculator program to exit. Now we show how to rectify this deficiency.
1931
1932 The Bison language itself includes the reserved word @code{error}, which
1933 may be included in the grammar rules. In the example below it has
1934 been added to one of the alternatives for @code{line}:
1935
1936 @example
1937 @group
1938 line: '\n'
1939 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1940 | error '\n' @{ yyerrok; @}
1941 ;
1942 @end group
1943 @end example
1944
1945 This addition to the grammar allows for simple error recovery in the
1946 event of a syntax error. If an expression that cannot be evaluated is
1947 read, the error will be recognized by the third rule for @code{line},
1948 and parsing will continue. (The @code{yyerror} function is still called
1949 upon to print its message as well.) The action executes the statement
1950 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
1951 that error recovery is complete (@pxref{Error Recovery}). Note the
1952 difference between @code{yyerrok} and @code{yyerror}; neither one is a
1953 misprint.
1954
1955 This form of error recovery deals with syntax errors. There are other
1956 kinds of errors; for example, division by zero, which raises an exception
1957 signal that is normally fatal. A real calculator program must handle this
1958 signal and use @code{longjmp} to return to @code{main} and resume parsing
1959 input lines; it would also have to discard the rest of the current line of
1960 input. We won't discuss this issue further because it is not specific to
1961 Bison programs.
1962
1963 @node Location Tracking Calc
1964 @section Location Tracking Calculator: @code{ltcalc}
1965 @cindex location tracking calculator
1966 @cindex @code{ltcalc}
1967 @cindex calculator, location tracking
1968
1969 This example extends the infix notation calculator with location
1970 tracking. This feature will be used to improve the error messages. For
1971 the sake of clarity, this example is a simple integer calculator, since
1972 most of the work needed to use locations will be done in the lexical
1973 analyzer.
1974
1975 @menu
1976 * Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
1977 * Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
1978 * Lexer: Ltcalc Lexer. The lexical analyzer.
1979 @end menu
1980
1981 @node Ltcalc Decls
1982 @subsection Declarations for @code{ltcalc}
1983
1984 The C and Bison declarations for the location tracking calculator are
1985 the same as the declarations for the infix notation calculator.
1986
1987 @example
1988 /* Location tracking calculator. */
1989
1990 %@{
1991 #define YYSTYPE int
1992 #include <math.h>
1993 int yylex (void);
1994 void yyerror (char const *);
1995 %@}
1996
1997 /* Bison declarations. */
1998 %token NUM
1999
2000 %left '-' '+'
2001 %left '*' '/'
2002 %left NEG
2003 %right '^'
2004
2005 %% /* The grammar follows. */
2006 @end example
2007
2008 @noindent
2009 Note there are no declarations specific to locations. Defining a data
2010 type for storing locations is not needed: we will use the type provided
2011 by default (@pxref{Location Type, ,Data Types of Locations}), which is a
2012 four member structure with the following integer fields:
2013 @code{first_line}, @code{first_column}, @code{last_line} and
2014 @code{last_column}. By conventions, and in accordance with the GNU
2015 Coding Standards and common practice, the line and column count both
2016 start at 1.
2017
2018 @node Ltcalc Rules
2019 @subsection Grammar Rules for @code{ltcalc}
2020
2021 Whether handling locations or not has no effect on the syntax of your
2022 language. Therefore, grammar rules for this example will be very close
2023 to those of the previous example: we will only modify them to benefit
2024 from the new information.
2025
2026 Here, we will use locations to report divisions by zero, and locate the
2027 wrong expressions or subexpressions.
2028
2029 @example
2030 @group
2031 input : /* empty */
2032 | input line
2033 ;
2034 @end group
2035
2036 @group
2037 line : '\n'
2038 | exp '\n' @{ printf ("%d\n", $1); @}
2039 ;
2040 @end group
2041
2042 @group
2043 exp : NUM @{ $$ = $1; @}
2044 | exp '+' exp @{ $$ = $1 + $3; @}
2045 | exp '-' exp @{ $$ = $1 - $3; @}
2046 | exp '*' exp @{ $$ = $1 * $3; @}
2047 @end group
2048 @group
2049 | exp '/' exp
2050 @{
2051 if ($3)
2052 $$ = $1 / $3;
2053 else
2054 @{
2055 $$ = 1;
2056 fprintf (stderr, "%d.%d-%d.%d: division by zero",
2057 @@3.first_line, @@3.first_column,
2058 @@3.last_line, @@3.last_column);
2059 @}
2060 @}
2061 @end group
2062 @group
2063 | '-' exp %prec NEG @{ $$ = -$2; @}
2064 | exp '^' exp @{ $$ = pow ($1, $3); @}
2065 | '(' exp ')' @{ $$ = $2; @}
2066 @end group
2067 @end example
2068
2069 This code shows how to reach locations inside of semantic actions, by
2070 using the pseudo-variables @code{@@@var{n}} for rule components, and the
2071 pseudo-variable @code{@@$} for groupings.
2072
2073 We don't need to assign a value to @code{@@$}: the output parser does it
2074 automatically. By default, before executing the C code of each action,
2075 @code{@@$} is set to range from the beginning of @code{@@1} to the end
2076 of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
2077 can be redefined (@pxref{Location Default Action, , Default Action for
2078 Locations}), and for very specific rules, @code{@@$} can be computed by
2079 hand.
2080
2081 @node Ltcalc Lexer
2082 @subsection The @code{ltcalc} Lexical Analyzer.
2083
2084 Until now, we relied on Bison's defaults to enable location
2085 tracking. The next step is to rewrite the lexical analyzer, and make it
2086 able to feed the parser with the token locations, as it already does for
2087 semantic values.
2088
2089 To this end, we must take into account every single character of the
2090 input text, to avoid the computed locations of being fuzzy or wrong:
2091
2092 @example
2093 @group
2094 int
2095 yylex (void)
2096 @{
2097 int c;
2098 @end group
2099
2100 @group
2101 /* Skip white space. */
2102 while ((c = getchar ()) == ' ' || c == '\t')
2103 ++yylloc.last_column;
2104 @end group
2105
2106 @group
2107 /* Step. */
2108 yylloc.first_line = yylloc.last_line;
2109 yylloc.first_column = yylloc.last_column;
2110 @end group
2111
2112 @group
2113 /* Process numbers. */
2114 if (isdigit (c))
2115 @{
2116 yylval = c - '0';
2117 ++yylloc.last_column;
2118 while (isdigit (c = getchar ()))
2119 @{
2120 ++yylloc.last_column;
2121 yylval = yylval * 10 + c - '0';
2122 @}
2123 ungetc (c, stdin);
2124 return NUM;
2125 @}
2126 @end group
2127
2128 /* Return end-of-input. */
2129 if (c == EOF)
2130 return 0;
2131
2132 /* Return a single char, and update location. */
2133 if (c == '\n')
2134 @{
2135 ++yylloc.last_line;
2136 yylloc.last_column = 0;
2137 @}
2138 else
2139 ++yylloc.last_column;
2140 return c;
2141 @}
2142 @end example
2143
2144 Basically, the lexical analyzer performs the same processing as before:
2145 it skips blanks and tabs, and reads numbers or single-character tokens.
2146 In addition, it updates @code{yylloc}, the global variable (of type
2147 @code{YYLTYPE}) containing the token's location.
2148
2149 Now, each time this function returns a token, the parser has its number
2150 as well as its semantic value, and its location in the text. The last
2151 needed change is to initialize @code{yylloc}, for example in the
2152 controlling function:
2153
2154 @example
2155 @group
2156 int
2157 main (void)
2158 @{
2159 yylloc.first_line = yylloc.last_line = 1;
2160 yylloc.first_column = yylloc.last_column = 0;
2161 return yyparse ();
2162 @}
2163 @end group
2164 @end example
2165
2166 Remember that computing locations is not a matter of syntax. Every
2167 character must be associated to a location update, whether it is in
2168 valid input, in comments, in literal strings, and so on.
2169
2170 @node Multi-function Calc
2171 @section Multi-Function Calculator: @code{mfcalc}
2172 @cindex multi-function calculator
2173 @cindex @code{mfcalc}
2174 @cindex calculator, multi-function
2175
2176 Now that the basics of Bison have been discussed, it is time to move on to
2177 a more advanced problem. The above calculators provided only five
2178 functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
2179 be nice to have a calculator that provides other mathematical functions such
2180 as @code{sin}, @code{cos}, etc.
2181
2182 It is easy to add new operators to the infix calculator as long as they are
2183 only single-character literals. The lexical analyzer @code{yylex} passes
2184 back all nonnumeric characters as tokens, so new grammar rules suffice for
2185 adding a new operator. But we want something more flexible: built-in
2186 functions whose syntax has this form:
2187
2188 @example
2189 @var{function_name} (@var{argument})
2190 @end example
2191
2192 @noindent
2193 At the same time, we will add memory to the calculator, by allowing you
2194 to create named variables, store values in them, and use them later.
2195 Here is a sample session with the multi-function calculator:
2196
2197 @example
2198 $ @kbd{mfcalc}
2199 @kbd{pi = 3.141592653589}
2200 3.1415926536
2201 @kbd{sin(pi)}
2202 0.0000000000
2203 @kbd{alpha = beta1 = 2.3}
2204 2.3000000000
2205 @kbd{alpha}
2206 2.3000000000
2207 @kbd{ln(alpha)}
2208 0.8329091229
2209 @kbd{exp(ln(beta1))}
2210 2.3000000000
2211 $
2212 @end example
2213
2214 Note that multiple assignment and nested function calls are permitted.
2215
2216 @menu
2217 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
2218 * Rules: Mfcalc Rules. Grammar rules for the calculator.
2219 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
2220 @end menu
2221
2222 @node Mfcalc Decl
2223 @subsection Declarations for @code{mfcalc}
2224
2225 Here are the C and Bison declarations for the multi-function calculator.
2226
2227 @smallexample
2228 @group
2229 %@{
2230 #include <math.h> /* For math functions, cos(), sin(), etc. */
2231 #include "calc.h" /* Contains definition of `symrec'. */
2232 int yylex (void);
2233 void yyerror (char const *);
2234 %@}
2235 @end group
2236 @group
2237 %union @{
2238 double val; /* For returning numbers. */
2239 symrec *tptr; /* For returning symbol-table pointers. */
2240 @}
2241 @end group
2242 %token <val> NUM /* Simple double precision number. */
2243 %token <tptr> VAR FNCT /* Variable and Function. */
2244 %type <val> exp
2245
2246 @group
2247 %right '='
2248 %left '-' '+'
2249 %left '*' '/'
2250 %left NEG /* negation--unary minus */
2251 %right '^' /* exponentiation */
2252 @end group
2253 %% /* The grammar follows. */
2254 @end smallexample
2255
2256 The above grammar introduces only two new features of the Bison language.
2257 These features allow semantic values to have various data types
2258 (@pxref{Multiple Types, ,More Than One Value Type}).
2259
2260 The @code{%union} declaration specifies the entire list of possible types;
2261 this is instead of defining @code{YYSTYPE}. The allowable types are now
2262 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
2263 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
2264
2265 Since values can now have various types, it is necessary to associate a
2266 type with each grammar symbol whose semantic value is used. These symbols
2267 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
2268 declarations are augmented with information about their data type (placed
2269 between angle brackets).
2270
2271 The Bison construct @code{%type} is used for declaring nonterminal
2272 symbols, just as @code{%token} is used for declaring token types. We
2273 have not used @code{%type} before because nonterminal symbols are
2274 normally declared implicitly by the rules that define them. But
2275 @code{exp} must be declared explicitly so we can specify its value type.
2276 @xref{Type Decl, ,Nonterminal Symbols}.
2277
2278 @node Mfcalc Rules
2279 @subsection Grammar Rules for @code{mfcalc}
2280
2281 Here are the grammar rules for the multi-function calculator.
2282 Most of them are copied directly from @code{calc}; three rules,
2283 those which mention @code{VAR} or @code{FNCT}, are new.
2284
2285 @smallexample
2286 @group
2287 input: /* empty */
2288 | input line
2289 ;
2290 @end group
2291
2292 @group
2293 line:
2294 '\n'
2295 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2296 | error '\n' @{ yyerrok; @}
2297 ;
2298 @end group
2299
2300 @group
2301 exp: NUM @{ $$ = $1; @}
2302 | VAR @{ $$ = $1->value.var; @}
2303 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
2304 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
2305 | exp '+' exp @{ $$ = $1 + $3; @}
2306 | exp '-' exp @{ $$ = $1 - $3; @}
2307 | exp '*' exp @{ $$ = $1 * $3; @}
2308 | exp '/' exp @{ $$ = $1 / $3; @}
2309 | '-' exp %prec NEG @{ $$ = -$2; @}
2310 | exp '^' exp @{ $$ = pow ($1, $3); @}
2311 | '(' exp ')' @{ $$ = $2; @}
2312 ;
2313 @end group
2314 /* End of grammar. */
2315 %%
2316 @end smallexample
2317
2318 @node Mfcalc Symtab
2319 @subsection The @code{mfcalc} Symbol Table
2320 @cindex symbol table example
2321
2322 The multi-function calculator requires a symbol table to keep track of the
2323 names and meanings of variables and functions. This doesn't affect the
2324 grammar rules (except for the actions) or the Bison declarations, but it
2325 requires some additional C functions for support.
2326
2327 The symbol table itself consists of a linked list of records. Its
2328 definition, which is kept in the header @file{calc.h}, is as follows. It
2329 provides for either functions or variables to be placed in the table.
2330
2331 @smallexample
2332 @group
2333 /* Function type. */
2334 typedef double (*func_t) (double);
2335 @end group
2336
2337 @group
2338 /* Data type for links in the chain of symbols. */
2339 struct symrec
2340 @{
2341 char *name; /* name of symbol */
2342 int type; /* type of symbol: either VAR or FNCT */
2343 union
2344 @{
2345 double var; /* value of a VAR */
2346 func_t fnctptr; /* value of a FNCT */
2347 @} value;
2348 struct symrec *next; /* link field */
2349 @};
2350 @end group
2351
2352 @group
2353 typedef struct symrec symrec;
2354
2355 /* The symbol table: a chain of `struct symrec'. */
2356 extern symrec *sym_table;
2357
2358 symrec *putsym (char const *, int);
2359 symrec *getsym (char const *);
2360 @end group
2361 @end smallexample
2362
2363 The new version of @code{main} includes a call to @code{init_table}, a
2364 function that initializes the symbol table. Here it is, and
2365 @code{init_table} as well:
2366
2367 @smallexample
2368 #include <stdio.h>
2369
2370 @group
2371 /* Called by yyparse on error. */
2372 void
2373 yyerror (char const *s)
2374 @{
2375 printf ("%s\n", s);
2376 @}
2377 @end group
2378
2379 @group
2380 struct init
2381 @{
2382 char const *fname;
2383 double (*fnct) (double);
2384 @};
2385 @end group
2386
2387 @group
2388 struct init const arith_fncts[] =
2389 @{
2390 "sin", sin,
2391 "cos", cos,
2392 "atan", atan,
2393 "ln", log,
2394 "exp", exp,
2395 "sqrt", sqrt,
2396 0, 0
2397 @};
2398 @end group
2399
2400 @group
2401 /* The symbol table: a chain of `struct symrec'. */
2402 symrec *sym_table;
2403 @end group
2404
2405 @group
2406 /* Put arithmetic functions in table. */
2407 void
2408 init_table (void)
2409 @{
2410 int i;
2411 symrec *ptr;
2412 for (i = 0; arith_fncts[i].fname != 0; i++)
2413 @{
2414 ptr = putsym (arith_fncts[i].fname, FNCT);
2415 ptr->value.fnctptr = arith_fncts[i].fnct;
2416 @}
2417 @}
2418 @end group
2419
2420 @group
2421 int
2422 main (void)
2423 @{
2424 init_table ();
2425 return yyparse ();
2426 @}
2427 @end group
2428 @end smallexample
2429
2430 By simply editing the initialization list and adding the necessary include
2431 files, you can add additional functions to the calculator.
2432
2433 Two important functions allow look-up and installation of symbols in the
2434 symbol table. The function @code{putsym} is passed a name and the type
2435 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2436 linked to the front of the list, and a pointer to the object is returned.
2437 The function @code{getsym} is passed the name of the symbol to look up. If
2438 found, a pointer to that symbol is returned; otherwise zero is returned.
2439
2440 @smallexample
2441 symrec *
2442 putsym (char const *sym_name, int sym_type)
2443 @{
2444 symrec *ptr;
2445 ptr = (symrec *) malloc (sizeof (symrec));
2446 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2447 strcpy (ptr->name,sym_name);
2448 ptr->type = sym_type;
2449 ptr->value.var = 0; /* Set value to 0 even if fctn. */
2450 ptr->next = (struct symrec *)sym_table;
2451 sym_table = ptr;
2452 return ptr;
2453 @}
2454
2455 symrec *
2456 getsym (char const *sym_name)
2457 @{
2458 symrec *ptr;
2459 for (ptr = sym_table; ptr != (symrec *) 0;
2460 ptr = (symrec *)ptr->next)
2461 if (strcmp (ptr->name,sym_name) == 0)
2462 return ptr;
2463 return 0;
2464 @}
2465 @end smallexample
2466
2467 The function @code{yylex} must now recognize variables, numeric values, and
2468 the single-character arithmetic operators. Strings of alphanumeric
2469 characters with a leading letter are recognized as either variables or
2470 functions depending on what the symbol table says about them.
2471
2472 The string is passed to @code{getsym} for look up in the symbol table. If
2473 the name appears in the table, a pointer to its location and its type
2474 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2475 already in the table, then it is installed as a @code{VAR} using
2476 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2477 returned to @code{yyparse}.
2478
2479 No change is needed in the handling of numeric values and arithmetic
2480 operators in @code{yylex}.
2481
2482 @smallexample
2483 @group
2484 #include <ctype.h>
2485 @end group
2486
2487 @group
2488 int
2489 yylex (void)
2490 @{
2491 int c;
2492
2493 /* Ignore white space, get first nonwhite character. */
2494 while ((c = getchar ()) == ' ' || c == '\t');
2495
2496 if (c == EOF)
2497 return 0;
2498 @end group
2499
2500 @group
2501 /* Char starts a number => parse the number. */
2502 if (c == '.' || isdigit (c))
2503 @{
2504 ungetc (c, stdin);
2505 scanf ("%lf", &yylval.val);
2506 return NUM;
2507 @}
2508 @end group
2509
2510 @group
2511 /* Char starts an identifier => read the name. */
2512 if (isalpha (c))
2513 @{
2514 symrec *s;
2515 static char *symbuf = 0;
2516 static int length = 0;
2517 int i;
2518 @end group
2519
2520 @group
2521 /* Initially make the buffer long enough
2522 for a 40-character symbol name. */
2523 if (length == 0)
2524 length = 40, symbuf = (char *)malloc (length + 1);
2525
2526 i = 0;
2527 do
2528 @end group
2529 @group
2530 @{
2531 /* If buffer is full, make it bigger. */
2532 if (i == length)
2533 @{
2534 length *= 2;
2535 symbuf = (char *) realloc (symbuf, length + 1);
2536 @}
2537 /* Add this character to the buffer. */
2538 symbuf[i++] = c;
2539 /* Get another character. */
2540 c = getchar ();
2541 @}
2542 @end group
2543 @group
2544 while (isalnum (c));
2545
2546 ungetc (c, stdin);
2547 symbuf[i] = '\0';
2548 @end group
2549
2550 @group
2551 s = getsym (symbuf);
2552 if (s == 0)
2553 s = putsym (symbuf, VAR);
2554 yylval.tptr = s;
2555 return s->type;
2556 @}
2557
2558 /* Any other character is a token by itself. */
2559 return c;
2560 @}
2561 @end group
2562 @end smallexample
2563
2564 This program is both powerful and flexible. You may easily add new
2565 functions, and it is a simple job to modify this code to install
2566 predefined variables such as @code{pi} or @code{e} as well.
2567
2568 @node Exercises
2569 @section Exercises
2570 @cindex exercises
2571
2572 @enumerate
2573 @item
2574 Add some new functions from @file{math.h} to the initialization list.
2575
2576 @item
2577 Add another array that contains constants and their values. Then
2578 modify @code{init_table} to add these constants to the symbol table.
2579 It will be easiest to give the constants type @code{VAR}.
2580
2581 @item
2582 Make the program report an error if the user refers to an
2583 uninitialized variable in any way except to store a value in it.
2584 @end enumerate
2585
2586 @node Grammar File
2587 @chapter Bison Grammar Files
2588
2589 Bison takes as input a context-free grammar specification and produces a
2590 C-language function that recognizes correct instances of the grammar.
2591
2592 The Bison grammar input file conventionally has a name ending in @samp{.y}.
2593 @xref{Invocation, ,Invoking Bison}.
2594
2595 @menu
2596 * Grammar Outline:: Overall layout of the grammar file.
2597 * Symbols:: Terminal and nonterminal symbols.
2598 * Rules:: How to write grammar rules.
2599 * Recursion:: Writing recursive rules.
2600 * Semantics:: Semantic values and actions.
2601 * Locations:: Locations and actions.
2602 * Declarations:: All kinds of Bison declarations are described here.
2603 * Multiple Parsers:: Putting more than one Bison parser in one program.
2604 @end menu
2605
2606 @node Grammar Outline
2607 @section Outline of a Bison Grammar
2608
2609 A Bison grammar file has four main sections, shown here with the
2610 appropriate delimiters:
2611
2612 @example
2613 %@{
2614 @var{Prologue}
2615 %@}
2616
2617 @var{Bison declarations}
2618
2619 %%
2620 @var{Grammar rules}
2621 %%
2622
2623 @var{Epilogue}
2624 @end example
2625
2626 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2627 As a @acronym{GNU} extension, @samp{//} introduces a comment that
2628 continues until end of line.
2629
2630 @menu
2631 * Prologue:: Syntax and usage of the prologue.
2632 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
2633 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2634 * Grammar Rules:: Syntax and usage of the grammar rules section.
2635 * Epilogue:: Syntax and usage of the epilogue.
2636 @end menu
2637
2638 @node Prologue
2639 @subsection The prologue
2640 @cindex declarations section
2641 @cindex Prologue
2642 @cindex declarations
2643
2644 The @var{Prologue} section contains macro definitions and declarations
2645 of functions and variables that are used in the actions in the grammar
2646 rules. These are copied to the beginning of the parser file so that
2647 they precede the definition of @code{yyparse}. You can use
2648 @samp{#include} to get the declarations from a header file. If you
2649 don't need any C declarations, you may omit the @samp{%@{} and
2650 @samp{%@}} delimiters that bracket this section.
2651
2652 The @var{Prologue} section is terminated by the first occurrence
2653 of @samp{%@}} that is outside a comment, a string literal, or a
2654 character constant.
2655
2656 You may have more than one @var{Prologue} section, intermixed with the
2657 @var{Bison declarations}. This allows you to have C and Bison
2658 declarations that refer to each other. For example, the @code{%union}
2659 declaration may use types defined in a header file, and you may wish to
2660 prototype functions that take arguments of type @code{YYSTYPE}. This
2661 can be done with two @var{Prologue} blocks, one before and one after the
2662 @code{%union} declaration.
2663
2664 @smallexample
2665 %@{
2666 #define _GNU_SOURCE
2667 #include <stdio.h>
2668 #include "ptypes.h"
2669 %@}
2670
2671 %union @{
2672 long int n;
2673 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2674 @}
2675
2676 %@{
2677 static void print_token_value (FILE *, int, YYSTYPE);
2678 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2679 %@}
2680
2681 @dots{}
2682 @end smallexample
2683
2684 When in doubt, it is usually safer to put prologue code before all
2685 Bison declarations, rather than after. For example, any definitions
2686 of feature test macros like @code{_GNU_SOURCE} or
2687 @code{_POSIX_C_SOURCE} should appear before all Bison declarations, as
2688 feature test macros can affect the behavior of Bison-generated
2689 @code{#include} directives.
2690
2691 @node Prologue Alternatives
2692 @subsection Prologue Alternatives
2693 @cindex Prologue Alternatives
2694
2695 @findex %code
2696 @findex %code requires
2697 @findex %code provides
2698 @findex %code top
2699 (The prologue alternatives described here are experimental.
2700 More user feedback will help to determine whether they should become permanent
2701 features.)
2702
2703 The functionality of @var{Prologue} sections can often be subtle and
2704 inflexible.
2705 As an alternative, Bison provides a %code directive with an explicit qualifier
2706 field, which identifies the purpose of the code and thus the location(s) where
2707 Bison should generate it.
2708 For C/C++, the qualifier can be omitted for the default location, or it can be
2709 one of @code{requires}, @code{provides}, @code{top}.
2710 @xref{Decl Summary,,%code}.
2711
2712 Look again at the example of the previous section:
2713
2714 @smallexample
2715 %@{
2716 #define _GNU_SOURCE
2717 #include <stdio.h>
2718 #include "ptypes.h"
2719 %@}
2720
2721 %union @{
2722 long int n;
2723 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2724 @}
2725
2726 %@{
2727 static void print_token_value (FILE *, int, YYSTYPE);
2728 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2729 %@}
2730
2731 @dots{}
2732 @end smallexample
2733
2734 @noindent
2735 Notice that there are two @var{Prologue} sections here, but there's a subtle
2736 distinction between their functionality.
2737 For example, if you decide to override Bison's default definition for
2738 @code{YYLTYPE}, in which @var{Prologue} section should you write your new
2739 definition?
2740 You should write it in the first since Bison will insert that code into the
2741 parser source code file @emph{before} the default @code{YYLTYPE} definition.
2742 In which @var{Prologue} section should you prototype an internal function,
2743 @code{trace_token}, that accepts @code{YYLTYPE} and @code{yytokentype} as
2744 arguments?
2745 You should prototype it in the second since Bison will insert that code
2746 @emph{after} the @code{YYLTYPE} and @code{yytokentype} definitions.
2747
2748 This distinction in functionality between the two @var{Prologue} sections is
2749 established by the appearance of the @code{%union} between them.
2750 This behavior raises a few questions.
2751 First, why should the position of a @code{%union} affect definitions related to
2752 @code{YYLTYPE} and @code{yytokentype}?
2753 Second, what if there is no @code{%union}?
2754 In that case, the second kind of @var{Prologue} section is not available.
2755 This behavior is not intuitive.
2756
2757 To avoid this subtle @code{%union} dependency, rewrite the example using a
2758 @code{%code top} and an unqualified @code{%code}.
2759 Let's go ahead and add the new @code{YYLTYPE} definition and the
2760 @code{trace_token} prototype at the same time:
2761
2762 @smallexample
2763 %code top @{
2764 #define _GNU_SOURCE
2765 #include <stdio.h>
2766
2767 /* WARNING: The following code really belongs
2768 * in a `%code requires'; see below. */
2769
2770 #include "ptypes.h"
2771 #define YYLTYPE YYLTYPE
2772 typedef struct YYLTYPE
2773 @{
2774 int first_line;
2775 int first_column;
2776 int last_line;
2777 int last_column;
2778 char *filename;
2779 @} YYLTYPE;
2780 @}
2781
2782 %union @{
2783 long int n;
2784 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2785 @}
2786
2787 %code @{
2788 static void print_token_value (FILE *, int, YYSTYPE);
2789 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2790 static void trace_token (enum yytokentype token, YYLTYPE loc);
2791 @}
2792
2793 @dots{}
2794 @end smallexample
2795
2796 @noindent
2797 In this way, @code{%code top} and the unqualified @code{%code} achieve the same
2798 functionality as the two kinds of @var{Prologue} sections, but it's always
2799 explicit which kind you intend.
2800 Moreover, both kinds are always available even in the absence of @code{%union}.
2801
2802 The @code{%code top} block above logically contains two parts.
2803 The first two lines before the warning need to appear near the top of the
2804 parser source code file.
2805 The first line after the warning is required by @code{YYSTYPE} and thus also
2806 needs to appear in the parser source code file.
2807 However, if you've instructed Bison to generate a parser header file
2808 (@pxref{Decl Summary, ,%defines}), you probably want that line to appear before
2809 the @code{YYSTYPE} definition in that header file as well.
2810 The @code{YYLTYPE} definition should also appear in the parser header file to
2811 override the default @code{YYLTYPE} definition there.
2812
2813 In other words, in the @code{%code top} block above, all but the first two
2814 lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
2815 definitions.
2816 Thus, they belong in one or more @code{%code requires}:
2817
2818 @smallexample
2819 %code top @{
2820 #define _GNU_SOURCE
2821 #include <stdio.h>
2822 @}
2823
2824 %code requires @{
2825 #include "ptypes.h"
2826 @}
2827 %union @{
2828 long int n;
2829 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2830 @}
2831
2832 %code requires @{
2833 #define YYLTYPE YYLTYPE
2834 typedef struct YYLTYPE
2835 @{
2836 int first_line;
2837 int first_column;
2838 int last_line;
2839 int last_column;
2840 char *filename;
2841 @} YYLTYPE;
2842 @}
2843
2844 %code @{
2845 static void print_token_value (FILE *, int, YYSTYPE);
2846 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2847 static void trace_token (enum yytokentype token, YYLTYPE loc);
2848 @}
2849
2850 @dots{}
2851 @end smallexample
2852
2853 @noindent
2854 Now Bison will insert @code{#include "ptypes.h"} and the new @code{YYLTYPE}
2855 definition before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
2856 definitions in both the parser source code file and the parser header file.
2857 (By the same reasoning, @code{%code requires} would also be the appropriate
2858 place to write your own definition for @code{YYSTYPE}.)
2859
2860 When you are writing dependency code for @code{YYSTYPE} and @code{YYLTYPE}, you
2861 should prefer @code{%code requires} over @code{%code top} regardless of whether
2862 you instruct Bison to generate a parser header file.
2863 When you are writing code that you need Bison to insert only into the parser
2864 source code file and that has no special need to appear at the top of that
2865 file, you should prefer the unqualified @code{%code} over @code{%code top}.
2866 These practices will make the purpose of each block of your code explicit to
2867 Bison and to other developers reading your grammar file.
2868 Following these practices, we expect the unqualified @code{%code} and
2869 @code{%code requires} to be the most important of the four @var{Prologue}
2870 alternatives.
2871
2872 At some point while developing your parser, you might decide to provide
2873 @code{trace_token} to modules that are external to your parser.
2874 Thus, you might wish for Bison to insert the prototype into both the parser
2875 header file and the parser source code file.
2876 Since this function is not a dependency required by @code{YYSTYPE} or
2877 @code{YYLTYPE}, it doesn't make sense to move its prototype to a
2878 @code{%code requires}.
2879 More importantly, since it depends upon @code{YYLTYPE} and @code{yytokentype},
2880 @code{%code requires} is not sufficient.
2881 Instead, move its prototype from the unqualified @code{%code} to a
2882 @code{%code provides}:
2883
2884 @smallexample
2885 %code top @{
2886 #define _GNU_SOURCE
2887 #include <stdio.h>
2888 @}
2889
2890 %code requires @{
2891 #include "ptypes.h"
2892 @}
2893 %union @{
2894 long int n;
2895 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2896 @}
2897
2898 %code requires @{
2899 #define YYLTYPE YYLTYPE
2900 typedef struct YYLTYPE
2901 @{
2902 int first_line;
2903 int first_column;
2904 int last_line;
2905 int last_column;
2906 char *filename;
2907 @} YYLTYPE;
2908 @}
2909
2910 %code provides @{
2911 void trace_token (enum yytokentype token, YYLTYPE loc);
2912 @}
2913
2914 %code @{
2915 static void print_token_value (FILE *, int, YYSTYPE);
2916 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2917 @}
2918
2919 @dots{}
2920 @end smallexample
2921
2922 @noindent
2923 Bison will insert the @code{trace_token} prototype into both the parser header
2924 file and the parser source code file after the definitions for
2925 @code{yytokentype}, @code{YYLTYPE}, and @code{YYSTYPE}.
2926
2927 The above examples are careful to write directives in an order that reflects
2928 the layout of the generated parser source code and header files:
2929 @code{%code top}, @code{%code requires}, @code{%code provides}, and then
2930 @code{%code}.
2931 While your grammar files may generally be easier to read if you also follow
2932 this order, Bison does not require it.
2933 Instead, Bison lets you choose an organization that makes sense to you.
2934
2935 You may declare any of these directives multiple times in the grammar file.
2936 In that case, Bison concatenates the contained code in declaration order.
2937 This is the only way in which the position of one of these directives within
2938 the grammar file affects its functionality.
2939
2940 The result of the previous two properties is greater flexibility in how you may
2941 organize your grammar file.
2942 For example, you may organize semantic-type-related directives by semantic
2943 type:
2944
2945 @smallexample
2946 %code requires @{ #include "type1.h" @}
2947 %union @{ type1 field1; @}
2948 %destructor @{ type1_free ($$); @} <field1>
2949 %printer @{ type1_print ($$); @} <field1>
2950
2951 %code requires @{ #include "type2.h" @}
2952 %union @{ type2 field2; @}
2953 %destructor @{ type2_free ($$); @} <field2>
2954 %printer @{ type2_print ($$); @} <field2>
2955 @end smallexample
2956
2957 @noindent
2958 You could even place each of the above directive groups in the rules section of
2959 the grammar file next to the set of rules that uses the associated semantic
2960 type.
2961 (In the rules section, you must terminate each of those directives with a
2962 semicolon.)
2963 And you don't have to worry that some directive (like a @code{%union}) in the
2964 definitions section is going to adversely affect their functionality in some
2965 counter-intuitive manner just because it comes first.
2966 Such an organization is not possible using @var{Prologue} sections.
2967
2968 This section has been concerned with explaining the advantages of the four
2969 @var{Prologue} alternatives over the original Yacc @var{Prologue}.
2970 However, in most cases when using these directives, you shouldn't need to
2971 think about all the low-level ordering issues discussed here.
2972 Instead, you should simply use these directives to label each block of your
2973 code according to its purpose and let Bison handle the ordering.
2974 @code{%code} is the most generic label.
2975 Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
2976 as needed.
2977
2978 @node Bison Declarations
2979 @subsection The Bison Declarations Section
2980 @cindex Bison declarations (introduction)
2981 @cindex declarations, Bison (introduction)
2982
2983 The @var{Bison declarations} section contains declarations that define
2984 terminal and nonterminal symbols, specify precedence, and so on.
2985 In some simple grammars you may not need any declarations.
2986 @xref{Declarations, ,Bison Declarations}.
2987
2988 @node Grammar Rules
2989 @subsection The Grammar Rules Section
2990 @cindex grammar rules section
2991 @cindex rules section for grammar
2992
2993 The @dfn{grammar rules} section contains one or more Bison grammar
2994 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
2995
2996 There must always be at least one grammar rule, and the first
2997 @samp{%%} (which precedes the grammar rules) may never be omitted even
2998 if it is the first thing in the file.
2999
3000 @node Epilogue
3001 @subsection The epilogue
3002 @cindex additional C code section
3003 @cindex epilogue
3004 @cindex C code, section for additional
3005
3006 The @var{Epilogue} is copied verbatim to the end of the parser file, just as
3007 the @var{Prologue} is copied to the beginning. This is the most convenient
3008 place to put anything that you want to have in the parser file but which need
3009 not come before the definition of @code{yyparse}. For example, the
3010 definitions of @code{yylex} and @code{yyerror} often go here. Because
3011 C requires functions to be declared before being used, you often need
3012 to declare functions like @code{yylex} and @code{yyerror} in the Prologue,
3013 even if you define them in the Epilogue.
3014 @xref{Interface, ,Parser C-Language Interface}.
3015
3016 If the last section is empty, you may omit the @samp{%%} that separates it
3017 from the grammar rules.
3018
3019 The Bison parser itself contains many macros and identifiers whose names
3020 start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3021 any such names (except those documented in this manual) in the epilogue
3022 of the grammar file.
3023
3024 @node Symbols
3025 @section Symbols, Terminal and Nonterminal
3026 @cindex nonterminal symbol
3027 @cindex terminal symbol
3028 @cindex token type
3029 @cindex symbol
3030
3031 @dfn{Symbols} in Bison grammars represent the grammatical classifications
3032 of the language.
3033
3034 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
3035 class of syntactically equivalent tokens. You use the symbol in grammar
3036 rules to mean that a token in that class is allowed. The symbol is
3037 represented in the Bison parser by a numeric code, and the @code{yylex}
3038 function returns a token type code to indicate what kind of token has
3039 been read. You don't need to know what the code value is; you can use
3040 the symbol to stand for it.
3041
3042 A @dfn{nonterminal symbol} stands for a class of syntactically
3043 equivalent groupings. The symbol name is used in writing grammar rules.
3044 By convention, it should be all lower case.
3045
3046 Symbol names can contain letters, digits (not at the beginning),
3047 underscores and periods. Periods make sense only in nonterminals.
3048
3049 There are three ways of writing terminal symbols in the grammar:
3050
3051 @itemize @bullet
3052 @item
3053 A @dfn{named token type} is written with an identifier, like an
3054 identifier in C@. By convention, it should be all upper case. Each
3055 such name must be defined with a Bison declaration such as
3056 @code{%token}. @xref{Token Decl, ,Token Type Names}.
3057
3058 @item
3059 @cindex character token
3060 @cindex literal token
3061 @cindex single-character literal
3062 A @dfn{character token type} (or @dfn{literal character token}) is
3063 written in the grammar using the same syntax used in C for character
3064 constants; for example, @code{'+'} is a character token type. A
3065 character token type doesn't need to be declared unless you need to
3066 specify its semantic value data type (@pxref{Value Type, ,Data Types of
3067 Semantic Values}), associativity, or precedence (@pxref{Precedence,
3068 ,Operator Precedence}).
3069
3070 By convention, a character token type is used only to represent a
3071 token that consists of that particular character. Thus, the token
3072 type @code{'+'} is used to represent the character @samp{+} as a
3073 token. Nothing enforces this convention, but if you depart from it,
3074 your program will confuse other readers.
3075
3076 All the usual escape sequences used in character literals in C can be
3077 used in Bison as well, but you must not use the null character as a
3078 character literal because its numeric code, zero, signifies
3079 end-of-input (@pxref{Calling Convention, ,Calling Convention
3080 for @code{yylex}}). Also, unlike standard C, trigraphs have no
3081 special meaning in Bison character literals, nor is backslash-newline
3082 allowed.
3083
3084 @item
3085 @cindex string token
3086 @cindex literal string token
3087 @cindex multicharacter literal
3088 A @dfn{literal string token} is written like a C string constant; for
3089 example, @code{"<="} is a literal string token. A literal string token
3090 doesn't need to be declared unless you need to specify its semantic
3091 value data type (@pxref{Value Type}), associativity, or precedence
3092 (@pxref{Precedence}).
3093
3094 You can associate the literal string token with a symbolic name as an
3095 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
3096 Declarations}). If you don't do that, the lexical analyzer has to
3097 retrieve the token number for the literal string token from the
3098 @code{yytname} table (@pxref{Calling Convention}).
3099
3100 @strong{Warning}: literal string tokens do not work in Yacc.
3101
3102 By convention, a literal string token is used only to represent a token
3103 that consists of that particular string. Thus, you should use the token
3104 type @code{"<="} to represent the string @samp{<=} as a token. Bison
3105 does not enforce this convention, but if you depart from it, people who
3106 read your program will be confused.
3107
3108 All the escape sequences used in string literals in C can be used in
3109 Bison as well, except that you must not use a null character within a
3110 string literal. Also, unlike Standard C, trigraphs have no special
3111 meaning in Bison string literals, nor is backslash-newline allowed. A
3112 literal string token must contain two or more characters; for a token
3113 containing just one character, use a character token (see above).
3114 @end itemize
3115
3116 How you choose to write a terminal symbol has no effect on its
3117 grammatical meaning. That depends only on where it appears in rules and
3118 on when the parser function returns that symbol.
3119
3120 The value returned by @code{yylex} is always one of the terminal
3121 symbols, except that a zero or negative value signifies end-of-input.
3122 Whichever way you write the token type in the grammar rules, you write
3123 it the same way in the definition of @code{yylex}. The numeric code
3124 for a character token type is simply the positive numeric code of the
3125 character, so @code{yylex} can use the identical value to generate the
3126 requisite code, though you may need to convert it to @code{unsigned
3127 char} to avoid sign-extension on hosts where @code{char} is signed.
3128 Each named token type becomes a C macro in
3129 the parser file, so @code{yylex} can use the name to stand for the code.
3130 (This is why periods don't make sense in terminal symbols.)
3131 @xref{Calling Convention, ,Calling Convention for @code{yylex}}.
3132
3133 If @code{yylex} is defined in a separate file, you need to arrange for the
3134 token-type macro definitions to be available there. Use the @samp{-d}
3135 option when you run Bison, so that it will write these macro definitions
3136 into a separate header file @file{@var{name}.tab.h} which you can include
3137 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
3138
3139 If you want to write a grammar that is portable to any Standard C
3140 host, you must use only nonnull character tokens taken from the basic
3141 execution character set of Standard C@. This set consists of the ten
3142 digits, the 52 lower- and upper-case English letters, and the
3143 characters in the following C-language string:
3144
3145 @example
3146 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3147 @end example
3148
3149 The @code{yylex} function and Bison must use a consistent character set
3150 and encoding for character tokens. For example, if you run Bison in an
3151 @acronym{ASCII} environment, but then compile and run the resulting
3152 program in an environment that uses an incompatible character set like
3153 @acronym{EBCDIC}, the resulting program may not work because the tables
3154 generated by Bison will assume @acronym{ASCII} numeric values for
3155 character tokens. It is standard practice for software distributions to
3156 contain C source files that were generated by Bison in an
3157 @acronym{ASCII} environment, so installers on platforms that are
3158 incompatible with @acronym{ASCII} must rebuild those files before
3159 compiling them.
3160
3161 The symbol @code{error} is a terminal symbol reserved for error recovery
3162 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
3163 In particular, @code{yylex} should never return this value. The default
3164 value of the error token is 256, unless you explicitly assigned 256 to
3165 one of your tokens with a @code{%token} declaration.
3166
3167 @node Rules
3168 @section Syntax of Grammar Rules
3169 @cindex rule syntax
3170 @cindex grammar rule syntax
3171 @cindex syntax of grammar rules
3172
3173 A Bison grammar rule has the following general form:
3174
3175 @example
3176 @group
3177 @var{result}: @var{components}@dots{}
3178 ;
3179 @end group
3180 @end example
3181
3182 @noindent
3183 where @var{result} is the nonterminal symbol that this rule describes,
3184 and @var{components} are various terminal and nonterminal symbols that
3185 are put together by this rule (@pxref{Symbols}).
3186
3187 For example,
3188
3189 @example
3190 @group
3191 exp: exp '+' exp
3192 ;
3193 @end group
3194 @end example
3195
3196 @noindent
3197 says that two groupings of type @code{exp}, with a @samp{+} token in between,
3198 can be combined into a larger grouping of type @code{exp}.
3199
3200 White space in rules is significant only to separate symbols. You can add
3201 extra white space as you wish.
3202
3203 Scattered among the components can be @var{actions} that determine
3204 the semantics of the rule. An action looks like this:
3205
3206 @example
3207 @{@var{C statements}@}
3208 @end example
3209
3210 @noindent
3211 @cindex braced code
3212 This is an example of @dfn{braced code}, that is, C code surrounded by
3213 braces, much like a compound statement in C@. Braced code can contain
3214 any sequence of C tokens, so long as its braces are balanced. Bison
3215 does not check the braced code for correctness directly; it merely
3216 copies the code to the output file, where the C compiler can check it.
3217
3218 Within braced code, the balanced-brace count is not affected by braces
3219 within comments, string literals, or character constants, but it is
3220 affected by the C digraphs @samp{<%} and @samp{%>} that represent
3221 braces. At the top level braced code must be terminated by @samp{@}}
3222 and not by a digraph. Bison does not look for trigraphs, so if braced
3223 code uses trigraphs you should ensure that they do not affect the
3224 nesting of braces or the boundaries of comments, string literals, or
3225 character constants.
3226
3227 Usually there is only one action and it follows the components.
3228 @xref{Actions}.
3229
3230 @findex |
3231 Multiple rules for the same @var{result} can be written separately or can
3232 be joined with the vertical-bar character @samp{|} as follows:
3233
3234 @example
3235 @group
3236 @var{result}: @var{rule1-components}@dots{}
3237 | @var{rule2-components}@dots{}
3238 @dots{}
3239 ;
3240 @end group
3241 @end example
3242
3243 @noindent
3244 They are still considered distinct rules even when joined in this way.
3245
3246 If @var{components} in a rule is empty, it means that @var{result} can
3247 match the empty string. For example, here is how to define a
3248 comma-separated sequence of zero or more @code{exp} groupings:
3249
3250 @example
3251 @group
3252 expseq: /* empty */
3253 | expseq1
3254 ;
3255 @end group
3256
3257 @group
3258 expseq1: exp
3259 | expseq1 ',' exp
3260 ;
3261 @end group
3262 @end example
3263
3264 @noindent
3265 It is customary to write a comment @samp{/* empty */} in each rule
3266 with no components.
3267
3268 @node Recursion
3269 @section Recursive Rules
3270 @cindex recursive rule
3271
3272 A rule is called @dfn{recursive} when its @var{result} nonterminal
3273 appears also on its right hand side. Nearly all Bison grammars need to
3274 use recursion, because that is the only way to define a sequence of any
3275 number of a particular thing. Consider this recursive definition of a
3276 comma-separated sequence of one or more expressions:
3277
3278 @example
3279 @group
3280 expseq1: exp
3281 | expseq1 ',' exp
3282 ;
3283 @end group
3284 @end example
3285
3286 @cindex left recursion
3287 @cindex right recursion
3288 @noindent
3289 Since the recursive use of @code{expseq1} is the leftmost symbol in the
3290 right hand side, we call this @dfn{left recursion}. By contrast, here
3291 the same construct is defined using @dfn{right recursion}:
3292
3293 @example
3294 @group
3295 expseq1: exp
3296 | exp ',' expseq1
3297 ;
3298 @end group
3299 @end example
3300
3301 @noindent
3302 Any kind of sequence can be defined using either left recursion or right
3303 recursion, but you should always use left recursion, because it can
3304 parse a sequence of any number of elements with bounded stack space.
3305 Right recursion uses up space on the Bison stack in proportion to the
3306 number of elements in the sequence, because all the elements must be
3307 shifted onto the stack before the rule can be applied even once.
3308 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
3309 of this.
3310
3311 @cindex mutual recursion
3312 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3313 rule does not appear directly on its right hand side, but does appear
3314 in rules for other nonterminals which do appear on its right hand
3315 side.
3316
3317 For example:
3318
3319 @example
3320 @group
3321 expr: primary
3322 | primary '+' primary
3323 ;
3324 @end group
3325
3326 @group
3327 primary: constant
3328 | '(' expr ')'
3329 ;
3330 @end group
3331 @end example
3332
3333 @noindent
3334 defines two mutually-recursive nonterminals, since each refers to the
3335 other.
3336
3337 @node Semantics
3338 @section Defining Language Semantics
3339 @cindex defining language semantics
3340 @cindex language semantics, defining
3341
3342 The grammar rules for a language determine only the syntax. The semantics
3343 are determined by the semantic values associated with various tokens and
3344 groupings, and by the actions taken when various groupings are recognized.
3345
3346 For example, the calculator calculates properly because the value
3347 associated with each expression is the proper number; it adds properly
3348 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3349 the numbers associated with @var{x} and @var{y}.
3350
3351 @menu
3352 * Value Type:: Specifying one data type for all semantic values.
3353 * Multiple Types:: Specifying several alternative data types.
3354 * Actions:: An action is the semantic definition of a grammar rule.
3355 * Action Types:: Specifying data types for actions to operate on.
3356 * Mid-Rule Actions:: Most actions go at the end of a rule.
3357 This says when, why and how to use the exceptional
3358 action in the middle of a rule.
3359 @end menu
3360
3361 @node Value Type
3362 @subsection Data Types of Semantic Values
3363 @cindex semantic value type
3364 @cindex value type, semantic
3365 @cindex data types of semantic values
3366 @cindex default data type
3367
3368 In a simple program it may be sufficient to use the same data type for
3369 the semantic values of all language constructs. This was true in the
3370 @acronym{RPN} and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
3371 Notation Calculator}).
3372
3373 Bison normally uses the type @code{int} for semantic values if your
3374 program uses the same data type for all language constructs. To
3375 specify some other type, define @code{YYSTYPE} as a macro, like this:
3376
3377 @example
3378 #define YYSTYPE double
3379 @end example
3380
3381 @noindent
3382 @code{YYSTYPE}'s replacement list should be a type name
3383 that does not contain parentheses or square brackets.
3384 This macro definition must go in the prologue of the grammar file
3385 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
3386
3387 @node Multiple Types
3388 @subsection More Than One Value Type
3389
3390 In most programs, you will need different data types for different kinds
3391 of tokens and groupings. For example, a numeric constant may need type
3392 @code{int} or @code{long int}, while a string constant needs type
3393 @code{char *}, and an identifier might need a pointer to an entry in the
3394 symbol table.
3395
3396 To use more than one data type for semantic values in one parser, Bison
3397 requires you to do two things:
3398
3399 @itemize @bullet
3400 @item
3401 Specify the entire collection of possible data types, either by using the
3402 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
3403 Value Types}), or by using a @code{typedef} or a @code{#define} to
3404 define @code{YYSTYPE} to be a union type whose member names are
3405 the type tags.
3406
3407 @item
3408 Choose one of those types for each symbol (terminal or nonterminal) for
3409 which semantic values are used. This is done for tokens with the
3410 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
3411 and for groupings with the @code{%type} Bison declaration (@pxref{Type
3412 Decl, ,Nonterminal Symbols}).
3413 @end itemize
3414
3415 @node Actions
3416 @subsection Actions
3417 @cindex action
3418 @vindex $$
3419 @vindex $@var{n}
3420
3421 An action accompanies a syntactic rule and contains C code to be executed
3422 each time an instance of that rule is recognized. The task of most actions
3423 is to compute a semantic value for the grouping built by the rule from the
3424 semantic values associated with tokens or smaller groupings.
3425
3426 An action consists of braced code containing C statements, and can be
3427 placed at any position in the rule;
3428 it is executed at that position. Most rules have just one action at the
3429 end of the rule, following all the components. Actions in the middle of
3430 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
3431 Actions, ,Actions in Mid-Rule}).
3432
3433 The C code in an action can refer to the semantic values of the components
3434 matched by the rule with the construct @code{$@var{n}}, which stands for
3435 the value of the @var{n}th component. The semantic value for the grouping
3436 being constructed is @code{$$}. Bison translates both of these
3437 constructs into expressions of the appropriate type when it copies the
3438 actions into the parser file. @code{$$} is translated to a modifiable
3439 lvalue, so it can be assigned to.
3440
3441 Here is a typical example:
3442
3443 @example
3444 @group
3445 exp: @dots{}
3446 | exp '+' exp
3447 @{ $$ = $1 + $3; @}
3448 @end group
3449 @end example
3450
3451 @noindent
3452 This rule constructs an @code{exp} from two smaller @code{exp} groupings
3453 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
3454 refer to the semantic values of the two component @code{exp} groupings,
3455 which are the first and third symbols on the right hand side of the rule.
3456 The sum is stored into @code{$$} so that it becomes the semantic value of
3457 the addition-expression just recognized by the rule. If there were a
3458 useful semantic value associated with the @samp{+} token, it could be
3459 referred to as @code{$2}.
3460
3461 Note that the vertical-bar character @samp{|} is really a rule
3462 separator, and actions are attached to a single rule. This is a
3463 difference with tools like Flex, for which @samp{|} stands for either
3464 ``or'', or ``the same action as that of the next rule''. In the
3465 following example, the action is triggered only when @samp{b} is found:
3466
3467 @example
3468 @group
3469 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
3470 @end group
3471 @end example
3472
3473 @cindex default action
3474 If you don't specify an action for a rule, Bison supplies a default:
3475 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule
3476 becomes the value of the whole rule. Of course, the default action is
3477 valid only if the two data types match. There is no meaningful default
3478 action for an empty rule; every empty rule must have an explicit action
3479 unless the rule's value does not matter.
3480
3481 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
3482 to tokens and groupings on the stack @emph{before} those that match the
3483 current rule. This is a very risky practice, and to use it reliably
3484 you must be certain of the context in which the rule is applied. Here
3485 is a case in which you can use this reliably:
3486
3487 @example
3488 @group
3489 foo: expr bar '+' expr @{ @dots{} @}
3490 | expr bar '-' expr @{ @dots{} @}
3491 ;
3492 @end group
3493
3494 @group
3495 bar: /* empty */
3496 @{ previous_expr = $0; @}
3497 ;
3498 @end group
3499 @end example
3500
3501 As long as @code{bar} is used only in the fashion shown here, @code{$0}
3502 always refers to the @code{expr} which precedes @code{bar} in the
3503 definition of @code{foo}.
3504
3505 @vindex yylval
3506 It is also possible to access the semantic value of the lookahead token, if
3507 any, from a semantic action.
3508 This semantic value is stored in @code{yylval}.
3509 @xref{Action Features, ,Special Features for Use in Actions}.
3510
3511 @node Action Types
3512 @subsection Data Types of Values in Actions
3513 @cindex action data types
3514 @cindex data types in actions
3515
3516 If you have chosen a single data type for semantic values, the @code{$$}
3517 and @code{$@var{n}} constructs always have that data type.
3518
3519 If you have used @code{%union} to specify a variety of data types, then you
3520 must declare a choice among these types for each terminal or nonterminal
3521 symbol that can have a semantic value. Then each time you use @code{$$} or
3522 @code{$@var{n}}, its data type is determined by which symbol it refers to
3523 in the rule. In this example,
3524
3525 @example
3526 @group
3527 exp: @dots{}
3528 | exp '+' exp
3529 @{ $$ = $1 + $3; @}
3530 @end group
3531 @end example
3532
3533 @noindent
3534 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
3535 have the data type declared for the nonterminal symbol @code{exp}. If
3536 @code{$2} were used, it would have the data type declared for the
3537 terminal symbol @code{'+'}, whatever that might be.
3538
3539 Alternatively, you can specify the data type when you refer to the value,
3540 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
3541 reference. For example, if you have defined types as shown here:
3542
3543 @example
3544 @group
3545 %union @{
3546 int itype;
3547 double dtype;
3548 @}
3549 @end group
3550 @end example
3551
3552 @noindent
3553 then you can write @code{$<itype>1} to refer to the first subunit of the
3554 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
3555
3556 @node Mid-Rule Actions
3557 @subsection Actions in Mid-Rule
3558 @cindex actions in mid-rule
3559 @cindex mid-rule actions
3560
3561 Occasionally it is useful to put an action in the middle of a rule.
3562 These actions are written just like usual end-of-rule actions, but they
3563 are executed before the parser even recognizes the following components.
3564
3565 A mid-rule action may refer to the components preceding it using
3566 @code{$@var{n}}, but it may not refer to subsequent components because
3567 it is run before they are parsed.
3568
3569 The mid-rule action itself counts as one of the components of the rule.
3570 This makes a difference when there is another action later in the same rule
3571 (and usually there is another at the end): you have to count the actions
3572 along with the symbols when working out which number @var{n} to use in
3573 @code{$@var{n}}.
3574
3575 The mid-rule action can also have a semantic value. The action can set
3576 its value with an assignment to @code{$$}, and actions later in the rule
3577 can refer to the value using @code{$@var{n}}. Since there is no symbol
3578 to name the action, there is no way to declare a data type for the value
3579 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
3580 specify a data type each time you refer to this value.
3581
3582 There is no way to set the value of the entire rule with a mid-rule
3583 action, because assignments to @code{$$} do not have that effect. The
3584 only way to set the value for the entire rule is with an ordinary action
3585 at the end of the rule.
3586
3587 Here is an example from a hypothetical compiler, handling a @code{let}
3588 statement that looks like @samp{let (@var{variable}) @var{statement}} and
3589 serves to create a variable named @var{variable} temporarily for the
3590 duration of @var{statement}. To parse this construct, we must put
3591 @var{variable} into the symbol table while @var{statement} is parsed, then
3592 remove it afterward. Here is how it is done:
3593
3594 @example
3595 @group
3596 stmt: LET '(' var ')'
3597 @{ $<context>$ = push_context ();
3598 declare_variable ($3); @}
3599 stmt @{ $$ = $6;
3600 pop_context ($<context>5); @}
3601 @end group
3602 @end example
3603
3604 @noindent
3605 As soon as @samp{let (@var{variable})} has been recognized, the first
3606 action is run. It saves a copy of the current semantic context (the
3607 list of accessible variables) as its semantic value, using alternative
3608 @code{context} in the data-type union. Then it calls
3609 @code{declare_variable} to add the new variable to that list. Once the
3610 first action is finished, the embedded statement @code{stmt} can be
3611 parsed. Note that the mid-rule action is component number 5, so the
3612 @samp{stmt} is component number 6.
3613
3614 After the embedded statement is parsed, its semantic value becomes the
3615 value of the entire @code{let}-statement. Then the semantic value from the
3616 earlier action is used to restore the prior list of variables. This
3617 removes the temporary @code{let}-variable from the list so that it won't
3618 appear to exist while the rest of the program is parsed.
3619
3620 @findex %destructor
3621 @cindex discarded symbols, mid-rule actions
3622 @cindex error recovery, mid-rule actions
3623 In the above example, if the parser initiates error recovery (@pxref{Error
3624 Recovery}) while parsing the tokens in the embedded statement @code{stmt},
3625 it might discard the previous semantic context @code{$<context>5} without
3626 restoring it.
3627 Thus, @code{$<context>5} needs a destructor (@pxref{Destructor Decl, , Freeing
3628 Discarded Symbols}).
3629 However, Bison currently provides no means to declare a destructor specific to
3630 a particular mid-rule action's semantic value.
3631
3632 One solution is to bury the mid-rule action inside a nonterminal symbol and to
3633 declare a destructor for that symbol:
3634
3635 @example
3636 @group
3637 %type <context> let
3638 %destructor @{ pop_context ($$); @} let
3639
3640 %%
3641
3642 stmt: let stmt
3643 @{ $$ = $2;
3644 pop_context ($1); @}
3645 ;
3646
3647 let: LET '(' var ')'
3648 @{ $$ = push_context ();
3649 declare_variable ($3); @}
3650 ;
3651
3652 @end group
3653 @end example
3654
3655 @noindent
3656 Note that the action is now at the end of its rule.
3657 Any mid-rule action can be converted to an end-of-rule action in this way, and
3658 this is what Bison actually does to implement mid-rule actions.
3659
3660 Taking action before a rule is completely recognized often leads to
3661 conflicts since the parser must commit to a parse in order to execute the
3662 action. For example, the following two rules, without mid-rule actions,
3663 can coexist in a working parser because the parser can shift the open-brace
3664 token and look at what follows before deciding whether there is a
3665 declaration or not:
3666
3667 @example
3668 @group
3669 compound: '@{' declarations statements '@}'
3670 | '@{' statements '@}'
3671 ;
3672 @end group
3673 @end example
3674
3675 @noindent
3676 But when we add a mid-rule action as follows, the rules become nonfunctional:
3677
3678 @example
3679 @group
3680 compound: @{ prepare_for_local_variables (); @}
3681 '@{' declarations statements '@}'
3682 @end group
3683 @group
3684 | '@{' statements '@}'
3685 ;
3686 @end group
3687 @end example
3688
3689 @noindent
3690 Now the parser is forced to decide whether to run the mid-rule action
3691 when it has read no farther than the open-brace. In other words, it
3692 must commit to using one rule or the other, without sufficient
3693 information to do it correctly. (The open-brace token is what is called
3694 the @dfn{lookahead} token at this time, since the parser is still
3695 deciding what to do about it. @xref{Lookahead, ,Lookahead Tokens}.)
3696
3697 You might think that you could correct the problem by putting identical
3698 actions into the two rules, like this:
3699
3700 @example
3701 @group
3702 compound: @{ prepare_for_local_variables (); @}
3703 '@{' declarations statements '@}'
3704 | @{ prepare_for_local_variables (); @}
3705 '@{' statements '@}'
3706 ;
3707 @end group
3708 @end example
3709
3710 @noindent
3711 But this does not help, because Bison does not realize that the two actions
3712 are identical. (Bison never tries to understand the C code in an action.)
3713
3714 If the grammar is such that a declaration can be distinguished from a
3715 statement by the first token (which is true in C), then one solution which
3716 does work is to put the action after the open-brace, like this:
3717
3718 @example
3719 @group
3720 compound: '@{' @{ prepare_for_local_variables (); @}
3721 declarations statements '@}'
3722 | '@{' statements '@}'
3723 ;
3724 @end group
3725 @end example
3726
3727 @noindent
3728 Now the first token of the following declaration or statement,
3729 which would in any case tell Bison which rule to use, can still do so.
3730
3731 Another solution is to bury the action inside a nonterminal symbol which
3732 serves as a subroutine:
3733
3734 @example
3735 @group
3736 subroutine: /* empty */
3737 @{ prepare_for_local_variables (); @}
3738 ;
3739
3740 @end group
3741
3742 @group
3743 compound: subroutine
3744 '@{' declarations statements '@}'
3745 | subroutine
3746 '@{' statements '@}'
3747 ;
3748 @end group
3749 @end example
3750
3751 @noindent
3752 Now Bison can execute the action in the rule for @code{subroutine} without
3753 deciding which rule for @code{compound} it will eventually use.
3754
3755 @node Locations
3756 @section Tracking Locations
3757 @cindex location
3758 @cindex textual location
3759 @cindex location, textual
3760
3761 Though grammar rules and semantic actions are enough to write a fully
3762 functional parser, it can be useful to process some additional information,
3763 especially symbol locations.
3764
3765 The way locations are handled is defined by providing a data type, and
3766 actions to take when rules are matched.
3767
3768 @menu
3769 * Location Type:: Specifying a data type for locations.
3770 * Actions and Locations:: Using locations in actions.
3771 * Location Default Action:: Defining a general way to compute locations.
3772 @end menu
3773
3774 @node Location Type
3775 @subsection Data Type of Locations
3776 @cindex data type of locations
3777 @cindex default location type
3778
3779 Defining a data type for locations is much simpler than for semantic values,
3780 since all tokens and groupings always use the same type.
3781
3782 You can specify the type of locations by defining a macro called
3783 @code{YYLTYPE}, just as you can specify the semantic value type by
3784 defining a @code{YYSTYPE} macro (@pxref{Value Type}).
3785 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3786 four members:
3787
3788 @example
3789 typedef struct YYLTYPE
3790 @{
3791 int first_line;
3792 int first_column;
3793 int last_line;
3794 int last_column;
3795 @} YYLTYPE;
3796 @end example
3797
3798 At the beginning of the parsing, Bison initializes all these fields to 1
3799 for @code{yylloc}.
3800
3801 @node Actions and Locations
3802 @subsection Actions and Locations
3803 @cindex location actions
3804 @cindex actions, location
3805 @vindex @@$
3806 @vindex @@@var{n}
3807
3808 Actions are not only useful for defining language semantics, but also for
3809 describing the behavior of the output parser with locations.
3810
3811 The most obvious way for building locations of syntactic groupings is very
3812 similar to the way semantic values are computed. In a given rule, several
3813 constructs can be used to access the locations of the elements being matched.
3814 The location of the @var{n}th component of the right hand side is
3815 @code{@@@var{n}}, while the location of the left hand side grouping is
3816 @code{@@$}.
3817
3818 Here is a basic example using the default data type for locations:
3819
3820 @example
3821 @group
3822 exp: @dots{}
3823 | exp '/' exp
3824 @{
3825 @@$.first_column = @@1.first_column;
3826 @@$.first_line = @@1.first_line;
3827 @@$.last_column = @@3.last_column;
3828 @@$.last_line = @@3.last_line;
3829 if ($3)
3830 $$ = $1 / $3;
3831 else
3832 @{
3833 $$ = 1;
3834 fprintf (stderr,
3835 "Division by zero, l%d,c%d-l%d,c%d",
3836 @@3.first_line, @@3.first_column,
3837 @@3.last_line, @@3.last_column);
3838 @}
3839 @}
3840 @end group
3841 @end example
3842
3843 As for semantic values, there is a default action for locations that is
3844 run each time a rule is matched. It sets the beginning of @code{@@$} to the
3845 beginning of the first symbol, and the end of @code{@@$} to the end of the
3846 last symbol.
3847
3848 With this default action, the location tracking can be fully automatic. The
3849 example above simply rewrites this way:
3850
3851 @example
3852 @group
3853 exp: @dots{}
3854 | exp '/' exp
3855 @{
3856 if ($3)
3857 $$ = $1 / $3;
3858 else
3859 @{
3860 $$ = 1;
3861 fprintf (stderr,
3862 "Division by zero, l%d,c%d-l%d,c%d",
3863 @@3.first_line, @@3.first_column,
3864 @@3.last_line, @@3.last_column);
3865 @}
3866 @}
3867 @end group
3868 @end example
3869
3870 @vindex yylloc
3871 It is also possible to access the location of the lookahead token, if any,
3872 from a semantic action.
3873 This location is stored in @code{yylloc}.
3874 @xref{Action Features, ,Special Features for Use in Actions}.
3875
3876 @node Location Default Action
3877 @subsection Default Action for Locations
3878 @vindex YYLLOC_DEFAULT
3879 @cindex @acronym{GLR} parsers and @code{YYLLOC_DEFAULT}
3880
3881 Actually, actions are not the best place to compute locations. Since
3882 locations are much more general than semantic values, there is room in
3883 the output parser to redefine the default action to take for each
3884 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
3885 matched, before the associated action is run. It is also invoked
3886 while processing a syntax error, to compute the error's location.
3887 Before reporting an unresolvable syntactic ambiguity, a @acronym{GLR}
3888 parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
3889 of that ambiguity.
3890
3891 Most of the time, this macro is general enough to suppress location
3892 dedicated code from semantic actions.
3893
3894 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
3895 the location of the grouping (the result of the computation). When a
3896 rule is matched, the second parameter identifies locations of
3897 all right hand side elements of the rule being matched, and the third
3898 parameter is the size of the rule's right hand side.
3899 When a @acronym{GLR} parser reports an ambiguity, which of multiple candidate
3900 right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
3901 When processing a syntax error, the second parameter identifies locations
3902 of the symbols that were discarded during error processing, and the third
3903 parameter is the number of discarded symbols.
3904
3905 By default, @code{YYLLOC_DEFAULT} is defined this way:
3906
3907 @smallexample
3908 @group
3909 # define YYLLOC_DEFAULT(Current, Rhs, N) \
3910 do \
3911 if (N) \
3912 @{ \
3913 (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
3914 (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
3915 (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
3916 (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
3917 @} \
3918 else \
3919 @{ \
3920 (Current).first_line = (Current).last_line = \
3921 YYRHSLOC(Rhs, 0).last_line; \
3922 (Current).first_column = (Current).last_column = \
3923 YYRHSLOC(Rhs, 0).last_column; \
3924 @} \
3925 while (0)
3926 @end group
3927 @end smallexample
3928
3929 where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
3930 in @var{rhs} when @var{k} is positive, and the location of the symbol
3931 just before the reduction when @var{k} and @var{n} are both zero.
3932
3933 When defining @code{YYLLOC_DEFAULT}, you should consider that:
3934
3935 @itemize @bullet
3936 @item
3937 All arguments are free of side-effects. However, only the first one (the
3938 result) should be modified by @code{YYLLOC_DEFAULT}.
3939
3940 @item
3941 For consistency with semantic actions, valid indexes within the
3942 right hand side range from 1 to @var{n}. When @var{n} is zero, only 0 is a
3943 valid index, and it refers to the symbol just before the reduction.
3944 During error processing @var{n} is always positive.
3945
3946 @item
3947 Your macro should parenthesize its arguments, if need be, since the
3948 actual arguments may not be surrounded by parentheses. Also, your
3949 macro should expand to something that can be used as a single
3950 statement when it is followed by a semicolon.
3951 @end itemize
3952
3953 @node Declarations
3954 @section Bison Declarations
3955 @cindex declarations, Bison
3956 @cindex Bison declarations
3957
3958 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
3959 used in formulating the grammar and the data types of semantic values.
3960 @xref{Symbols}.
3961
3962 All token type names (but not single-character literal tokens such as
3963 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
3964 declared if you need to specify which data type to use for the semantic
3965 value (@pxref{Multiple Types, ,More Than One Value Type}).
3966
3967 The first rule in the file also specifies the start symbol, by default.
3968 If you want some other symbol to be the start symbol, you must declare
3969 it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free
3970 Grammars}).
3971
3972 @menu
3973 * Require Decl:: Requiring a Bison version.
3974 * Token Decl:: Declaring terminal symbols.
3975 * Precedence Decl:: Declaring terminals with precedence and associativity.
3976 * Union Decl:: Declaring the set of all semantic value types.
3977 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
3978 * Initial Action Decl:: Code run before parsing starts.
3979 * Destructor Decl:: Declaring how symbols are freed.
3980 * Expect Decl:: Suppressing warnings about parsing conflicts.
3981 * Start Decl:: Specifying the start symbol.
3982 * Pure Decl:: Requesting a reentrant parser.
3983 * Decl Summary:: Table of all Bison declarations.
3984 @end menu
3985
3986 @node Require Decl
3987 @subsection Require a Version of Bison
3988 @cindex version requirement
3989 @cindex requiring a version of Bison
3990 @findex %require
3991
3992 You may require the minimum version of Bison to process the grammar. If
3993 the requirement is not met, @command{bison} exits with an error (exit
3994 status 63).
3995
3996 @example
3997 %require "@var{version}"
3998 @end example
3999
4000 @node Token Decl
4001 @subsection Token Type Names
4002 @cindex declaring token type names
4003 @cindex token type names, declaring
4004 @cindex declaring literal string tokens
4005 @findex %token
4006
4007 The basic way to declare a token type name (terminal symbol) is as follows:
4008
4009 @example
4010 %token @var{name}
4011 @end example
4012
4013 Bison will convert this into a @code{#define} directive in
4014 the parser, so that the function @code{yylex} (if it is in this file)
4015 can use the name @var{name} to stand for this token type's code.
4016
4017 Alternatively, you can use @code{%left}, @code{%right}, or
4018 @code{%nonassoc} instead of @code{%token}, if you wish to specify
4019 associativity and precedence. @xref{Precedence Decl, ,Operator
4020 Precedence}.
4021
4022 You can explicitly specify the numeric code for a token type by appending
4023 a decimal or hexadecimal integer value in the field immediately
4024 following the token name:
4025
4026 @example
4027 %token NUM 300
4028 %token XNUM 0x12d // a GNU extension
4029 @end example
4030
4031 @noindent
4032 It is generally best, however, to let Bison choose the numeric codes for
4033 all token types. Bison will automatically select codes that don't conflict
4034 with each other or with normal characters.
4035
4036 In the event that the stack type is a union, you must augment the
4037 @code{%token} or other token declaration to include the data type
4038 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
4039 Than One Value Type}).
4040
4041 For example:
4042
4043 @example
4044 @group
4045 %union @{ /* define stack type */
4046 double val;
4047 symrec *tptr;
4048 @}
4049 %token <val> NUM /* define token NUM and its type */
4050 @end group
4051 @end example
4052
4053 You can associate a literal string token with a token type name by
4054 writing the literal string at the end of a @code{%token}
4055 declaration which declares the name. For example:
4056
4057 @example
4058 %token arrow "=>"
4059 @end example
4060
4061 @noindent
4062 For example, a grammar for the C language might specify these names with
4063 equivalent literal string tokens:
4064
4065 @example
4066 %token <operator> OR "||"
4067 %token <operator> LE 134 "<="
4068 %left OR "<="
4069 @end example
4070
4071 @noindent
4072 Once you equate the literal string and the token name, you can use them
4073 interchangeably in further declarations or the grammar rules. The
4074 @code{yylex} function can use the token name or the literal string to
4075 obtain the token type code number (@pxref{Calling Convention}).
4076
4077 @node Precedence Decl
4078 @subsection Operator Precedence
4079 @cindex precedence declarations
4080 @cindex declaring operator precedence
4081 @cindex operator precedence, declaring
4082
4083 Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
4084 declare a token and specify its precedence and associativity, all at
4085 once. These are called @dfn{precedence declarations}.
4086 @xref{Precedence, ,Operator Precedence}, for general information on
4087 operator precedence.
4088
4089 The syntax of a precedence declaration is the same as that of
4090 @code{%token}: either
4091
4092 @example
4093 %left @var{symbols}@dots{}
4094 @end example
4095
4096 @noindent
4097 or
4098
4099 @example
4100 %left <@var{type}> @var{symbols}@dots{}
4101 @end example
4102
4103 And indeed any of these declarations serves the purposes of @code{%token}.
4104 But in addition, they specify the associativity and relative precedence for
4105 all the @var{symbols}:
4106
4107 @itemize @bullet
4108 @item
4109 The associativity of an operator @var{op} determines how repeated uses
4110 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
4111 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
4112 grouping @var{y} with @var{z} first. @code{%left} specifies
4113 left-associativity (grouping @var{x} with @var{y} first) and
4114 @code{%right} specifies right-associativity (grouping @var{y} with
4115 @var{z} first). @code{%nonassoc} specifies no associativity, which
4116 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
4117 considered a syntax error.
4118
4119 @item
4120 The precedence of an operator determines how it nests with other operators.
4121 All the tokens declared in a single precedence declaration have equal
4122 precedence and nest together according to their associativity.
4123 When two tokens declared in different precedence declarations associate,
4124 the one declared later has the higher precedence and is grouped first.
4125 @end itemize
4126
4127 @node Union Decl
4128 @subsection The Collection of Value Types
4129 @cindex declaring value types
4130 @cindex value types, declaring
4131 @findex %union
4132
4133 The @code{%union} declaration specifies the entire collection of
4134 possible data types for semantic values. The keyword @code{%union} is
4135 followed by braced code containing the same thing that goes inside a
4136 @code{union} in C@.
4137
4138 For example:
4139
4140 @example
4141 @group
4142 %union @{
4143 double val;
4144 symrec *tptr;
4145 @}
4146 @end group
4147 @end example
4148
4149 @noindent
4150 This says that the two alternative types are @code{double} and @code{symrec
4151 *}. They are given names @code{val} and @code{tptr}; these names are used
4152 in the @code{%token} and @code{%type} declarations to pick one of the types
4153 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
4154
4155 As an extension to @acronym{POSIX}, a tag is allowed after the
4156 @code{union}. For example:
4157
4158 @example
4159 @group
4160 %union value @{
4161 double val;
4162 symrec *tptr;
4163 @}
4164 @end group
4165 @end example
4166
4167 @noindent
4168 specifies the union tag @code{value}, so the corresponding C type is
4169 @code{union value}. If you do not specify a tag, it defaults to
4170 @code{YYSTYPE}.
4171
4172 As another extension to @acronym{POSIX}, you may specify multiple
4173 @code{%union} declarations; their contents are concatenated. However,
4174 only the first @code{%union} declaration can specify a tag.
4175
4176 Note that, unlike making a @code{union} declaration in C, you need not write
4177 a semicolon after the closing brace.
4178
4179 Instead of @code{%union}, you can define and use your own union type
4180 @code{YYSTYPE} if your grammar contains at least one
4181 @samp{<@var{type}>} tag. For example, you can put the following into
4182 a header file @file{parser.h}:
4183
4184 @example
4185 @group
4186 union YYSTYPE @{
4187 double val;
4188 symrec *tptr;
4189 @};
4190 typedef union YYSTYPE YYSTYPE;
4191 @end group
4192 @end example
4193
4194 @noindent
4195 and then your grammar can use the following
4196 instead of @code{%union}:
4197
4198 @example
4199 @group
4200 %@{
4201 #include "parser.h"
4202 %@}
4203 %type <val> expr
4204 %token <tptr> ID
4205 @end group
4206 @end example
4207
4208 @node Type Decl
4209 @subsection Nonterminal Symbols
4210 @cindex declaring value types, nonterminals
4211 @cindex value types, nonterminals, declaring
4212 @findex %type
4213
4214 @noindent
4215 When you use @code{%union} to specify multiple value types, you must
4216 declare the value type of each nonterminal symbol for which values are
4217 used. This is done with a @code{%type} declaration, like this:
4218
4219 @example
4220 %type <@var{type}> @var{nonterminal}@dots{}
4221 @end example
4222
4223 @noindent
4224 Here @var{nonterminal} is the name of a nonterminal symbol, and
4225 @var{type} is the name given in the @code{%union} to the alternative
4226 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
4227 can give any number of nonterminal symbols in the same @code{%type}
4228 declaration, if they have the same value type. Use spaces to separate
4229 the symbol names.
4230
4231 You can also declare the value type of a terminal symbol. To do this,
4232 use the same @code{<@var{type}>} construction in a declaration for the
4233 terminal symbol. All kinds of token declarations allow
4234 @code{<@var{type}>}.
4235
4236 @node Initial Action Decl
4237 @subsection Performing Actions before Parsing
4238 @findex %initial-action
4239
4240 Sometimes your parser needs to perform some initializations before
4241 parsing. The @code{%initial-action} directive allows for such arbitrary
4242 code.
4243
4244 @deffn {Directive} %initial-action @{ @var{code} @}
4245 @findex %initial-action
4246 Declare that the braced @var{code} must be invoked before parsing each time
4247 @code{yyparse} is called. The @var{code} may use @code{$$} and
4248 @code{@@$} --- initial value and location of the lookahead --- and the
4249 @code{%parse-param}.
4250 @end deffn
4251
4252 For instance, if your locations use a file name, you may use
4253
4254 @example
4255 %parse-param @{ char const *file_name @};
4256 %initial-action
4257 @{
4258 @@$.initialize (file_name);
4259 @};
4260 @end example
4261
4262
4263 @node Destructor Decl
4264 @subsection Freeing Discarded Symbols
4265 @cindex freeing discarded symbols
4266 @findex %destructor
4267 @findex <*>
4268 @findex <>
4269 During error recovery (@pxref{Error Recovery}), symbols already pushed
4270 on the stack and tokens coming from the rest of the file are discarded
4271 until the parser falls on its feet. If the parser runs out of memory,
4272 or if it returns via @code{YYABORT} or @code{YYACCEPT}, all the
4273 symbols on the stack must be discarded. Even if the parser succeeds, it
4274 must discard the start symbol.
4275
4276 When discarded symbols convey heap based information, this memory is
4277 lost. While this behavior can be tolerable for batch parsers, such as
4278 in traditional compilers, it is unacceptable for programs like shells or
4279 protocol implementations that may parse and execute indefinitely.
4280
4281 The @code{%destructor} directive defines code that is called when a
4282 symbol is automatically discarded.
4283
4284 @deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
4285 @findex %destructor
4286 Invoke the braced @var{code} whenever the parser discards one of the
4287 @var{symbols}.
4288 Within @var{code}, @code{$$} designates the semantic value associated
4289 with the discarded symbol, and @code{@@$} designates its location.
4290 The additional parser parameters are also available (@pxref{Parser Function, ,
4291 The Parser Function @code{yyparse}}).
4292
4293 When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
4294 per-symbol @code{%destructor}.
4295 You may also define a per-type @code{%destructor} by listing a semantic type
4296 tag among @var{symbols}.
4297 In that case, the parser will invoke this @var{code} whenever it discards any
4298 grammar symbol that has that semantic type tag unless that symbol has its own
4299 per-symbol @code{%destructor}.
4300
4301 Finally, you can define two different kinds of default @code{%destructor}s.
4302 (These default forms are experimental.
4303 More user feedback will help to determine whether they should become permanent
4304 features.)
4305 You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
4306 exactly one @code{%destructor} declaration in your grammar file.
4307 The parser will invoke the @var{code} associated with one of these whenever it
4308 discards any user-defined grammar symbol that has no per-symbol and no per-type
4309 @code{%destructor}.
4310 The parser uses the @var{code} for @code{<*>} in the case of such a grammar
4311 symbol for which you have formally declared a semantic type tag (@code{%type}
4312 counts as such a declaration, but @code{$<tag>$} does not).
4313 The parser uses the @var{code} for @code{<>} in the case of such a grammar
4314 symbol that has no declared semantic type tag.
4315 @end deffn
4316
4317 @noindent
4318 For example:
4319
4320 @smallexample
4321 %union @{ char *string; @}
4322 %token <string> STRING1
4323 %token <string> STRING2
4324 %type <string> string1
4325 %type <string> string2
4326 %union @{ char character; @}
4327 %token <character> CHR
4328 %type <character> chr
4329 %token TAGLESS
4330
4331 %destructor @{ @} <character>
4332 %destructor @{ free ($$); @} <*>
4333 %destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
4334 %destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
4335 @end smallexample
4336
4337 @noindent
4338 guarantees that, when the parser discards any user-defined symbol that has a
4339 semantic type tag other than @code{<character>}, it passes its semantic value
4340 to @code{free} by default.
4341 However, when the parser discards a @code{STRING1} or a @code{string1}, it also
4342 prints its line number to @code{stdout}.
4343 It performs only the second @code{%destructor} in this case, so it invokes
4344 @code{free} only once.
4345 Finally, the parser merely prints a message whenever it discards any symbol,
4346 such as @code{TAGLESS}, that has no semantic type tag.
4347
4348 A Bison-generated parser invokes the default @code{%destructor}s only for
4349 user-defined as opposed to Bison-defined symbols.
4350 For example, the parser will not invoke either kind of default
4351 @code{%destructor} for the special Bison-defined symbols @code{$accept},
4352 @code{$undefined}, or @code{$end} (@pxref{Table of Symbols, ,Bison Symbols}),
4353 none of which you can reference in your grammar.
4354 It also will not invoke either for the @code{error} token (@pxref{Table of
4355 Symbols, ,error}), which is always defined by Bison regardless of whether you
4356 reference it in your grammar.
4357 However, it may invoke one of them for the end token (token 0) if you
4358 redefine it from @code{$end} to, for example, @code{END}:
4359
4360 @smallexample
4361 %token END 0
4362 @end smallexample
4363
4364 @cindex actions in mid-rule
4365 @cindex mid-rule actions
4366 Finally, Bison will never invoke a @code{%destructor} for an unreferenced
4367 mid-rule semantic value (@pxref{Mid-Rule Actions,,Actions in Mid-Rule}).
4368 That is, Bison does not consider a mid-rule to have a semantic value if you do
4369 not reference @code{$$} in the mid-rule's action or @code{$@var{n}} (where
4370 @var{n} is the RHS symbol position of the mid-rule) in any later action in that
4371 rule.
4372 However, if you do reference either, the Bison-generated parser will invoke the
4373 @code{<>} @code{%destructor} whenever it discards the mid-rule symbol.
4374
4375 @ignore
4376 @noindent
4377 In the future, it may be possible to redefine the @code{error} token as a
4378 nonterminal that captures the discarded symbols.
4379 In that case, the parser will invoke the default destructor for it as well.
4380 @end ignore
4381
4382 @sp 1
4383
4384 @cindex discarded symbols
4385 @dfn{Discarded symbols} are the following:
4386
4387 @itemize
4388 @item
4389 stacked symbols popped during the first phase of error recovery,
4390 @item
4391 incoming terminals during the second phase of error recovery,
4392 @item
4393 the current lookahead and the entire stack (except the current
4394 right-hand side symbols) when the parser returns immediately, and
4395 @item
4396 the start symbol, when the parser succeeds.
4397 @end itemize
4398
4399 The parser can @dfn{return immediately} because of an explicit call to
4400 @code{YYABORT} or @code{YYACCEPT}, or failed error recovery, or memory
4401 exhaustion.
4402
4403 Right-hand side symbols of a rule that explicitly triggers a syntax
4404 error via @code{YYERROR} are not discarded automatically. As a rule
4405 of thumb, destructors are invoked only when user actions cannot manage
4406 the memory.
4407
4408 @node Expect Decl
4409 @subsection Suppressing Conflict Warnings
4410 @cindex suppressing conflict warnings
4411 @cindex preventing warnings about conflicts
4412 @cindex warnings, preventing
4413 @cindex conflicts, suppressing warnings of
4414 @findex %expect
4415 @findex %expect-rr
4416
4417 Bison normally warns if there are any conflicts in the grammar
4418 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
4419 have harmless shift/reduce conflicts which are resolved in a predictable
4420 way and would be difficult to eliminate. It is desirable to suppress
4421 the warning about these conflicts unless the number of conflicts
4422 changes. You can do this with the @code{%expect} declaration.
4423
4424 The declaration looks like this:
4425
4426 @example
4427 %expect @var{n}
4428 @end example
4429
4430 Here @var{n} is a decimal integer. The declaration says there should
4431 be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
4432 Bison reports an error if the number of shift/reduce conflicts differs
4433 from @var{n}, or if there are any reduce/reduce conflicts.
4434
4435 For normal @acronym{LALR}(1) parsers, reduce/reduce conflicts are more
4436 serious, and should be eliminated entirely. Bison will always report
4437 reduce/reduce conflicts for these parsers. With @acronym{GLR}
4438 parsers, however, both kinds of conflicts are routine; otherwise,
4439 there would be no need to use @acronym{GLR} parsing. Therefore, it is
4440 also possible to specify an expected number of reduce/reduce conflicts
4441 in @acronym{GLR} parsers, using the declaration:
4442
4443 @example
4444 %expect-rr @var{n}
4445 @end example
4446
4447 In general, using @code{%expect} involves these steps:
4448
4449 @itemize @bullet
4450 @item
4451 Compile your grammar without @code{%expect}. Use the @samp{-v} option
4452 to get a verbose list of where the conflicts occur. Bison will also
4453 print the number of conflicts.
4454
4455 @item
4456 Check each of the conflicts to make sure that Bison's default
4457 resolution is what you really want. If not, rewrite the grammar and
4458 go back to the beginning.
4459
4460 @item
4461 Add an @code{%expect} declaration, copying the number @var{n} from the
4462 number which Bison printed. With @acronym{GLR} parsers, add an
4463 @code{%expect-rr} declaration as well.
4464 @end itemize
4465
4466 Now Bison will warn you if you introduce an unexpected conflict, but
4467 will keep silent otherwise.
4468
4469 @node Start Decl
4470 @subsection The Start-Symbol
4471 @cindex declaring the start symbol
4472 @cindex start symbol, declaring
4473 @cindex default start symbol
4474 @findex %start
4475
4476 Bison assumes by default that the start symbol for the grammar is the first
4477 nonterminal specified in the grammar specification section. The programmer
4478 may override this restriction with the @code{%start} declaration as follows:
4479
4480 @example
4481 %start @var{symbol}
4482 @end example
4483
4484 @node Pure Decl
4485 @subsection A Pure (Reentrant) Parser
4486 @cindex reentrant parser
4487 @cindex pure parser
4488 @findex %pure-parser
4489
4490 A @dfn{reentrant} program is one which does not alter in the course of
4491 execution; in other words, it consists entirely of @dfn{pure} (read-only)
4492 code. Reentrancy is important whenever asynchronous execution is possible;
4493 for example, a nonreentrant program may not be safe to call from a signal
4494 handler. In systems with multiple threads of control, a nonreentrant
4495 program must be called only within interlocks.
4496
4497 Normally, Bison generates a parser which is not reentrant. This is
4498 suitable for most uses, and it permits compatibility with Yacc. (The
4499 standard Yacc interfaces are inherently nonreentrant, because they use
4500 statically allocated variables for communication with @code{yylex},
4501 including @code{yylval} and @code{yylloc}.)
4502
4503 Alternatively, you can generate a pure, reentrant parser. The Bison
4504 declaration @code{%pure-parser} says that you want the parser to be
4505 reentrant. It looks like this:
4506
4507 @example
4508 %pure-parser
4509 @end example
4510
4511 The result is that the communication variables @code{yylval} and
4512 @code{yylloc} become local variables in @code{yyparse}, and a different
4513 calling convention is used for the lexical analyzer function
4514 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
4515 Parsers}, for the details of this. The variable @code{yynerrs} also
4516 becomes local in @code{yyparse} (@pxref{Error Reporting, ,The Error
4517 Reporting Function @code{yyerror}}). The convention for calling
4518 @code{yyparse} itself is unchanged.
4519
4520 Whether the parser is pure has nothing to do with the grammar rules.
4521 You can generate either a pure parser or a nonreentrant parser from any
4522 valid grammar.
4523
4524 @node Decl Summary
4525 @subsection Bison Declaration Summary
4526 @cindex Bison declaration summary
4527 @cindex declaration summary
4528 @cindex summary, Bison declaration
4529
4530 Here is a summary of the declarations used to define a grammar:
4531
4532 @deffn {Directive} %union
4533 Declare the collection of data types that semantic values may have
4534 (@pxref{Union Decl, ,The Collection of Value Types}).
4535 @end deffn
4536
4537 @deffn {Directive} %token
4538 Declare a terminal symbol (token type name) with no precedence
4539 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
4540 @end deffn
4541
4542 @deffn {Directive} %right
4543 Declare a terminal symbol (token type name) that is right-associative
4544 (@pxref{Precedence Decl, ,Operator Precedence}).
4545 @end deffn
4546
4547 @deffn {Directive} %left
4548 Declare a terminal symbol (token type name) that is left-associative
4549 (@pxref{Precedence Decl, ,Operator Precedence}).
4550 @end deffn
4551
4552 @deffn {Directive} %nonassoc
4553 Declare a terminal symbol (token type name) that is nonassociative
4554 (@pxref{Precedence Decl, ,Operator Precedence}).
4555 Using it in a way that would be associative is a syntax error.
4556 @end deffn
4557
4558 @ifset defaultprec
4559 @deffn {Directive} %default-prec
4560 Assign a precedence to rules lacking an explicit @code{%prec} modifier
4561 (@pxref{Contextual Precedence, ,Context-Dependent Precedence}).
4562 @end deffn
4563 @end ifset
4564
4565 @deffn {Directive} %type
4566 Declare the type of semantic values for a nonterminal symbol
4567 (@pxref{Type Decl, ,Nonterminal Symbols}).
4568 @end deffn
4569
4570 @deffn {Directive} %start
4571 Specify the grammar's start symbol (@pxref{Start Decl, ,The
4572 Start-Symbol}).
4573 @end deffn
4574
4575 @deffn {Directive} %expect
4576 Declare the expected number of shift-reduce conflicts
4577 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
4578 @end deffn
4579
4580
4581 @sp 1
4582 @noindent
4583 In order to change the behavior of @command{bison}, use the following
4584 directives:
4585
4586 @deffn {Directive} %code @{@var{code}@}
4587 @findex %code
4588 This is the unqualified form of the @code{%code} directive.
4589 It inserts @var{code} verbatim at a language-dependent default location in the
4590 output@footnote{The default location is actually skeleton-dependent;
4591 writers of non-standard skeletons however should choose the default location
4592 consistently with the behavior of the standard Bison skeletons.}.
4593
4594 @cindex Prologue
4595 For C/C++, the default location is the parser source code
4596 file after the usual contents of the parser header file.
4597 Thus, @code{%code} replaces the traditional Yacc prologue,
4598 @code{%@{@var{code}%@}}, for most purposes.
4599 For a detailed discussion, see @ref{Prologue Alternatives}.
4600
4601 For Java, the default location is inside the parser class.
4602
4603 (Like all the Yacc prologue alternatives, this directive is experimental.
4604 More user feedback will help to determine whether it should become a permanent
4605 feature.)
4606 @end deffn
4607
4608 @deffn {Directive} %code @var{qualifier} @{@var{code}@}
4609 This is the qualified form of the @code{%code} directive.
4610 If you need to specify location-sensitive verbatim @var{code} that does not
4611 belong at the default location selected by the unqualified @code{%code} form,
4612 use this form instead.
4613
4614 @var{qualifier} identifies the purpose of @var{code} and thus the location(s)
4615 where Bison should generate it.
4616 Not all values of @var{qualifier} are available for all target languages:
4617
4618 @itemize @bullet
4619 @findex %code requires
4620 @item requires
4621
4622 @itemize @bullet
4623 @item Language(s): C, C++
4624
4625 @item Purpose: This is the best place to write dependency code required for
4626 @code{YYSTYPE} and @code{YYLTYPE}.
4627 In other words, it's the best place to define types referenced in @code{%union}
4628 directives, and it's the best place to override Bison's default @code{YYSTYPE}
4629 and @code{YYLTYPE} definitions.
4630
4631 @item Location(s): The parser header file and the parser source code file
4632 before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE} definitions.
4633 @end itemize
4634
4635 @item provides
4636 @findex %code provides
4637
4638 @itemize @bullet
4639 @item Language(s): C, C++
4640
4641 @item Purpose: This is the best place to write additional definitions and
4642 declarations that should be provided to other modules.
4643
4644 @item Location(s): The parser header file and the parser source code file after
4645 the Bison-generated @code{YYSTYPE}, @code{YYLTYPE}, and token definitions.
4646 @end itemize
4647
4648 @item top
4649 @findex %code top
4650
4651 @itemize @bullet
4652 @item Language(s): C, C++
4653
4654 @item Purpose: The unqualified @code{%code} or @code{%code requires} should
4655 usually be more appropriate than @code{%code top}.
4656 However, occasionally it is necessary to insert code much nearer the top of the
4657 parser source code file.
4658 For example:
4659
4660 @smallexample
4661 %code top @{
4662 #define _GNU_SOURCE
4663 #include <stdio.h>
4664 @}
4665 @end smallexample
4666
4667 @item Location(s): Near the top of the parser source code file.
4668 @end itemize
4669
4670 @item imports
4671 @findex %code imports
4672
4673 @itemize @bullet
4674 @item Language(s): Java
4675
4676 @item Purpose: This is the best place to write Java import directives.
4677
4678 @item Location(s): The parser Java file after any Java package directive and
4679 before any class definitions.
4680 @end itemize
4681 @end itemize
4682
4683 (Like all the Yacc prologue alternatives, this directive is experimental.
4684 More user feedback will help to determine whether it should become a permanent
4685 feature.)
4686
4687 @cindex Prologue
4688 For a detailed discussion of how to use @code{%code} in place of the
4689 traditional Yacc prologue for C/C++, see @ref{Prologue Alternatives}.
4690 @end deffn
4691
4692 @deffn {Directive} %debug
4693 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
4694 already defined, so that the debugging facilities are compiled.
4695 @end deffn
4696 @xref{Tracing, ,Tracing Your Parser}.
4697
4698 @deffn {Directive} %define @var{variable}
4699 @deffnx {Directive} %define @var{variable} "@var{value}"
4700 Define a variable to adjust Bison's behavior.
4701 The possible choices for @var{variable}, as well as their meanings, depend on
4702 the selected target language and/or the parser skeleton (@pxref{Decl
4703 Summary,,%language}).
4704
4705 Bison will warn if a @var{variable} is defined multiple times.
4706
4707 Omitting @code{"@var{value}"} is always equivalent to specifying it as
4708 @code{""}.
4709
4710 Some @var{variable}s may be used as booleans.
4711 In this case, Bison will complain if the variable definition does not meet one
4712 of the following four conditions:
4713
4714 @enumerate
4715 @item @code{"@var{value}"} is @code{"true"}
4716
4717 @item @code{"@var{value}"} is omitted (or is @code{""}).
4718 This is equivalent to @code{"true"}.
4719
4720 @item @code{"@var{value}"} is @code{"false"}.
4721
4722 @item @var{variable} is never defined.
4723 In this case, Bison selects a default value, which may depend on the selected
4724 target language and/or parser skeleton.
4725 @end enumerate
4726 @end deffn
4727
4728 @deffn {Directive} %defines
4729 Write a header file containing macro definitions for the token type
4730 names defined in the grammar as well as a few other declarations.
4731 If the parser output file is named @file{@var{name}.c} then this file
4732 is named @file{@var{name}.h}.
4733
4734 For C parsers, the output header declares @code{YYSTYPE} unless
4735 @code{YYSTYPE} is already defined as a macro or you have used a
4736 @code{<@var{type}>} tag without using @code{%union}.
4737 Therefore, if you are using a @code{%union}
4738 (@pxref{Multiple Types, ,More Than One Value Type}) with components that
4739 require other definitions, or if you have defined a @code{YYSTYPE} macro
4740 or type definition
4741 (@pxref{Value Type, ,Data Types of Semantic Values}), you need to
4742 arrange for these definitions to be propagated to all modules, e.g., by
4743 putting them in a prerequisite header that is included both by your
4744 parser and by any other module that needs @code{YYSTYPE}.
4745
4746 Unless your parser is pure, the output header declares @code{yylval}
4747 as an external variable. @xref{Pure Decl, ,A Pure (Reentrant)
4748 Parser}.
4749
4750 If you have also used locations, the output header declares
4751 @code{YYLTYPE} and @code{yylloc} using a protocol similar to that of
4752 the @code{YYSTYPE} macro and @code{yylval}. @xref{Locations, ,Tracking
4753 Locations}.
4754
4755 This output file is normally essential if you wish to put the definition
4756 of @code{yylex} in a separate source file, because @code{yylex}
4757 typically needs to be able to refer to the above-mentioned declarations
4758 and to the token type codes. @xref{Token Values, ,Semantic Values of
4759 Tokens}.
4760
4761 @findex %code requires
4762 @findex %code provides
4763 If you have declared @code{%code requires} or @code{%code provides}, the output
4764 header also contains their code.
4765 @xref{Decl Summary, ,%code}.
4766 @end deffn
4767
4768 @deffn {Directive} %defines @var{defines-file}
4769 Same as above, but save in the file @var{defines-file}.
4770 @end deffn
4771
4772 @deffn {Directive} %destructor
4773 Specify how the parser should reclaim the memory associated to
4774 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
4775 @end deffn
4776
4777 @deffn {Directive} %file-prefix "@var{prefix}"
4778 Specify a prefix to use for all Bison output file names. The names are
4779 chosen as if the input file were named @file{@var{prefix}.y}.
4780 @end deffn
4781
4782 @deffn {Directive} %language "@var{language}"
4783 Specify the programming language for the generated parser. Currently
4784 supported languages include C and C++.
4785 @var{language} is case-insensitive.
4786 @end deffn
4787
4788 @deffn {Directive} %locations
4789 Generate the code processing the locations (@pxref{Action Features,
4790 ,Special Features for Use in Actions}). This mode is enabled as soon as
4791 the grammar uses the special @samp{@@@var{n}} tokens, but if your
4792 grammar does not use it, using @samp{%locations} allows for more
4793 accurate syntax error messages.
4794 @end deffn
4795
4796 @deffn {Directive} %name-prefix "@var{prefix}"
4797 Rename the external symbols used in the parser so that they start with
4798 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
4799 in C parsers
4800 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
4801 @code{yylval}, @code{yychar}, @code{yydebug}, and
4802 (if locations are used) @code{yylloc}. For example, if you use
4803 @samp{%name-prefix "c_"}, the names become @code{c_parse}, @code{c_lex},
4804 and so on. In C++ parsers, it is only the surrounding namespace which is
4805 named @var{prefix} instead of @samp{yy}.
4806 @xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
4807 @end deffn
4808
4809 @ifset defaultprec
4810 @deffn {Directive} %no-default-prec
4811 Do not assign a precedence to rules lacking an explicit @code{%prec}
4812 modifier (@pxref{Contextual Precedence, ,Context-Dependent
4813 Precedence}).
4814 @end deffn
4815 @end ifset
4816
4817 @deffn {Directive} %no-lines
4818 Don't generate any @code{#line} preprocessor commands in the parser
4819 file. Ordinarily Bison writes these commands in the parser file so that
4820 the C compiler and debuggers will associate errors and object code with
4821 your source file (the grammar file). This directive causes them to
4822 associate errors with the parser file, treating it an independent source
4823 file in its own right.
4824 @end deffn
4825
4826 @deffn {Directive} %output "@var{file}"
4827 Specify @var{file} for the parser file.
4828 @end deffn
4829
4830 @deffn {Directive} %pure-parser
4831 Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure
4832 (Reentrant) Parser}).
4833 @end deffn
4834
4835 @deffn {Directive} %require "@var{version}"
4836 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
4837 Require a Version of Bison}.
4838 @end deffn
4839
4840 @deffn {Directive} %skeleton "@var{file}"
4841 Specify the skeleton to use.
4842
4843 You probably don't need this option unless you are developing Bison.
4844 You should use @code{%language} if you want to specify the skeleton for a
4845 different language, because it is clearer and because it will always choose the
4846 correct skeleton for non-deterministic or push parsers.
4847
4848 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
4849 file in the Bison installation directory.
4850 If it does, @var{file} is an absolute file name or a file name relative to the
4851 directory of the grammar file.
4852 This is similar to how most shells resolve commands.
4853 @end deffn
4854
4855 @deffn {Directive} %token-table
4856 Generate an array of token names in the parser file. The name of the
4857 array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
4858 token whose internal Bison token code number is @var{i}. The first
4859 three elements of @code{yytname} correspond to the predefined tokens
4860 @code{"$end"},
4861 @code{"error"}, and @code{"$undefined"}; after these come the symbols
4862 defined in the grammar file.
4863
4864 The name in the table includes all the characters needed to represent
4865 the token in Bison. For single-character literals and literal
4866 strings, this includes the surrounding quoting characters and any
4867 escape sequences. For example, the Bison single-character literal
4868 @code{'+'} corresponds to a three-character name, represented in C as
4869 @code{"'+'"}; and the Bison two-character literal string @code{"\\/"}
4870 corresponds to a five-character name, represented in C as
4871 @code{"\"\\\\/\""}.
4872
4873 When you specify @code{%token-table}, Bison also generates macro
4874 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
4875 @code{YYNRULES}, and @code{YYNSTATES}:
4876
4877 @table @code
4878 @item YYNTOKENS
4879 The highest token number, plus one.
4880 @item YYNNTS
4881 The number of nonterminal symbols.
4882 @item YYNRULES
4883 The number of grammar rules,
4884 @item YYNSTATES
4885 The number of parser states (@pxref{Parser States}).
4886 @end table
4887 @end deffn
4888
4889 @deffn {Directive} %verbose
4890 Write an extra output file containing verbose descriptions of the
4891 parser states and what is done for each type of lookahead token in
4892 that state. @xref{Understanding, , Understanding Your Parser}, for more
4893 information.
4894 @end deffn
4895
4896 @deffn {Directive} %yacc
4897 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
4898 including its naming conventions. @xref{Bison Options}, for more.
4899 @end deffn
4900
4901
4902 @node Multiple Parsers
4903 @section Multiple Parsers in the Same Program
4904
4905 Most programs that use Bison parse only one language and therefore contain
4906 only one Bison parser. But what if you want to parse more than one
4907 language with the same program? Then you need to avoid a name conflict
4908 between different definitions of @code{yyparse}, @code{yylval}, and so on.
4909
4910 The easy way to do this is to use the option @samp{-p @var{prefix}}
4911 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
4912 functions and variables of the Bison parser to start with @var{prefix}
4913 instead of @samp{yy}. You can use this to give each parser distinct
4914 names that do not conflict.
4915
4916 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
4917 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
4918 @code{yychar} and @code{yydebug}. For example, if you use @samp{-p c},
4919 the names become @code{cparse}, @code{clex}, and so on.
4920
4921 @strong{All the other variables and macros associated with Bison are not
4922 renamed.} These others are not global; there is no conflict if the same
4923 name is used in different parsers. For example, @code{YYSTYPE} is not
4924 renamed, but defining this in different ways in different parsers causes
4925 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
4926
4927 The @samp{-p} option works by adding macro definitions to the beginning
4928 of the parser source file, defining @code{yyparse} as
4929 @code{@var{prefix}parse}, and so on. This effectively substitutes one
4930 name for the other in the entire parser file.
4931
4932 @node Interface
4933 @chapter Parser C-Language Interface
4934 @cindex C-language interface
4935 @cindex interface
4936
4937 The Bison parser is actually a C function named @code{yyparse}. Here we
4938 describe the interface conventions of @code{yyparse} and the other
4939 functions that it needs to use.
4940
4941 Keep in mind that the parser uses many C identifiers starting with
4942 @samp{yy} and @samp{YY} for internal purposes. If you use such an
4943 identifier (aside from those in this manual) in an action or in epilogue
4944 in the grammar file, you are likely to run into trouble.
4945
4946 @menu
4947 * Parser Function:: How to call @code{yyparse} and what it returns.
4948 * Lexical:: You must supply a function @code{yylex}
4949 which reads tokens.
4950 * Error Reporting:: You must supply a function @code{yyerror}.
4951 * Action Features:: Special features for use in actions.
4952 * Internationalization:: How to let the parser speak in the user's
4953 native language.
4954 @end menu
4955
4956 @node Parser Function
4957 @section The Parser Function @code{yyparse}
4958 @findex yyparse
4959
4960 You call the function @code{yyparse} to cause parsing to occur. This
4961 function reads tokens, executes actions, and ultimately returns when it
4962 encounters end-of-input or an unrecoverable syntax error. You can also
4963 write an action which directs @code{yyparse} to return immediately
4964 without reading further.
4965
4966
4967 @deftypefun int yyparse (void)
4968 The value returned by @code{yyparse} is 0 if parsing was successful (return
4969 is due to end-of-input).
4970
4971 The value is 1 if parsing failed because of invalid input, i.e., input
4972 that contains a syntax error or that causes @code{YYABORT} to be
4973 invoked.
4974
4975 The value is 2 if parsing failed due to memory exhaustion.
4976 @end deftypefun
4977
4978 In an action, you can cause immediate return from @code{yyparse} by using
4979 these macros:
4980
4981 @defmac YYACCEPT
4982 @findex YYACCEPT
4983 Return immediately with value 0 (to report success).
4984 @end defmac
4985
4986 @defmac YYABORT
4987 @findex YYABORT
4988 Return immediately with value 1 (to report failure).
4989 @end defmac
4990
4991 If you use a reentrant parser, you can optionally pass additional
4992 parameter information to it in a reentrant way. To do so, use the
4993 declaration @code{%parse-param}:
4994
4995 @deffn {Directive} %parse-param @{@var{argument-declaration}@}
4996 @findex %parse-param
4997 Declare that an argument declared by the braced-code
4998 @var{argument-declaration} is an additional @code{yyparse} argument.
4999 The @var{argument-declaration} is used when declaring
5000 functions or prototypes. The last identifier in
5001 @var{argument-declaration} must be the argument name.
5002 @end deffn
5003
5004 Here's an example. Write this in the parser:
5005
5006 @example
5007 %parse-param @{int *nastiness@}
5008 %parse-param @{int *randomness@}
5009 @end example
5010
5011 @noindent
5012 Then call the parser like this:
5013
5014 @example
5015 @{
5016 int nastiness, randomness;
5017 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
5018 value = yyparse (&nastiness, &randomness);
5019 @dots{}
5020 @}
5021 @end example
5022
5023 @noindent
5024 In the grammar actions, use expressions like this to refer to the data:
5025
5026 @example
5027 exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
5028 @end example
5029
5030
5031 @node Lexical
5032 @section The Lexical Analyzer Function @code{yylex}
5033 @findex yylex
5034 @cindex lexical analyzer
5035
5036 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
5037 the input stream and returns them to the parser. Bison does not create
5038 this function automatically; you must write it so that @code{yyparse} can
5039 call it. The function is sometimes referred to as a lexical scanner.
5040
5041 In simple programs, @code{yylex} is often defined at the end of the Bison
5042 grammar file. If @code{yylex} is defined in a separate source file, you
5043 need to arrange for the token-type macro definitions to be available there.
5044 To do this, use the @samp{-d} option when you run Bison, so that it will
5045 write these macro definitions into a separate header file
5046 @file{@var{name}.tab.h} which you can include in the other source files
5047 that need it. @xref{Invocation, ,Invoking Bison}.
5048
5049 @menu
5050 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
5051 * Token Values:: How @code{yylex} must return the semantic value
5052 of the token it has read.
5053 * Token Locations:: How @code{yylex} must return the text location
5054 (line number, etc.) of the token, if the
5055 actions want that.
5056 * Pure Calling:: How the calling convention differs
5057 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
5058 @end menu
5059
5060 @node Calling Convention
5061 @subsection Calling Convention for @code{yylex}
5062
5063 The value that @code{yylex} returns must be the positive numeric code
5064 for the type of token it has just found; a zero or negative value
5065 signifies end-of-input.
5066
5067 When a token is referred to in the grammar rules by a name, that name
5068 in the parser file becomes a C macro whose definition is the proper
5069 numeric code for that token type. So @code{yylex} can use the name
5070 to indicate that type. @xref{Symbols}.
5071
5072 When a token is referred to in the grammar rules by a character literal,
5073 the numeric code for that character is also the code for the token type.
5074 So @code{yylex} can simply return that character code, possibly converted
5075 to @code{unsigned char} to avoid sign-extension. The null character
5076 must not be used this way, because its code is zero and that
5077 signifies end-of-input.
5078
5079 Here is an example showing these things:
5080
5081 @example
5082 int
5083 yylex (void)
5084 @{
5085 @dots{}
5086 if (c == EOF) /* Detect end-of-input. */
5087 return 0;
5088 @dots{}
5089 if (c == '+' || c == '-')
5090 return c; /* Assume token type for `+' is '+'. */
5091 @dots{}
5092 return INT; /* Return the type of the token. */
5093 @dots{}
5094 @}
5095 @end example
5096
5097 @noindent
5098 This interface has been designed so that the output from the @code{lex}
5099 utility can be used without change as the definition of @code{yylex}.
5100
5101 If the grammar uses literal string tokens, there are two ways that
5102 @code{yylex} can determine the token type codes for them:
5103
5104 @itemize @bullet
5105 @item
5106 If the grammar defines symbolic token names as aliases for the
5107 literal string tokens, @code{yylex} can use these symbolic names like
5108 all others. In this case, the use of the literal string tokens in
5109 the grammar file has no effect on @code{yylex}.
5110
5111 @item
5112 @code{yylex} can find the multicharacter token in the @code{yytname}
5113 table. The index of the token in the table is the token type's code.
5114 The name of a multicharacter token is recorded in @code{yytname} with a
5115 double-quote, the token's characters, and another double-quote. The
5116 token's characters are escaped as necessary to be suitable as input
5117 to Bison.
5118
5119 Here's code for looking up a multicharacter token in @code{yytname},
5120 assuming that the characters of the token are stored in
5121 @code{token_buffer}, and assuming that the token does not contain any
5122 characters like @samp{"} that require escaping.
5123
5124 @smallexample
5125 for (i = 0; i < YYNTOKENS; i++)
5126 @{
5127 if (yytname[i] != 0
5128 && yytname[i][0] == '"'
5129 && ! strncmp (yytname[i] + 1, token_buffer,
5130 strlen (token_buffer))
5131 && yytname[i][strlen (token_buffer) + 1] == '"'
5132 && yytname[i][strlen (token_buffer) + 2] == 0)
5133 break;
5134 @}
5135 @end smallexample
5136
5137 The @code{yytname} table is generated only if you use the
5138 @code{%token-table} declaration. @xref{Decl Summary}.
5139 @end itemize
5140
5141 @node Token Values
5142 @subsection Semantic Values of Tokens
5143
5144 @vindex yylval
5145 In an ordinary (nonreentrant) parser, the semantic value of the token must
5146 be stored into the global variable @code{yylval}. When you are using
5147 just one data type for semantic values, @code{yylval} has that type.
5148 Thus, if the type is @code{int} (the default), you might write this in
5149 @code{yylex}:
5150
5151 @example
5152 @group
5153 @dots{}
5154 yylval = value; /* Put value onto Bison stack. */
5155 return INT; /* Return the type of the token. */
5156 @dots{}
5157 @end group
5158 @end example
5159
5160 When you are using multiple data types, @code{yylval}'s type is a union
5161 made from the @code{%union} declaration (@pxref{Union Decl, ,The
5162 Collection of Value Types}). So when you store a token's value, you
5163 must use the proper member of the union. If the @code{%union}
5164 declaration looks like this:
5165
5166 @example
5167 @group
5168 %union @{
5169 int intval;
5170 double val;
5171 symrec *tptr;
5172 @}
5173 @end group
5174 @end example
5175
5176 @noindent
5177 then the code in @code{yylex} might look like this:
5178
5179 @example
5180 @group
5181 @dots{}
5182 yylval.intval = value; /* Put value onto Bison stack. */
5183 return INT; /* Return the type of the token. */
5184 @dots{}
5185 @end group
5186 @end example
5187
5188 @node Token Locations
5189 @subsection Textual Locations of Tokens
5190
5191 @vindex yylloc
5192 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
5193 Tracking Locations}) in actions to keep track of the textual locations
5194 of tokens and groupings, then you must provide this information in
5195 @code{yylex}. The function @code{yyparse} expects to find the textual
5196 location of a token just parsed in the global variable @code{yylloc}.
5197 So @code{yylex} must store the proper data in that variable.
5198
5199 By default, the value of @code{yylloc} is a structure and you need only
5200 initialize the members that are going to be used by the actions. The
5201 four members are called @code{first_line}, @code{first_column},
5202 @code{last_line} and @code{last_column}. Note that the use of this
5203 feature makes the parser noticeably slower.
5204
5205 @tindex YYLTYPE
5206 The data type of @code{yylloc} has the name @code{YYLTYPE}.
5207
5208 @node Pure Calling
5209 @subsection Calling Conventions for Pure Parsers
5210
5211 When you use the Bison declaration @code{%pure-parser} to request a
5212 pure, reentrant parser, the global communication variables @code{yylval}
5213 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
5214 Parser}.) In such parsers the two global variables are replaced by
5215 pointers passed as arguments to @code{yylex}. You must declare them as
5216 shown here, and pass the information back by storing it through those
5217 pointers.
5218
5219 @example
5220 int
5221 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
5222 @{
5223 @dots{}
5224 *lvalp = value; /* Put value onto Bison stack. */
5225 return INT; /* Return the type of the token. */
5226 @dots{}
5227 @}
5228 @end example
5229
5230 If the grammar file does not use the @samp{@@} constructs to refer to
5231 textual locations, then the type @code{YYLTYPE} will not be defined. In
5232 this case, omit the second argument; @code{yylex} will be called with
5233 only one argument.
5234
5235
5236 If you wish to pass the additional parameter data to @code{yylex}, use
5237 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
5238 Function}).
5239
5240 @deffn {Directive} lex-param @{@var{argument-declaration}@}
5241 @findex %lex-param
5242 Declare that the braced-code @var{argument-declaration} is an
5243 additional @code{yylex} argument declaration.
5244 @end deffn
5245
5246 For instance:
5247
5248 @example
5249 %parse-param @{int *nastiness@}
5250 %lex-param @{int *nastiness@}
5251 %parse-param @{int *randomness@}
5252 @end example
5253
5254 @noindent
5255 results in the following signature:
5256
5257 @example
5258 int yylex (int *nastiness);
5259 int yyparse (int *nastiness, int *randomness);
5260 @end example
5261
5262 If @code{%pure-parser} is added:
5263
5264 @example
5265 int yylex (YYSTYPE *lvalp, int *nastiness);
5266 int yyparse (int *nastiness, int *randomness);
5267 @end example
5268
5269 @noindent
5270 and finally, if both @code{%pure-parser} and @code{%locations} are used:
5271
5272 @example
5273 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
5274 int yyparse (int *nastiness, int *randomness);
5275 @end example
5276
5277 @node Error Reporting
5278 @section The Error Reporting Function @code{yyerror}
5279 @cindex error reporting function
5280 @findex yyerror
5281 @cindex parse error
5282 @cindex syntax error
5283
5284 The Bison parser detects a @dfn{syntax error} or @dfn{parse error}
5285 whenever it reads a token which cannot satisfy any syntax rule. An
5286 action in the grammar can also explicitly proclaim an error, using the
5287 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
5288 in Actions}).
5289
5290 The Bison parser expects to report the error by calling an error
5291 reporting function named @code{yyerror}, which you must supply. It is
5292 called by @code{yyparse} whenever a syntax error is found, and it
5293 receives one argument. For a syntax error, the string is normally
5294 @w{@code{"syntax error"}}.
5295
5296 @findex %error-verbose
5297 If you invoke the directive @code{%error-verbose} in the Bison
5298 declarations section (@pxref{Bison Declarations, ,The Bison Declarations
5299 Section}), then Bison provides a more verbose and specific error message
5300 string instead of just plain @w{@code{"syntax error"}}.
5301
5302 The parser can detect one other kind of error: memory exhaustion. This
5303 can happen when the input contains constructions that are very deeply
5304 nested. It isn't likely you will encounter this, since the Bison
5305 parser normally extends its stack automatically up to a very large limit. But
5306 if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
5307 fashion, except that the argument string is @w{@code{"memory exhausted"}}.
5308
5309 In some cases diagnostics like @w{@code{"syntax error"}} are
5310 translated automatically from English to some other language before
5311 they are passed to @code{yyerror}. @xref{Internationalization}.
5312
5313 The following definition suffices in simple programs:
5314
5315 @example
5316 @group
5317 void
5318 yyerror (char const *s)
5319 @{
5320 @end group
5321 @group
5322 fprintf (stderr, "%s\n", s);
5323 @}
5324 @end group
5325 @end example
5326
5327 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
5328 error recovery if you have written suitable error recovery grammar rules
5329 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
5330 immediately return 1.
5331
5332 Obviously, in location tracking pure parsers, @code{yyerror} should have
5333 an access to the current location.
5334 This is indeed the case for the @acronym{GLR}
5335 parsers, but not for the Yacc parser, for historical reasons. I.e., if
5336 @samp{%locations %pure-parser} is passed then the prototypes for
5337 @code{yyerror} are:
5338
5339 @example
5340 void yyerror (char const *msg); /* Yacc parsers. */
5341 void yyerror (YYLTYPE *locp, char const *msg); /* GLR parsers. */
5342 @end example
5343
5344 If @samp{%parse-param @{int *nastiness@}} is used, then:
5345
5346 @example
5347 void yyerror (int *nastiness, char const *msg); /* Yacc parsers. */
5348 void yyerror (int *nastiness, char const *msg); /* GLR parsers. */
5349 @end example
5350
5351 Finally, @acronym{GLR} and Yacc parsers share the same @code{yyerror} calling
5352 convention for absolutely pure parsers, i.e., when the calling
5353 convention of @code{yylex} @emph{and} the calling convention of
5354 @code{%pure-parser} are pure. I.e.:
5355
5356 @example
5357 /* Location tracking. */
5358 %locations
5359 /* Pure yylex. */
5360 %pure-parser
5361 %lex-param @{int *nastiness@}
5362 /* Pure yyparse. */
5363 %parse-param @{int *nastiness@}
5364 %parse-param @{int *randomness@}
5365 @end example
5366
5367 @noindent
5368 results in the following signatures for all the parser kinds:
5369
5370 @example
5371 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
5372 int yyparse (int *nastiness, int *randomness);
5373 void yyerror (YYLTYPE *locp,
5374 int *nastiness, int *randomness,
5375 char const *msg);
5376 @end example
5377
5378 @noindent
5379 The prototypes are only indications of how the code produced by Bison
5380 uses @code{yyerror}. Bison-generated code always ignores the returned
5381 value, so @code{yyerror} can return any type, including @code{void}.
5382 Also, @code{yyerror} can be a variadic function; that is why the
5383 message is always passed last.
5384
5385 Traditionally @code{yyerror} returns an @code{int} that is always
5386 ignored, but this is purely for historical reasons, and @code{void} is
5387 preferable since it more accurately describes the return type for
5388 @code{yyerror}.
5389
5390 @vindex yynerrs
5391 The variable @code{yynerrs} contains the number of syntax errors
5392 reported so far. Normally this variable is global; but if you
5393 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
5394 then it is a local variable which only the actions can access.
5395
5396 @node Action Features
5397 @section Special Features for Use in Actions
5398 @cindex summary, action features
5399 @cindex action features summary
5400
5401 Here is a table of Bison constructs, variables and macros that
5402 are useful in actions.
5403
5404 @deffn {Variable} $$
5405 Acts like a variable that contains the semantic value for the
5406 grouping made by the current rule. @xref{Actions}.
5407 @end deffn
5408
5409 @deffn {Variable} $@var{n}
5410 Acts like a variable that contains the semantic value for the
5411 @var{n}th component of the current rule. @xref{Actions}.
5412 @end deffn
5413
5414 @deffn {Variable} $<@var{typealt}>$
5415 Like @code{$$} but specifies alternative @var{typealt} in the union
5416 specified by the @code{%union} declaration. @xref{Action Types, ,Data
5417 Types of Values in Actions}.
5418 @end deffn
5419
5420 @deffn {Variable} $<@var{typealt}>@var{n}
5421 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
5422 union specified by the @code{%union} declaration.
5423 @xref{Action Types, ,Data Types of Values in Actions}.
5424 @end deffn
5425
5426 @deffn {Macro} YYABORT;
5427 Return immediately from @code{yyparse}, indicating failure.
5428 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
5429 @end deffn
5430
5431 @deffn {Macro} YYACCEPT;
5432 Return immediately from @code{yyparse}, indicating success.
5433 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
5434 @end deffn
5435
5436 @deffn {Macro} YYBACKUP (@var{token}, @var{value});
5437 @findex YYBACKUP
5438 Unshift a token. This macro is allowed only for rules that reduce
5439 a single value, and only when there is no lookahead token.
5440 It is also disallowed in @acronym{GLR} parsers.
5441 It installs a lookahead token with token type @var{token} and
5442 semantic value @var{value}; then it discards the value that was
5443 going to be reduced by this rule.
5444
5445 If the macro is used when it is not valid, such as when there is
5446 a lookahead token already, then it reports a syntax error with
5447 a message @samp{cannot back up} and performs ordinary error
5448 recovery.
5449
5450 In either case, the rest of the action is not executed.
5451 @end deffn
5452
5453 @deffn {Macro} YYEMPTY
5454 @vindex YYEMPTY
5455 Value stored in @code{yychar} when there is no lookahead token.
5456 @end deffn
5457
5458 @deffn {Macro} YYEOF
5459 @vindex YYEOF
5460 Value stored in @code{yychar} when the lookahead is the end of the input
5461 stream.
5462 @end deffn
5463
5464 @deffn {Macro} YYERROR;
5465 @findex YYERROR
5466 Cause an immediate syntax error. This statement initiates error
5467 recovery just as if the parser itself had detected an error; however, it
5468 does not call @code{yyerror}, and does not print any message. If you
5469 want to print an error message, call @code{yyerror} explicitly before
5470 the @samp{YYERROR;} statement. @xref{Error Recovery}.
5471 @end deffn
5472
5473 @deffn {Macro} YYRECOVERING
5474 @findex YYRECOVERING
5475 The expression @code{YYRECOVERING ()} yields 1 when the parser
5476 is recovering from a syntax error, and 0 otherwise.
5477 @xref{Error Recovery}.
5478 @end deffn
5479
5480 @deffn {Variable} yychar
5481 Variable containing either the lookahead token, or @code{YYEOF} when the
5482 lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
5483 has been performed so the next token is not yet known.
5484 Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
5485 Actions}).
5486 @xref{Lookahead, ,Lookahead Tokens}.
5487 @end deffn
5488
5489 @deffn {Macro} yyclearin;
5490 Discard the current lookahead token. This is useful primarily in
5491 error rules.
5492 Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
5493 Semantic Actions}).
5494 @xref{Error Recovery}.
5495 @end deffn
5496
5497 @deffn {Macro} yyerrok;
5498 Resume generating error messages immediately for subsequent syntax
5499 errors. This is useful primarily in error rules.
5500 @xref{Error Recovery}.
5501 @end deffn
5502
5503 @deffn {Variable} yylloc
5504 Variable containing the lookahead token location when @code{yychar} is not set
5505 to @code{YYEMPTY} or @code{YYEOF}.
5506 Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
5507 Actions}).
5508 @xref{Actions and Locations, ,Actions and Locations}.
5509 @end deffn
5510
5511 @deffn {Variable} yylval
5512 Variable containing the lookahead token semantic value when @code{yychar} is
5513 not set to @code{YYEMPTY} or @code{YYEOF}.
5514 Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
5515 Actions}).
5516 @xref{Actions, ,Actions}.
5517 @end deffn
5518
5519 @deffn {Value} @@$
5520 @findex @@$
5521 Acts like a structure variable containing information on the textual location
5522 of the grouping made by the current rule. @xref{Locations, ,
5523 Tracking Locations}.
5524
5525 @c Check if those paragraphs are still useful or not.
5526
5527 @c @example
5528 @c struct @{
5529 @c int first_line, last_line;
5530 @c int first_column, last_column;
5531 @c @};
5532 @c @end example
5533
5534 @c Thus, to get the starting line number of the third component, you would
5535 @c use @samp{@@3.first_line}.
5536
5537 @c In order for the members of this structure to contain valid information,
5538 @c you must make @code{yylex} supply this information about each token.
5539 @c If you need only certain members, then @code{yylex} need only fill in
5540 @c those members.
5541
5542 @c The use of this feature makes the parser noticeably slower.
5543 @end deffn
5544
5545 @deffn {Value} @@@var{n}
5546 @findex @@@var{n}
5547 Acts like a structure variable containing information on the textual location
5548 of the @var{n}th component of the current rule. @xref{Locations, ,
5549 Tracking Locations}.
5550 @end deffn
5551
5552 @node Internationalization
5553 @section Parser Internationalization
5554 @cindex internationalization
5555 @cindex i18n
5556 @cindex NLS
5557 @cindex gettext
5558 @cindex bison-po
5559
5560 A Bison-generated parser can print diagnostics, including error and
5561 tracing messages. By default, they appear in English. However, Bison
5562 also supports outputting diagnostics in the user's native language. To
5563 make this work, the user should set the usual environment variables.
5564 @xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
5565 For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
5566 set the user's locale to French Canadian using the @acronym{UTF}-8
5567 encoding. The exact set of available locales depends on the user's
5568 installation.
5569
5570 The maintainer of a package that uses a Bison-generated parser enables
5571 the internationalization of the parser's output through the following
5572 steps. Here we assume a package that uses @acronym{GNU} Autoconf and
5573 @acronym{GNU} Automake.
5574
5575 @enumerate
5576 @item
5577 @cindex bison-i18n.m4
5578 Into the directory containing the @acronym{GNU} Autoconf macros used
5579 by the package---often called @file{m4}---copy the
5580 @file{bison-i18n.m4} file installed by Bison under
5581 @samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
5582 For example:
5583
5584 @example
5585 cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
5586 @end example
5587
5588 @item
5589 @findex BISON_I18N
5590 @vindex BISON_LOCALEDIR
5591 @vindex YYENABLE_NLS
5592 In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
5593 invocation, add an invocation of @code{BISON_I18N}. This macro is
5594 defined in the file @file{bison-i18n.m4} that you copied earlier. It
5595 causes @samp{configure} to find the value of the
5596 @code{BISON_LOCALEDIR} variable, and it defines the source-language
5597 symbol @code{YYENABLE_NLS} to enable translations in the
5598 Bison-generated parser.
5599
5600 @item
5601 In the @code{main} function of your program, designate the directory
5602 containing Bison's runtime message catalog, through a call to
5603 @samp{bindtextdomain} with domain name @samp{bison-runtime}.
5604 For example:
5605
5606 @example
5607 bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
5608 @end example
5609
5610 Typically this appears after any other call @code{bindtextdomain
5611 (PACKAGE, LOCALEDIR)} that your package already has. Here we rely on
5612 @samp{BISON_LOCALEDIR} to be defined as a string through the
5613 @file{Makefile}.
5614
5615 @item
5616 In the @file{Makefile.am} that controls the compilation of the @code{main}
5617 function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
5618 either in @samp{DEFS} or in @samp{AM_CPPFLAGS}. For example:
5619
5620 @example
5621 DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
5622 @end example
5623
5624 or:
5625
5626 @example
5627 AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
5628 @end example
5629
5630 @item
5631 Finally, invoke the command @command{autoreconf} to generate the build
5632 infrastructure.
5633 @end enumerate
5634
5635
5636 @node Algorithm
5637 @chapter The Bison Parser Algorithm
5638 @cindex Bison parser algorithm
5639 @cindex algorithm of parser
5640 @cindex shifting
5641 @cindex reduction
5642 @cindex parser stack
5643 @cindex stack, parser
5644
5645 As Bison reads tokens, it pushes them onto a stack along with their
5646 semantic values. The stack is called the @dfn{parser stack}. Pushing a
5647 token is traditionally called @dfn{shifting}.
5648
5649 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
5650 @samp{3} to come. The stack will have four elements, one for each token
5651 that was shifted.
5652
5653 But the stack does not always have an element for each token read. When
5654 the last @var{n} tokens and groupings shifted match the components of a
5655 grammar rule, they can be combined according to that rule. This is called
5656 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
5657 single grouping whose symbol is the result (left hand side) of that rule.
5658 Running the rule's action is part of the process of reduction, because this
5659 is what computes the semantic value of the resulting grouping.
5660
5661 For example, if the infix calculator's parser stack contains this:
5662
5663 @example
5664 1 + 5 * 3
5665 @end example
5666
5667 @noindent
5668 and the next input token is a newline character, then the last three
5669 elements can be reduced to 15 via the rule:
5670
5671 @example
5672 expr: expr '*' expr;
5673 @end example
5674
5675 @noindent
5676 Then the stack contains just these three elements:
5677
5678 @example
5679 1 + 15
5680 @end example
5681
5682 @noindent
5683 At this point, another reduction can be made, resulting in the single value
5684 16. Then the newline token can be shifted.
5685
5686 The parser tries, by shifts and reductions, to reduce the entire input down
5687 to a single grouping whose symbol is the grammar's start-symbol
5688 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
5689
5690 This kind of parser is known in the literature as a bottom-up parser.
5691
5692 @menu
5693 * Lookahead:: Parser looks one token ahead when deciding what to do.
5694 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
5695 * Precedence:: Operator precedence works by resolving conflicts.
5696 * Contextual Precedence:: When an operator's precedence depends on context.
5697 * Parser States:: The parser is a finite-state-machine with stack.
5698 * Reduce/Reduce:: When two rules are applicable in the same situation.
5699 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
5700 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
5701 * Memory Management:: What happens when memory is exhausted. How to avoid it.
5702 @end menu
5703
5704 @node Lookahead
5705 @section Lookahead Tokens
5706 @cindex lookahead token
5707
5708 The Bison parser does @emph{not} always reduce immediately as soon as the
5709 last @var{n} tokens and groupings match a rule. This is because such a
5710 simple strategy is inadequate to handle most languages. Instead, when a
5711 reduction is possible, the parser sometimes ``looks ahead'' at the next
5712 token in order to decide what to do.
5713
5714 When a token is read, it is not immediately shifted; first it becomes the
5715 @dfn{lookahead token}, which is not on the stack. Now the parser can
5716 perform one or more reductions of tokens and groupings on the stack, while
5717 the lookahead token remains off to the side. When no more reductions
5718 should take place, the lookahead token is shifted onto the stack. This
5719 does not mean that all possible reductions have been done; depending on the
5720 token type of the lookahead token, some rules may choose to delay their
5721 application.
5722
5723 Here is a simple case where lookahead is needed. These three rules define
5724 expressions which contain binary addition operators and postfix unary
5725 factorial operators (@samp{!}), and allow parentheses for grouping.
5726
5727 @example
5728 @group
5729 expr: term '+' expr
5730 | term
5731 ;
5732 @end group
5733
5734 @group
5735 term: '(' expr ')'
5736 | term '!'
5737 | NUMBER
5738 ;
5739 @end group
5740 @end example
5741
5742 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
5743 should be done? If the following token is @samp{)}, then the first three
5744 tokens must be reduced to form an @code{expr}. This is the only valid
5745 course, because shifting the @samp{)} would produce a sequence of symbols
5746 @w{@code{term ')'}}, and no rule allows this.
5747
5748 If the following token is @samp{!}, then it must be shifted immediately so
5749 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
5750 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
5751 @code{expr}. It would then be impossible to shift the @samp{!} because
5752 doing so would produce on the stack the sequence of symbols @code{expr
5753 '!'}. No rule allows that sequence.
5754
5755 @vindex yychar
5756 @vindex yylval
5757 @vindex yylloc
5758 The lookahead token is stored in the variable @code{yychar}.
5759 Its semantic value and location, if any, are stored in the variables
5760 @code{yylval} and @code{yylloc}.
5761 @xref{Action Features, ,Special Features for Use in Actions}.
5762
5763 @node Shift/Reduce
5764 @section Shift/Reduce Conflicts
5765 @cindex conflicts
5766 @cindex shift/reduce conflicts
5767 @cindex dangling @code{else}
5768 @cindex @code{else}, dangling
5769
5770 Suppose we are parsing a language which has if-then and if-then-else
5771 statements, with a pair of rules like this:
5772
5773 @example
5774 @group
5775 if_stmt:
5776 IF expr THEN stmt
5777 | IF expr THEN stmt ELSE stmt
5778 ;
5779 @end group
5780 @end example
5781
5782 @noindent
5783 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
5784 terminal symbols for specific keyword tokens.
5785
5786 When the @code{ELSE} token is read and becomes the lookahead token, the
5787 contents of the stack (assuming the input is valid) are just right for
5788 reduction by the first rule. But it is also legitimate to shift the
5789 @code{ELSE}, because that would lead to eventual reduction by the second
5790 rule.
5791
5792 This situation, where either a shift or a reduction would be valid, is
5793 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
5794 these conflicts by choosing to shift, unless otherwise directed by
5795 operator precedence declarations. To see the reason for this, let's
5796 contrast it with the other alternative.
5797
5798 Since the parser prefers to shift the @code{ELSE}, the result is to attach
5799 the else-clause to the innermost if-statement, making these two inputs
5800 equivalent:
5801
5802 @example
5803 if x then if y then win (); else lose;
5804
5805 if x then do; if y then win (); else lose; end;
5806 @end example
5807
5808 But if the parser chose to reduce when possible rather than shift, the
5809 result would be to attach the else-clause to the outermost if-statement,
5810 making these two inputs equivalent:
5811
5812 @example
5813 if x then if y then win (); else lose;
5814
5815 if x then do; if y then win (); end; else lose;
5816 @end example
5817
5818 The conflict exists because the grammar as written is ambiguous: either
5819 parsing of the simple nested if-statement is legitimate. The established
5820 convention is that these ambiguities are resolved by attaching the
5821 else-clause to the innermost if-statement; this is what Bison accomplishes
5822 by choosing to shift rather than reduce. (It would ideally be cleaner to
5823 write an unambiguous grammar, but that is very hard to do in this case.)
5824 This particular ambiguity was first encountered in the specifications of
5825 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
5826
5827 To avoid warnings from Bison about predictable, legitimate shift/reduce
5828 conflicts, use the @code{%expect @var{n}} declaration. There will be no
5829 warning as long as the number of shift/reduce conflicts is exactly @var{n}.
5830 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
5831
5832 The definition of @code{if_stmt} above is solely to blame for the
5833 conflict, but the conflict does not actually appear without additional
5834 rules. Here is a complete Bison input file that actually manifests the
5835 conflict:
5836
5837 @example
5838 @group
5839 %token IF THEN ELSE variable
5840 %%
5841 @end group
5842 @group
5843 stmt: expr
5844 | if_stmt
5845 ;
5846 @end group
5847
5848 @group
5849 if_stmt:
5850 IF expr THEN stmt
5851 | IF expr THEN stmt ELSE stmt
5852 ;
5853 @end group
5854
5855 expr: variable
5856 ;
5857 @end example
5858
5859 @node Precedence
5860 @section Operator Precedence
5861 @cindex operator precedence
5862 @cindex precedence of operators
5863
5864 Another situation where shift/reduce conflicts appear is in arithmetic
5865 expressions. Here shifting is not always the preferred resolution; the
5866 Bison declarations for operator precedence allow you to specify when to
5867 shift and when to reduce.
5868
5869 @menu
5870 * Why Precedence:: An example showing why precedence is needed.
5871 * Using Precedence:: How to specify precedence in Bison grammars.
5872 * Precedence Examples:: How these features are used in the previous example.
5873 * How Precedence:: How they work.
5874 @end menu
5875
5876 @node Why Precedence
5877 @subsection When Precedence is Needed
5878
5879 Consider the following ambiguous grammar fragment (ambiguous because the
5880 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
5881
5882 @example
5883 @group
5884 expr: expr '-' expr
5885 | expr '*' expr
5886 | expr '<' expr
5887 | '(' expr ')'
5888 @dots{}
5889 ;
5890 @end group
5891 @end example
5892
5893 @noindent
5894 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
5895 should it reduce them via the rule for the subtraction operator? It
5896 depends on the next token. Of course, if the next token is @samp{)}, we
5897 must reduce; shifting is invalid because no single rule can reduce the
5898 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
5899 the next token is @samp{*} or @samp{<}, we have a choice: either
5900 shifting or reduction would allow the parse to complete, but with
5901 different results.
5902
5903 To decide which one Bison should do, we must consider the results. If
5904 the next operator token @var{op} is shifted, then it must be reduced
5905 first in order to permit another opportunity to reduce the difference.
5906 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
5907 hand, if the subtraction is reduced before shifting @var{op}, the result
5908 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
5909 reduce should depend on the relative precedence of the operators
5910 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
5911 @samp{<}.
5912
5913 @cindex associativity
5914 What about input such as @w{@samp{1 - 2 - 5}}; should this be
5915 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
5916 operators we prefer the former, which is called @dfn{left association}.
5917 The latter alternative, @dfn{right association}, is desirable for
5918 assignment operators. The choice of left or right association is a
5919 matter of whether the parser chooses to shift or reduce when the stack
5920 contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
5921 makes right-associativity.
5922
5923 @node Using Precedence
5924 @subsection Specifying Operator Precedence
5925 @findex %left
5926 @findex %right
5927 @findex %nonassoc
5928
5929 Bison allows you to specify these choices with the operator precedence
5930 declarations @code{%left} and @code{%right}. Each such declaration
5931 contains a list of tokens, which are operators whose precedence and
5932 associativity is being declared. The @code{%left} declaration makes all
5933 those operators left-associative and the @code{%right} declaration makes
5934 them right-associative. A third alternative is @code{%nonassoc}, which
5935 declares that it is a syntax error to find the same operator twice ``in a
5936 row''.
5937
5938 The relative precedence of different operators is controlled by the
5939 order in which they are declared. The first @code{%left} or
5940 @code{%right} declaration in the file declares the operators whose
5941 precedence is lowest, the next such declaration declares the operators
5942 whose precedence is a little higher, and so on.
5943
5944 @node Precedence Examples
5945 @subsection Precedence Examples
5946
5947 In our example, we would want the following declarations:
5948
5949 @example
5950 %left '<'
5951 %left '-'
5952 %left '*'
5953 @end example
5954
5955 In a more complete example, which supports other operators as well, we
5956 would declare them in groups of equal precedence. For example, @code{'+'} is
5957 declared with @code{'-'}:
5958
5959 @example
5960 %left '<' '>' '=' NE LE GE
5961 %left '+' '-'
5962 %left '*' '/'
5963 @end example
5964
5965 @noindent
5966 (Here @code{NE} and so on stand for the operators for ``not equal''
5967 and so on. We assume that these tokens are more than one character long
5968 and therefore are represented by names, not character literals.)
5969
5970 @node How Precedence
5971 @subsection How Precedence Works
5972
5973 The first effect of the precedence declarations is to assign precedence
5974 levels to the terminal symbols declared. The second effect is to assign
5975 precedence levels to certain rules: each rule gets its precedence from
5976 the last terminal symbol mentioned in the components. (You can also
5977 specify explicitly the precedence of a rule. @xref{Contextual
5978 Precedence, ,Context-Dependent Precedence}.)
5979
5980 Finally, the resolution of conflicts works by comparing the precedence
5981 of the rule being considered with that of the lookahead token. If the
5982 token's precedence is higher, the choice is to shift. If the rule's
5983 precedence is higher, the choice is to reduce. If they have equal
5984 precedence, the choice is made based on the associativity of that
5985 precedence level. The verbose output file made by @samp{-v}
5986 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
5987 resolved.
5988
5989 Not all rules and not all tokens have precedence. If either the rule or
5990 the lookahead token has no precedence, then the default is to shift.
5991
5992 @node Contextual Precedence
5993 @section Context-Dependent Precedence
5994 @cindex context-dependent precedence
5995 @cindex unary operator precedence
5996 @cindex precedence, context-dependent
5997 @cindex precedence, unary operator
5998 @findex %prec
5999
6000 Often the precedence of an operator depends on the context. This sounds
6001 outlandish at first, but it is really very common. For example, a minus
6002 sign typically has a very high precedence as a unary operator, and a
6003 somewhat lower precedence (lower than multiplication) as a binary operator.
6004
6005 The Bison precedence declarations, @code{%left}, @code{%right} and
6006 @code{%nonassoc}, can only be used once for a given token; so a token has
6007 only one precedence declared in this way. For context-dependent
6008 precedence, you need to use an additional mechanism: the @code{%prec}
6009 modifier for rules.
6010
6011 The @code{%prec} modifier declares the precedence of a particular rule by
6012 specifying a terminal symbol whose precedence should be used for that rule.
6013 It's not necessary for that symbol to appear otherwise in the rule. The
6014 modifier's syntax is:
6015
6016 @example
6017 %prec @var{terminal-symbol}
6018 @end example
6019
6020 @noindent
6021 and it is written after the components of the rule. Its effect is to
6022 assign the rule the precedence of @var{terminal-symbol}, overriding
6023 the precedence that would be deduced for it in the ordinary way. The
6024 altered rule precedence then affects how conflicts involving that rule
6025 are resolved (@pxref{Precedence, ,Operator Precedence}).
6026
6027 Here is how @code{%prec} solves the problem of unary minus. First, declare
6028 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
6029 are no tokens of this type, but the symbol serves to stand for its
6030 precedence:
6031
6032 @example
6033 @dots{}
6034 %left '+' '-'
6035 %left '*'
6036 %left UMINUS
6037 @end example
6038
6039 Now the precedence of @code{UMINUS} can be used in specific rules:
6040
6041 @example
6042 @group
6043 exp: @dots{}
6044 | exp '-' exp
6045 @dots{}
6046 | '-' exp %prec UMINUS
6047 @end group
6048 @end example
6049
6050 @ifset defaultprec
6051 If you forget to append @code{%prec UMINUS} to the rule for unary
6052 minus, Bison silently assumes that minus has its usual precedence.
6053 This kind of problem can be tricky to debug, since one typically
6054 discovers the mistake only by testing the code.
6055
6056 The @code{%no-default-prec;} declaration makes it easier to discover
6057 this kind of problem systematically. It causes rules that lack a
6058 @code{%prec} modifier to have no precedence, even if the last terminal
6059 symbol mentioned in their components has a declared precedence.
6060
6061 If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
6062 for all rules that participate in precedence conflict resolution.
6063 Then you will see any shift/reduce conflict until you tell Bison how
6064 to resolve it, either by changing your grammar or by adding an
6065 explicit precedence. This will probably add declarations to the
6066 grammar, but it helps to protect against incorrect rule precedences.
6067
6068 The effect of @code{%no-default-prec;} can be reversed by giving
6069 @code{%default-prec;}, which is the default.
6070 @end ifset
6071
6072 @node Parser States
6073 @section Parser States
6074 @cindex finite-state machine
6075 @cindex parser state
6076 @cindex state (of parser)
6077
6078 The function @code{yyparse} is implemented using a finite-state machine.
6079 The values pushed on the parser stack are not simply token type codes; they
6080 represent the entire sequence of terminal and nonterminal symbols at or
6081 near the top of the stack. The current state collects all the information
6082 about previous input which is relevant to deciding what to do next.
6083
6084 Each time a lookahead token is read, the current parser state together
6085 with the type of lookahead token are looked up in a table. This table
6086 entry can say, ``Shift the lookahead token.'' In this case, it also
6087 specifies the new parser state, which is pushed onto the top of the
6088 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
6089 This means that a certain number of tokens or groupings are taken off
6090 the top of the stack, and replaced by one grouping. In other words,
6091 that number of states are popped from the stack, and one new state is
6092 pushed.
6093
6094 There is one other alternative: the table can say that the lookahead token
6095 is erroneous in the current state. This causes error processing to begin
6096 (@pxref{Error Recovery}).
6097
6098 @node Reduce/Reduce
6099 @section Reduce/Reduce Conflicts
6100 @cindex reduce/reduce conflict
6101 @cindex conflicts, reduce/reduce
6102
6103 A reduce/reduce conflict occurs if there are two or more rules that apply
6104 to the same sequence of input. This usually indicates a serious error
6105 in the grammar.
6106
6107 For example, here is an erroneous attempt to define a sequence
6108 of zero or more @code{word} groupings.
6109
6110 @example
6111 sequence: /* empty */
6112 @{ printf ("empty sequence\n"); @}
6113 | maybeword
6114 | sequence word
6115 @{ printf ("added word %s\n", $2); @}
6116 ;
6117
6118 maybeword: /* empty */
6119 @{ printf ("empty maybeword\n"); @}
6120 | word
6121 @{ printf ("single word %s\n", $1); @}
6122 ;
6123 @end example
6124
6125 @noindent
6126 The error is an ambiguity: there is more than one way to parse a single
6127 @code{word} into a @code{sequence}. It could be reduced to a
6128 @code{maybeword} and then into a @code{sequence} via the second rule.
6129 Alternatively, nothing-at-all could be reduced into a @code{sequence}
6130 via the first rule, and this could be combined with the @code{word}
6131 using the third rule for @code{sequence}.
6132
6133 There is also more than one way to reduce nothing-at-all into a
6134 @code{sequence}. This can be done directly via the first rule,
6135 or indirectly via @code{maybeword} and then the second rule.
6136
6137 You might think that this is a distinction without a difference, because it
6138 does not change whether any particular input is valid or not. But it does
6139 affect which actions are run. One parsing order runs the second rule's
6140 action; the other runs the first rule's action and the third rule's action.
6141 In this example, the output of the program changes.
6142
6143 Bison resolves a reduce/reduce conflict by choosing to use the rule that
6144 appears first in the grammar, but it is very risky to rely on this. Every
6145 reduce/reduce conflict must be studied and usually eliminated. Here is the
6146 proper way to define @code{sequence}:
6147
6148 @example
6149 sequence: /* empty */
6150 @{ printf ("empty sequence\n"); @}
6151 | sequence word
6152 @{ printf ("added word %s\n", $2); @}
6153 ;
6154 @end example
6155
6156 Here is another common error that yields a reduce/reduce conflict:
6157
6158 @example
6159 sequence: /* empty */
6160 | sequence words
6161 | sequence redirects
6162 ;
6163
6164 words: /* empty */
6165 | words word
6166 ;
6167
6168 redirects:/* empty */
6169 | redirects redirect
6170 ;
6171 @end example
6172
6173 @noindent
6174 The intention here is to define a sequence which can contain either
6175 @code{word} or @code{redirect} groupings. The individual definitions of
6176 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
6177 three together make a subtle ambiguity: even an empty input can be parsed
6178 in infinitely many ways!
6179
6180 Consider: nothing-at-all could be a @code{words}. Or it could be two
6181 @code{words} in a row, or three, or any number. It could equally well be a
6182 @code{redirects}, or two, or any number. Or it could be a @code{words}
6183 followed by three @code{redirects} and another @code{words}. And so on.
6184
6185 Here are two ways to correct these rules. First, to make it a single level
6186 of sequence:
6187
6188 @example
6189 sequence: /* empty */
6190 | sequence word
6191 | sequence redirect
6192 ;
6193 @end example
6194
6195 Second, to prevent either a @code{words} or a @code{redirects}
6196 from being empty:
6197
6198 @example
6199 sequence: /* empty */
6200 | sequence words
6201 | sequence redirects
6202 ;
6203
6204 words: word
6205 | words word
6206 ;
6207
6208 redirects:redirect
6209 | redirects redirect
6210 ;
6211 @end example
6212
6213 @node Mystery Conflicts
6214 @section Mysterious Reduce/Reduce Conflicts
6215
6216 Sometimes reduce/reduce conflicts can occur that don't look warranted.
6217 Here is an example:
6218
6219 @example
6220 @group
6221 %token ID
6222
6223 %%
6224 def: param_spec return_spec ','
6225 ;
6226 param_spec:
6227 type
6228 | name_list ':' type
6229 ;
6230 @end group
6231 @group
6232 return_spec:
6233 type
6234 | name ':' type
6235 ;
6236 @end group
6237 @group
6238 type: ID
6239 ;
6240 @end group
6241 @group
6242 name: ID
6243 ;
6244 name_list:
6245 name
6246 | name ',' name_list
6247 ;
6248 @end group
6249 @end example
6250
6251 It would seem that this grammar can be parsed with only a single token
6252 of lookahead: when a @code{param_spec} is being read, an @code{ID} is
6253 a @code{name} if a comma or colon follows, or a @code{type} if another
6254 @code{ID} follows. In other words, this grammar is @acronym{LR}(1).
6255
6256 @cindex @acronym{LR}(1)
6257 @cindex @acronym{LALR}(1)
6258 However, Bison, like most parser generators, cannot actually handle all
6259 @acronym{LR}(1) grammars. In this grammar, two contexts, that after
6260 an @code{ID}
6261 at the beginning of a @code{param_spec} and likewise at the beginning of
6262 a @code{return_spec}, are similar enough that Bison assumes they are the
6263 same. They appear similar because the same set of rules would be
6264 active---the rule for reducing to a @code{name} and that for reducing to
6265 a @code{type}. Bison is unable to determine at that stage of processing
6266 that the rules would require different lookahead tokens in the two
6267 contexts, so it makes a single parser state for them both. Combining
6268 the two contexts causes a conflict later. In parser terminology, this
6269 occurrence means that the grammar is not @acronym{LALR}(1).
6270
6271 In general, it is better to fix deficiencies than to document them. But
6272 this particular deficiency is intrinsically hard to fix; parser
6273 generators that can handle @acronym{LR}(1) grammars are hard to write
6274 and tend to
6275 produce parsers that are very large. In practice, Bison is more useful
6276 as it is now.
6277
6278 When the problem arises, you can often fix it by identifying the two
6279 parser states that are being confused, and adding something to make them
6280 look distinct. In the above example, adding one rule to
6281 @code{return_spec} as follows makes the problem go away:
6282
6283 @example
6284 @group
6285 %token BOGUS
6286 @dots{}
6287 %%
6288 @dots{}
6289 return_spec:
6290 type
6291 | name ':' type
6292 /* This rule is never used. */
6293 | ID BOGUS
6294 ;
6295 @end group
6296 @end example
6297
6298 This corrects the problem because it introduces the possibility of an
6299 additional active rule in the context after the @code{ID} at the beginning of
6300 @code{return_spec}. This rule is not active in the corresponding context
6301 in a @code{param_spec}, so the two contexts receive distinct parser states.
6302 As long as the token @code{BOGUS} is never generated by @code{yylex},
6303 the added rule cannot alter the way actual input is parsed.
6304
6305 In this particular example, there is another way to solve the problem:
6306 rewrite the rule for @code{return_spec} to use @code{ID} directly
6307 instead of via @code{name}. This also causes the two confusing
6308 contexts to have different sets of active rules, because the one for
6309 @code{return_spec} activates the altered rule for @code{return_spec}
6310 rather than the one for @code{name}.
6311
6312 @example
6313 param_spec:
6314 type
6315 | name_list ':' type
6316 ;
6317 return_spec:
6318 type
6319 | ID ':' type
6320 ;
6321 @end example
6322
6323 For a more detailed exposition of @acronym{LALR}(1) parsers and parser
6324 generators, please see:
6325 Frank DeRemer and Thomas Pennello, Efficient Computation of
6326 @acronym{LALR}(1) Look-Ahead Sets, @cite{@acronym{ACM} Transactions on
6327 Programming Languages and Systems}, Vol.@: 4, No.@: 4 (October 1982),
6328 pp.@: 615--649 @uref{http://doi.acm.org/10.1145/69622.357187}.
6329
6330 @node Generalized LR Parsing
6331 @section Generalized @acronym{LR} (@acronym{GLR}) Parsing
6332 @cindex @acronym{GLR} parsing
6333 @cindex generalized @acronym{LR} (@acronym{GLR}) parsing
6334 @cindex ambiguous grammars
6335 @cindex nondeterministic parsing
6336
6337 Bison produces @emph{deterministic} parsers that choose uniquely
6338 when to reduce and which reduction to apply
6339 based on a summary of the preceding input and on one extra token of lookahead.
6340 As a result, normal Bison handles a proper subset of the family of
6341 context-free languages.
6342 Ambiguous grammars, since they have strings with more than one possible
6343 sequence of reductions cannot have deterministic parsers in this sense.
6344 The same is true of languages that require more than one symbol of
6345 lookahead, since the parser lacks the information necessary to make a
6346 decision at the point it must be made in a shift-reduce parser.
6347 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
6348 there are languages where Bison's particular choice of how to
6349 summarize the input seen so far loses necessary information.
6350
6351 When you use the @samp{%glr-parser} declaration in your grammar file,
6352 Bison generates a parser that uses a different algorithm, called
6353 Generalized @acronym{LR} (or @acronym{GLR}). A Bison @acronym{GLR}
6354 parser uses the same basic
6355 algorithm for parsing as an ordinary Bison parser, but behaves
6356 differently in cases where there is a shift-reduce conflict that has not
6357 been resolved by precedence rules (@pxref{Precedence}) or a
6358 reduce-reduce conflict. When a @acronym{GLR} parser encounters such a
6359 situation, it
6360 effectively @emph{splits} into a several parsers, one for each possible
6361 shift or reduction. These parsers then proceed as usual, consuming
6362 tokens in lock-step. Some of the stacks may encounter other conflicts
6363 and split further, with the result that instead of a sequence of states,
6364 a Bison @acronym{GLR} parsing stack is what is in effect a tree of states.
6365
6366 In effect, each stack represents a guess as to what the proper parse
6367 is. Additional input may indicate that a guess was wrong, in which case
6368 the appropriate stack silently disappears. Otherwise, the semantics
6369 actions generated in each stack are saved, rather than being executed
6370 immediately. When a stack disappears, its saved semantic actions never
6371 get executed. When a reduction causes two stacks to become equivalent,
6372 their sets of semantic actions are both saved with the state that
6373 results from the reduction. We say that two stacks are equivalent
6374 when they both represent the same sequence of states,
6375 and each pair of corresponding states represents a
6376 grammar symbol that produces the same segment of the input token
6377 stream.
6378
6379 Whenever the parser makes a transition from having multiple
6380 states to having one, it reverts to the normal @acronym{LALR}(1) parsing
6381 algorithm, after resolving and executing the saved-up actions.
6382 At this transition, some of the states on the stack will have semantic
6383 values that are sets (actually multisets) of possible actions. The
6384 parser tries to pick one of the actions by first finding one whose rule
6385 has the highest dynamic precedence, as set by the @samp{%dprec}
6386 declaration. Otherwise, if the alternative actions are not ordered by
6387 precedence, but there the same merging function is declared for both
6388 rules by the @samp{%merge} declaration,
6389 Bison resolves and evaluates both and then calls the merge function on
6390 the result. Otherwise, it reports an ambiguity.
6391
6392 It is possible to use a data structure for the @acronym{GLR} parsing tree that
6393 permits the processing of any @acronym{LALR}(1) grammar in linear time (in the
6394 size of the input), any unambiguous (not necessarily
6395 @acronym{LALR}(1)) grammar in
6396 quadratic worst-case time, and any general (possibly ambiguous)
6397 context-free grammar in cubic worst-case time. However, Bison currently
6398 uses a simpler data structure that requires time proportional to the
6399 length of the input times the maximum number of stacks required for any
6400 prefix of the input. Thus, really ambiguous or nondeterministic
6401 grammars can require exponential time and space to process. Such badly
6402 behaving examples, however, are not generally of practical interest.
6403 Usually, nondeterminism in a grammar is local---the parser is ``in
6404 doubt'' only for a few tokens at a time. Therefore, the current data
6405 structure should generally be adequate. On @acronym{LALR}(1) portions of a
6406 grammar, in particular, it is only slightly slower than with the default
6407 Bison parser.
6408
6409 For a more detailed exposition of @acronym{GLR} parsers, please see: Elizabeth
6410 Scott, Adrian Johnstone and Shamsa Sadaf Hussain, Tomita-Style
6411 Generalised @acronym{LR} Parsers, Royal Holloway, University of
6412 London, Department of Computer Science, TR-00-12,
6413 @uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps},
6414 (2000-12-24).
6415
6416 @node Memory Management
6417 @section Memory Management, and How to Avoid Memory Exhaustion
6418 @cindex memory exhaustion
6419 @cindex memory management
6420 @cindex stack overflow
6421 @cindex parser stack overflow
6422 @cindex overflow of parser stack
6423
6424 The Bison parser stack can run out of memory if too many tokens are shifted and
6425 not reduced. When this happens, the parser function @code{yyparse}
6426 calls @code{yyerror} and then returns 2.
6427
6428 Because Bison parsers have growing stacks, hitting the upper limit
6429 usually results from using a right recursion instead of a left
6430 recursion, @xref{Recursion, ,Recursive Rules}.
6431
6432 @vindex YYMAXDEPTH
6433 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
6434 parser stack can become before memory is exhausted. Define the
6435 macro with a value that is an integer. This value is the maximum number
6436 of tokens that can be shifted (and not reduced) before overflow.
6437
6438 The stack space allowed is not necessarily allocated. If you specify a
6439 large value for @code{YYMAXDEPTH}, the parser normally allocates a small
6440 stack at first, and then makes it bigger by stages as needed. This
6441 increasing allocation happens automatically and silently. Therefore,
6442 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
6443 space for ordinary inputs that do not need much stack.
6444
6445 However, do not allow @code{YYMAXDEPTH} to be a value so large that
6446 arithmetic overflow could occur when calculating the size of the stack
6447 space. Also, do not allow @code{YYMAXDEPTH} to be less than
6448 @code{YYINITDEPTH}.
6449
6450 @cindex default stack limit
6451 The default value of @code{YYMAXDEPTH}, if you do not define it, is
6452 10000.
6453
6454 @vindex YYINITDEPTH
6455 You can control how much stack is allocated initially by defining the
6456 macro @code{YYINITDEPTH} to a positive integer. For the C
6457 @acronym{LALR}(1) parser, this value must be a compile-time constant
6458 unless you are assuming C99 or some other target language or compiler
6459 that allows variable-length arrays. The default is 200.
6460
6461 Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
6462
6463 @c FIXME: C++ output.
6464 Because of semantical differences between C and C++, the
6465 @acronym{LALR}(1) parsers in C produced by Bison cannot grow when compiled
6466 by C++ compilers. In this precise case (compiling a C parser as C++) you are
6467 suggested to grow @code{YYINITDEPTH}. The Bison maintainers hope to fix
6468 this deficiency in a future release.
6469
6470 @node Error Recovery
6471 @chapter Error Recovery
6472 @cindex error recovery
6473 @cindex recovery from errors
6474
6475 It is not usually acceptable to have a program terminate on a syntax
6476 error. For example, a compiler should recover sufficiently to parse the
6477 rest of the input file and check it for errors; a calculator should accept
6478 another expression.
6479
6480 In a simple interactive command parser where each input is one line, it may
6481 be sufficient to allow @code{yyparse} to return 1 on error and have the
6482 caller ignore the rest of the input line when that happens (and then call
6483 @code{yyparse} again). But this is inadequate for a compiler, because it
6484 forgets all the syntactic context leading up to the error. A syntax error
6485 deep within a function in the compiler input should not cause the compiler
6486 to treat the following line like the beginning of a source file.
6487
6488 @findex error
6489 You can define how to recover from a syntax error by writing rules to
6490 recognize the special token @code{error}. This is a terminal symbol that
6491 is always defined (you need not declare it) and reserved for error
6492 handling. The Bison parser generates an @code{error} token whenever a
6493 syntax error happens; if you have provided a rule to recognize this token
6494 in the current context, the parse can continue.
6495
6496 For example:
6497
6498 @example
6499 stmnts: /* empty string */
6500 | stmnts '\n'
6501 | stmnts exp '\n'
6502 | stmnts error '\n'
6503 @end example
6504
6505 The fourth rule in this example says that an error followed by a newline
6506 makes a valid addition to any @code{stmnts}.
6507
6508 What happens if a syntax error occurs in the middle of an @code{exp}? The
6509 error recovery rule, interpreted strictly, applies to the precise sequence
6510 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
6511 the middle of an @code{exp}, there will probably be some additional tokens
6512 and subexpressions on the stack after the last @code{stmnts}, and there
6513 will be tokens to read before the next newline. So the rule is not
6514 applicable in the ordinary way.
6515
6516 But Bison can force the situation to fit the rule, by discarding part of
6517 the semantic context and part of the input. First it discards states
6518 and objects from the stack until it gets back to a state in which the
6519 @code{error} token is acceptable. (This means that the subexpressions
6520 already parsed are discarded, back to the last complete @code{stmnts}.)
6521 At this point the @code{error} token can be shifted. Then, if the old
6522 lookahead token is not acceptable to be shifted next, the parser reads
6523 tokens and discards them until it finds a token which is acceptable. In
6524 this example, Bison reads and discards input until the next newline so
6525 that the fourth rule can apply. Note that discarded symbols are
6526 possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
6527 Discarded Symbols}, for a means to reclaim this memory.
6528
6529 The choice of error rules in the grammar is a choice of strategies for
6530 error recovery. A simple and useful strategy is simply to skip the rest of
6531 the current input line or current statement if an error is detected:
6532
6533 @example
6534 stmnt: error ';' /* On error, skip until ';' is read. */
6535 @end example
6536
6537 It is also useful to recover to the matching close-delimiter of an
6538 opening-delimiter that has already been parsed. Otherwise the
6539 close-delimiter will probably appear to be unmatched, and generate another,
6540 spurious error message:
6541
6542 @example
6543 primary: '(' expr ')'
6544 | '(' error ')'
6545 @dots{}
6546 ;
6547 @end example
6548
6549 Error recovery strategies are necessarily guesses. When they guess wrong,
6550 one syntax error often leads to another. In the above example, the error
6551 recovery rule guesses that an error is due to bad input within one
6552 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
6553 middle of a valid @code{stmnt}. After the error recovery rule recovers
6554 from the first error, another syntax error will be found straightaway,
6555 since the text following the spurious semicolon is also an invalid
6556 @code{stmnt}.
6557
6558 To prevent an outpouring of error messages, the parser will output no error
6559 message for another syntax error that happens shortly after the first; only
6560 after three consecutive input tokens have been successfully shifted will
6561 error messages resume.
6562
6563 Note that rules which accept the @code{error} token may have actions, just
6564 as any other rules can.
6565
6566 @findex yyerrok
6567 You can make error messages resume immediately by using the macro
6568 @code{yyerrok} in an action. If you do this in the error rule's action, no
6569 error messages will be suppressed. This macro requires no arguments;
6570 @samp{yyerrok;} is a valid C statement.
6571
6572 @findex yyclearin
6573 The previous lookahead token is reanalyzed immediately after an error. If
6574 this is unacceptable, then the macro @code{yyclearin} may be used to clear
6575 this token. Write the statement @samp{yyclearin;} in the error rule's
6576 action.
6577 @xref{Action Features, ,Special Features for Use in Actions}.
6578
6579 For example, suppose that on a syntax error, an error handling routine is
6580 called that advances the input stream to some point where parsing should
6581 once again commence. The next symbol returned by the lexical scanner is
6582 probably correct. The previous lookahead token ought to be discarded
6583 with @samp{yyclearin;}.
6584
6585 @vindex YYRECOVERING
6586 The expression @code{YYRECOVERING ()} yields 1 when the parser
6587 is recovering from a syntax error, and 0 otherwise.
6588 Syntax error diagnostics are suppressed while recovering from a syntax
6589 error.
6590
6591 @node Context Dependency
6592 @chapter Handling Context Dependencies
6593
6594 The Bison paradigm is to parse tokens first, then group them into larger
6595 syntactic units. In many languages, the meaning of a token is affected by
6596 its context. Although this violates the Bison paradigm, certain techniques
6597 (known as @dfn{kludges}) may enable you to write Bison parsers for such
6598 languages.
6599
6600 @menu
6601 * Semantic Tokens:: Token parsing can depend on the semantic context.
6602 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
6603 * Tie-in Recovery:: Lexical tie-ins have implications for how
6604 error recovery rules must be written.
6605 @end menu
6606
6607 (Actually, ``kludge'' means any technique that gets its job done but is
6608 neither clean nor robust.)
6609
6610 @node Semantic Tokens
6611 @section Semantic Info in Token Types
6612
6613 The C language has a context dependency: the way an identifier is used
6614 depends on what its current meaning is. For example, consider this:
6615
6616 @example
6617 foo (x);
6618 @end example
6619
6620 This looks like a function call statement, but if @code{foo} is a typedef
6621 name, then this is actually a declaration of @code{x}. How can a Bison
6622 parser for C decide how to parse this input?
6623
6624 The method used in @acronym{GNU} C is to have two different token types,
6625 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
6626 identifier, it looks up the current declaration of the identifier in order
6627 to decide which token type to return: @code{TYPENAME} if the identifier is
6628 declared as a typedef, @code{IDENTIFIER} otherwise.
6629
6630 The grammar rules can then express the context dependency by the choice of
6631 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
6632 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
6633 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
6634 is @emph{not} significant, such as in declarations that can shadow a
6635 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
6636 accepted---there is one rule for each of the two token types.
6637
6638 This technique is simple to use if the decision of which kinds of
6639 identifiers to allow is made at a place close to where the identifier is
6640 parsed. But in C this is not always so: C allows a declaration to
6641 redeclare a typedef name provided an explicit type has been specified
6642 earlier:
6643
6644 @example
6645 typedef int foo, bar;
6646 int baz (void)
6647 @{
6648 static bar (bar); /* @r{redeclare @code{bar} as static variable} */
6649 extern foo foo (foo); /* @r{redeclare @code{foo} as function} */
6650 return foo (bar);
6651 @}
6652 @end example
6653
6654 Unfortunately, the name being declared is separated from the declaration
6655 construct itself by a complicated syntactic structure---the ``declarator''.
6656
6657 As a result, part of the Bison parser for C needs to be duplicated, with
6658 all the nonterminal names changed: once for parsing a declaration in
6659 which a typedef name can be redefined, and once for parsing a
6660 declaration in which that can't be done. Here is a part of the
6661 duplication, with actions omitted for brevity:
6662
6663 @example
6664 initdcl:
6665 declarator maybeasm '='
6666 init
6667 | declarator maybeasm
6668 ;
6669
6670 notype_initdcl:
6671 notype_declarator maybeasm '='
6672 init
6673 | notype_declarator maybeasm
6674 ;
6675 @end example
6676
6677 @noindent
6678 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
6679 cannot. The distinction between @code{declarator} and
6680 @code{notype_declarator} is the same sort of thing.
6681
6682 There is some similarity between this technique and a lexical tie-in
6683 (described next), in that information which alters the lexical analysis is
6684 changed during parsing by other parts of the program. The difference is
6685 here the information is global, and is used for other purposes in the
6686 program. A true lexical tie-in has a special-purpose flag controlled by
6687 the syntactic context.
6688
6689 @node Lexical Tie-ins
6690 @section Lexical Tie-ins
6691 @cindex lexical tie-in
6692
6693 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
6694 which is set by Bison actions, whose purpose is to alter the way tokens are
6695 parsed.
6696
6697 For example, suppose we have a language vaguely like C, but with a special
6698 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
6699 an expression in parentheses in which all integers are hexadecimal. In
6700 particular, the token @samp{a1b} must be treated as an integer rather than
6701 as an identifier if it appears in that context. Here is how you can do it:
6702
6703 @example
6704 @group
6705 %@{
6706 int hexflag;
6707 int yylex (void);
6708 void yyerror (char const *);
6709 %@}
6710 %%
6711 @dots{}
6712 @end group
6713 @group
6714 expr: IDENTIFIER
6715 | constant
6716 | HEX '('
6717 @{ hexflag = 1; @}
6718 expr ')'
6719 @{ hexflag = 0;
6720 $$ = $4; @}
6721 | expr '+' expr
6722 @{ $$ = make_sum ($1, $3); @}
6723 @dots{}
6724 ;
6725 @end group
6726
6727 @group
6728 constant:
6729 INTEGER
6730 | STRING
6731 ;
6732 @end group
6733 @end example
6734
6735 @noindent
6736 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
6737 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
6738 with letters are parsed as integers if possible.
6739
6740 The declaration of @code{hexflag} shown in the prologue of the parser file
6741 is needed to make it accessible to the actions (@pxref{Prologue, ,The Prologue}).
6742 You must also write the code in @code{yylex} to obey the flag.
6743
6744 @node Tie-in Recovery
6745 @section Lexical Tie-ins and Error Recovery
6746
6747 Lexical tie-ins make strict demands on any error recovery rules you have.
6748 @xref{Error Recovery}.
6749
6750 The reason for this is that the purpose of an error recovery rule is to
6751 abort the parsing of one construct and resume in some larger construct.
6752 For example, in C-like languages, a typical error recovery rule is to skip
6753 tokens until the next semicolon, and then start a new statement, like this:
6754
6755 @example
6756 stmt: expr ';'
6757 | IF '(' expr ')' stmt @{ @dots{} @}
6758 @dots{}
6759 error ';'
6760 @{ hexflag = 0; @}
6761 ;
6762 @end example
6763
6764 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
6765 construct, this error rule will apply, and then the action for the
6766 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
6767 remain set for the entire rest of the input, or until the next @code{hex}
6768 keyword, causing identifiers to be misinterpreted as integers.
6769
6770 To avoid this problem the error recovery rule itself clears @code{hexflag}.
6771
6772 There may also be an error recovery rule that works within expressions.
6773 For example, there could be a rule which applies within parentheses
6774 and skips to the close-parenthesis:
6775
6776 @example
6777 @group
6778 expr: @dots{}
6779 | '(' expr ')'
6780 @{ $$ = $2; @}
6781 | '(' error ')'
6782 @dots{}
6783 @end group
6784 @end example
6785
6786 If this rule acts within the @code{hex} construct, it is not going to abort
6787 that construct (since it applies to an inner level of parentheses within
6788 the construct). Therefore, it should not clear the flag: the rest of
6789 the @code{hex} construct should be parsed with the flag still in effect.
6790
6791 What if there is an error recovery rule which might abort out of the
6792 @code{hex} construct or might not, depending on circumstances? There is no
6793 way you can write the action to determine whether a @code{hex} construct is
6794 being aborted or not. So if you are using a lexical tie-in, you had better
6795 make sure your error recovery rules are not of this kind. Each rule must
6796 be such that you can be sure that it always will, or always won't, have to
6797 clear the flag.
6798
6799 @c ================================================== Debugging Your Parser
6800
6801 @node Debugging
6802 @chapter Debugging Your Parser
6803
6804 Developing a parser can be a challenge, especially if you don't
6805 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
6806 Algorithm}). Even so, sometimes a detailed description of the automaton
6807 can help (@pxref{Understanding, , Understanding Your Parser}), or
6808 tracing the execution of the parser can give some insight on why it
6809 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
6810
6811 @menu
6812 * Understanding:: Understanding the structure of your parser.
6813 * Tracing:: Tracing the execution of your parser.
6814 @end menu
6815
6816 @node Understanding
6817 @section Understanding Your Parser
6818
6819 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
6820 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
6821 frequent than one would hope), looking at this automaton is required to
6822 tune or simply fix a parser. Bison provides two different
6823 representation of it, either textually or graphically (as a DOT file).
6824
6825 The textual file is generated when the options @option{--report} or
6826 @option{--verbose} are specified, see @xref{Invocation, , Invoking
6827 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
6828 the parser output file name, and adding @samp{.output} instead.
6829 Therefore, if the input file is @file{foo.y}, then the parser file is
6830 called @file{foo.tab.c} by default. As a consequence, the verbose
6831 output file is called @file{foo.output}.
6832
6833 The following grammar file, @file{calc.y}, will be used in the sequel:
6834
6835 @example
6836 %token NUM STR
6837 %left '+' '-'
6838 %left '*'
6839 %%
6840 exp: exp '+' exp
6841 | exp '-' exp
6842 | exp '*' exp
6843 | exp '/' exp
6844 | NUM
6845 ;
6846 useless: STR;
6847 %%
6848 @end example
6849
6850 @command{bison} reports:
6851
6852 @example
6853 calc.y: warning: 1 useless nonterminal and 1 useless rule
6854 calc.y:11.1-7: warning: useless nonterminal: useless
6855 calc.y:11.10-12: warning: useless rule: useless: STR
6856 calc.y: conflicts: 7 shift/reduce
6857 @end example
6858
6859 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
6860 creates a file @file{calc.output} with contents detailed below. The
6861 order of the output and the exact presentation might vary, but the
6862 interpretation is the same.
6863
6864 The first section includes details on conflicts that were solved thanks
6865 to precedence and/or associativity:
6866
6867 @example
6868 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
6869 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
6870 Conflict in state 8 between rule 2 and token '*' resolved as shift.
6871 @exdent @dots{}
6872 @end example
6873
6874 @noindent
6875 The next section lists states that still have conflicts.
6876
6877 @example
6878 State 8 conflicts: 1 shift/reduce
6879 State 9 conflicts: 1 shift/reduce
6880 State 10 conflicts: 1 shift/reduce
6881 State 11 conflicts: 4 shift/reduce
6882 @end example
6883
6884 @noindent
6885 @cindex token, useless
6886 @cindex useless token
6887 @cindex nonterminal, useless
6888 @cindex useless nonterminal
6889 @cindex rule, useless
6890 @cindex useless rule
6891 The next section reports useless tokens, nonterminal and rules. Useless
6892 nonterminals and rules are removed in order to produce a smaller parser,
6893 but useless tokens are preserved, since they might be used by the
6894 scanner (note the difference between ``useless'' and ``not used''
6895 below):
6896
6897 @example
6898 Useless nonterminals:
6899 useless
6900
6901 Terminals which are not used:
6902 STR
6903
6904 Useless rules:
6905 #6 useless: STR;
6906 @end example
6907
6908 @noindent
6909 The next section reproduces the exact grammar that Bison used:
6910
6911 @example
6912 Grammar
6913
6914 Number, Line, Rule
6915 0 5 $accept -> exp $end
6916 1 5 exp -> exp '+' exp
6917 2 6 exp -> exp '-' exp
6918 3 7 exp -> exp '*' exp
6919 4 8 exp -> exp '/' exp
6920 5 9 exp -> NUM
6921 @end example
6922
6923 @noindent
6924 and reports the uses of the symbols:
6925
6926 @example
6927 Terminals, with rules where they appear
6928
6929 $end (0) 0
6930 '*' (42) 3
6931 '+' (43) 1
6932 '-' (45) 2
6933 '/' (47) 4
6934 error (256)
6935 NUM (258) 5
6936
6937 Nonterminals, with rules where they appear
6938
6939 $accept (8)
6940 on left: 0
6941 exp (9)
6942 on left: 1 2 3 4 5, on right: 0 1 2 3 4
6943 @end example
6944
6945 @noindent
6946 @cindex item
6947 @cindex pointed rule
6948 @cindex rule, pointed
6949 Bison then proceeds onto the automaton itself, describing each state
6950 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
6951 item is a production rule together with a point (marked by @samp{.})
6952 that the input cursor.
6953
6954 @example
6955 state 0
6956
6957 $accept -> . exp $ (rule 0)
6958
6959 NUM shift, and go to state 1
6960
6961 exp go to state 2
6962 @end example
6963
6964 This reads as follows: ``state 0 corresponds to being at the very
6965 beginning of the parsing, in the initial rule, right before the start
6966 symbol (here, @code{exp}). When the parser returns to this state right
6967 after having reduced a rule that produced an @code{exp}, the control
6968 flow jumps to state 2. If there is no such transition on a nonterminal
6969 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
6970 the parse stack, and the control flow jumps to state 1. Any other
6971 lookahead triggers a syntax error.''
6972
6973 @cindex core, item set
6974 @cindex item set core
6975 @cindex kernel, item set
6976 @cindex item set core
6977 Even though the only active rule in state 0 seems to be rule 0, the
6978 report lists @code{NUM} as a lookahead token because @code{NUM} can be
6979 at the beginning of any rule deriving an @code{exp}. By default Bison
6980 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
6981 you want to see more detail you can invoke @command{bison} with
6982 @option{--report=itemset} to list all the items, include those that can
6983 be derived:
6984
6985 @example
6986 state 0
6987
6988 $accept -> . exp $ (rule 0)
6989 exp -> . exp '+' exp (rule 1)
6990 exp -> . exp '-' exp (rule 2)
6991 exp -> . exp '*' exp (rule 3)
6992 exp -> . exp '/' exp (rule 4)
6993 exp -> . NUM (rule 5)
6994
6995 NUM shift, and go to state 1
6996
6997 exp go to state 2
6998 @end example
6999
7000 @noindent
7001 In the state 1...
7002
7003 @example
7004 state 1
7005
7006 exp -> NUM . (rule 5)
7007
7008 $default reduce using rule 5 (exp)
7009 @end example
7010
7011 @noindent
7012 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead token
7013 (@samp{$default}), the parser will reduce it. If it was coming from
7014 state 0, then, after this reduction it will return to state 0, and will
7015 jump to state 2 (@samp{exp: go to state 2}).
7016
7017 @example
7018 state 2
7019
7020 $accept -> exp . $ (rule 0)
7021 exp -> exp . '+' exp (rule 1)
7022 exp -> exp . '-' exp (rule 2)
7023 exp -> exp . '*' exp (rule 3)
7024 exp -> exp . '/' exp (rule 4)
7025
7026 $ shift, and go to state 3
7027 '+' shift, and go to state 4
7028 '-' shift, and go to state 5
7029 '*' shift, and go to state 6
7030 '/' shift, and go to state 7
7031 @end example
7032
7033 @noindent
7034 In state 2, the automaton can only shift a symbol. For instance,
7035 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
7036 @samp{+}, it will be shifted on the parse stack, and the automaton
7037 control will jump to state 4, corresponding to the item @samp{exp -> exp
7038 '+' . exp}. Since there is no default action, any other token than
7039 those listed above will trigger a syntax error.
7040
7041 The state 3 is named the @dfn{final state}, or the @dfn{accepting
7042 state}:
7043
7044 @example
7045 state 3
7046
7047 $accept -> exp $ . (rule 0)
7048
7049 $default accept
7050 @end example
7051
7052 @noindent
7053 the initial rule is completed (the start symbol and the end
7054 of input were read), the parsing exits successfully.
7055
7056 The interpretation of states 4 to 7 is straightforward, and is left to
7057 the reader.
7058
7059 @example
7060 state 4
7061
7062 exp -> exp '+' . exp (rule 1)
7063
7064 NUM shift, and go to state 1
7065
7066 exp go to state 8
7067
7068 state 5
7069
7070 exp -> exp '-' . exp (rule 2)
7071
7072 NUM shift, and go to state 1
7073
7074 exp go to state 9
7075
7076 state 6
7077
7078 exp -> exp '*' . exp (rule 3)
7079
7080 NUM shift, and go to state 1
7081
7082 exp go to state 10
7083
7084 state 7
7085
7086 exp -> exp '/' . exp (rule 4)
7087
7088 NUM shift, and go to state 1
7089
7090 exp go to state 11
7091 @end example
7092
7093 As was announced in beginning of the report, @samp{State 8 conflicts:
7094 1 shift/reduce}:
7095
7096 @example
7097 state 8
7098
7099 exp -> exp . '+' exp (rule 1)
7100 exp -> exp '+' exp . (rule 1)
7101 exp -> exp . '-' exp (rule 2)
7102 exp -> exp . '*' exp (rule 3)
7103 exp -> exp . '/' exp (rule 4)
7104
7105 '*' shift, and go to state 6
7106 '/' shift, and go to state 7
7107
7108 '/' [reduce using rule 1 (exp)]
7109 $default reduce using rule 1 (exp)
7110 @end example
7111
7112 Indeed, there are two actions associated to the lookahead @samp{/}:
7113 either shifting (and going to state 7), or reducing rule 1. The
7114 conflict means that either the grammar is ambiguous, or the parser lacks
7115 information to make the right decision. Indeed the grammar is
7116 ambiguous, as, since we did not specify the precedence of @samp{/}, the
7117 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
7118 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
7119 NUM}, which corresponds to reducing rule 1.
7120
7121 Because in @acronym{LALR}(1) parsing a single decision can be made, Bison
7122 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
7123 Shift/Reduce Conflicts}. Discarded actions are reported in between
7124 square brackets.
7125
7126 Note that all the previous states had a single possible action: either
7127 shifting the next token and going to the corresponding state, or
7128 reducing a single rule. In the other cases, i.e., when shifting
7129 @emph{and} reducing is possible or when @emph{several} reductions are
7130 possible, the lookahead is required to select the action. State 8 is
7131 one such state: if the lookahead is @samp{*} or @samp{/} then the action
7132 is shifting, otherwise the action is reducing rule 1. In other words,
7133 the first two items, corresponding to rule 1, are not eligible when the
7134 lookahead token is @samp{*}, since we specified that @samp{*} has higher
7135 precedence than @samp{+}. More generally, some items are eligible only
7136 with some set of possible lookahead tokens. When run with
7137 @option{--report=lookahead}, Bison specifies these lookahead tokens:
7138
7139 @example
7140 state 8
7141
7142 exp -> exp . '+' exp [$, '+', '-', '/'] (rule 1)
7143 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
7144 exp -> exp . '-' exp (rule 2)
7145 exp -> exp . '*' exp (rule 3)
7146 exp -> exp . '/' exp (rule 4)
7147
7148 '*' shift, and go to state 6
7149 '/' shift, and go to state 7
7150
7151 '/' [reduce using rule 1 (exp)]
7152 $default reduce using rule 1 (exp)
7153 @end example
7154
7155 The remaining states are similar:
7156
7157 @example
7158 state 9
7159
7160 exp -> exp . '+' exp (rule 1)
7161 exp -> exp . '-' exp (rule 2)
7162 exp -> exp '-' exp . (rule 2)
7163 exp -> exp . '*' exp (rule 3)
7164 exp -> exp . '/' exp (rule 4)
7165
7166 '*' shift, and go to state 6
7167 '/' shift, and go to state 7
7168
7169 '/' [reduce using rule 2 (exp)]
7170 $default reduce using rule 2 (exp)
7171
7172 state 10
7173
7174 exp -> exp . '+' exp (rule 1)
7175 exp -> exp . '-' exp (rule 2)
7176 exp -> exp . '*' exp (rule 3)
7177 exp -> exp '*' exp . (rule 3)
7178 exp -> exp . '/' exp (rule 4)
7179
7180 '/' shift, and go to state 7
7181
7182 '/' [reduce using rule 3 (exp)]
7183 $default reduce using rule 3 (exp)
7184
7185 state 11
7186
7187 exp -> exp . '+' exp (rule 1)
7188 exp -> exp . '-' exp (rule 2)
7189 exp -> exp . '*' exp (rule 3)
7190 exp -> exp . '/' exp (rule 4)
7191 exp -> exp '/' exp . (rule 4)
7192
7193 '+' shift, and go to state 4
7194 '-' shift, and go to state 5
7195 '*' shift, and go to state 6
7196 '/' shift, and go to state 7
7197
7198 '+' [reduce using rule 4 (exp)]
7199 '-' [reduce using rule 4 (exp)]
7200 '*' [reduce using rule 4 (exp)]
7201 '/' [reduce using rule 4 (exp)]
7202 $default reduce using rule 4 (exp)
7203 @end example
7204
7205 @noindent
7206 Observe that state 11 contains conflicts not only due to the lack of
7207 precedence of @samp{/} with respect to @samp{+}, @samp{-}, and
7208 @samp{*}, but also because the
7209 associativity of @samp{/} is not specified.
7210
7211
7212 @node Tracing
7213 @section Tracing Your Parser
7214 @findex yydebug
7215 @cindex debugging
7216 @cindex tracing the parser
7217
7218 If a Bison grammar compiles properly but doesn't do what you want when it
7219 runs, the @code{yydebug} parser-trace feature can help you figure out why.
7220
7221 There are several means to enable compilation of trace facilities:
7222
7223 @table @asis
7224 @item the macro @code{YYDEBUG}
7225 @findex YYDEBUG
7226 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
7227 parser. This is compliant with @acronym{POSIX} Yacc. You could use
7228 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
7229 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
7230 Prologue}).
7231
7232 @item the option @option{-t}, @option{--debug}
7233 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
7234 ,Invoking Bison}). This is @acronym{POSIX} compliant too.
7235
7236 @item the directive @samp{%debug}
7237 @findex %debug
7238 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison
7239 Declaration Summary}). This is a Bison extension, which will prove
7240 useful when Bison will output parsers for languages that don't use a
7241 preprocessor. Unless @acronym{POSIX} and Yacc portability matter to
7242 you, this is
7243 the preferred solution.
7244 @end table
7245
7246 We suggest that you always enable the debug option so that debugging is
7247 always possible.
7248
7249 The trace facility outputs messages with macro calls of the form
7250 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
7251 @var{format} and @var{args} are the usual @code{printf} format and variadic
7252 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
7253 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
7254 and @code{YYFPRINTF} is defined to @code{fprintf}.
7255
7256 Once you have compiled the program with trace facilities, the way to
7257 request a trace is to store a nonzero value in the variable @code{yydebug}.
7258 You can do this by making the C code do it (in @code{main}, perhaps), or
7259 you can alter the value with a C debugger.
7260
7261 Each step taken by the parser when @code{yydebug} is nonzero produces a
7262 line or two of trace information, written on @code{stderr}. The trace
7263 messages tell you these things:
7264
7265 @itemize @bullet
7266 @item
7267 Each time the parser calls @code{yylex}, what kind of token was read.
7268
7269 @item
7270 Each time a token is shifted, the depth and complete contents of the
7271 state stack (@pxref{Parser States}).
7272
7273 @item
7274 Each time a rule is reduced, which rule it is, and the complete contents
7275 of the state stack afterward.
7276 @end itemize
7277
7278 To make sense of this information, it helps to refer to the listing file
7279 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
7280 Bison}). This file shows the meaning of each state in terms of
7281 positions in various rules, and also what each state will do with each
7282 possible input token. As you read the successive trace messages, you
7283 can see that the parser is functioning according to its specification in
7284 the listing file. Eventually you will arrive at the place where
7285 something undesirable happens, and you will see which parts of the
7286 grammar are to blame.
7287
7288 The parser file is a C program and you can use C debuggers on it, but it's
7289 not easy to interpret what it is doing. The parser function is a
7290 finite-state machine interpreter, and aside from the actions it executes
7291 the same code over and over. Only the values of variables show where in
7292 the grammar it is working.
7293
7294 @findex YYPRINT
7295 The debugging information normally gives the token type of each token
7296 read, but not its semantic value. You can optionally define a macro
7297 named @code{YYPRINT} to provide a way to print the value. If you define
7298 @code{YYPRINT}, it should take three arguments. The parser will pass a
7299 standard I/O stream, the numeric code for the token type, and the token
7300 value (from @code{yylval}).
7301
7302 Here is an example of @code{YYPRINT} suitable for the multi-function
7303 calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
7304
7305 @smallexample
7306 %@{
7307 static void print_token_value (FILE *, int, YYSTYPE);
7308 #define YYPRINT(file, type, value) print_token_value (file, type, value)
7309 %@}
7310
7311 @dots{} %% @dots{} %% @dots{}
7312
7313 static void
7314 print_token_value (FILE *file, int type, YYSTYPE value)
7315 @{
7316 if (type == VAR)
7317 fprintf (file, "%s", value.tptr->name);
7318 else if (type == NUM)
7319 fprintf (file, "%d", value.val);
7320 @}
7321 @end smallexample
7322
7323 @c ================================================= Invoking Bison
7324
7325 @node Invocation
7326 @chapter Invoking Bison
7327 @cindex invoking Bison
7328 @cindex Bison invocation
7329 @cindex options for invoking Bison
7330
7331 The usual way to invoke Bison is as follows:
7332
7333 @example
7334 bison @var{infile}
7335 @end example
7336
7337 Here @var{infile} is the grammar file name, which usually ends in
7338 @samp{.y}. The parser file's name is made by replacing the @samp{.y}
7339 with @samp{.tab.c} and removing any leading directory. Thus, the
7340 @samp{bison foo.y} file name yields
7341 @file{foo.tab.c}, and the @samp{bison hack/foo.y} file name yields
7342 @file{foo.tab.c}. It's also possible, in case you are writing
7343 C++ code instead of C in your grammar file, to name it @file{foo.ypp}
7344 or @file{foo.y++}. Then, the output files will take an extension like
7345 the given one as input (respectively @file{foo.tab.cpp} and
7346 @file{foo.tab.c++}).
7347 This feature takes effect with all options that manipulate file names like
7348 @samp{-o} or @samp{-d}.
7349
7350 For example :
7351
7352 @example
7353 bison -d @var{infile.yxx}
7354 @end example
7355 @noindent
7356 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
7357
7358 @example
7359 bison -d -o @var{output.c++} @var{infile.y}
7360 @end example
7361 @noindent
7362 will produce @file{output.c++} and @file{outfile.h++}.
7363
7364 For compatibility with @acronym{POSIX}, the standard Bison
7365 distribution also contains a shell script called @command{yacc} that
7366 invokes Bison with the @option{-y} option.
7367
7368 @menu
7369 * Bison Options:: All the options described in detail,
7370 in alphabetical order by short options.
7371 * Option Cross Key:: Alphabetical list of long options.
7372 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
7373 @end menu
7374
7375 @node Bison Options
7376 @section Bison Options
7377
7378 Bison supports both traditional single-letter options and mnemonic long
7379 option names. Long option names are indicated with @samp{--} instead of
7380 @samp{-}. Abbreviations for option names are allowed as long as they
7381 are unique. When a long option takes an argument, like
7382 @samp{--file-prefix}, connect the option name and the argument with
7383 @samp{=}.
7384
7385 Here is a list of options that can be used with Bison, alphabetized by
7386 short option. It is followed by a cross key alphabetized by long
7387 option.
7388
7389 @c Please, keep this ordered as in `bison --help'.
7390 @noindent
7391 Operations modes:
7392 @table @option
7393 @item -h
7394 @itemx --help
7395 Print a summary of the command-line options to Bison and exit.
7396
7397 @item -V
7398 @itemx --version
7399 Print the version number of Bison and exit.
7400
7401 @item --print-localedir
7402 Print the name of the directory containing locale-dependent data.
7403
7404 @item -y
7405 @itemx --yacc
7406 Act more like the traditional Yacc command. This can cause
7407 different diagnostics to be generated, and may change behavior in
7408 other minor ways. Most importantly, imitate Yacc's output
7409 file name conventions, so that the parser output file is called
7410 @file{y.tab.c}, and the other outputs are called @file{y.output} and
7411 @file{y.tab.h}.
7412 Also, if generating an @acronym{LALR}(1) parser in C, generate @code{#define}
7413 statements in addition to an @code{enum} to associate token numbers with token
7414 names.
7415 Thus, the following shell script can substitute for Yacc, and the Bison
7416 distribution contains such a script for compatibility with @acronym{POSIX}:
7417
7418 @example
7419 #! /bin/sh
7420 bison -y "$@@"
7421 @end example
7422
7423 The @option{-y}/@option{--yacc} option is intended for use with
7424 traditional Yacc grammars. If your grammar uses a Bison extension
7425 like @samp{%glr-parser}, Bison might not be Yacc-compatible even if
7426 this option is specified.
7427
7428 @end table
7429
7430 @noindent
7431 Tuning the parser:
7432
7433 @table @option
7434 @item -t
7435 @itemx --debug
7436 In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
7437 already defined, so that the debugging facilities are compiled.
7438 @xref{Tracing, ,Tracing Your Parser}.
7439
7440 @item -L @var{language}
7441 @itemx --language=@var{language}
7442 Specify the programming language for the generated parser, as if
7443 @code{%language} was specified (@pxref{Decl Summary, , Bison Declaration
7444 Summary}). Currently supported languages include C and C++.
7445 @var{language} is case-insensitive.
7446
7447 @item --locations
7448 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
7449
7450 @item -p @var{prefix}
7451 @itemx --name-prefix=@var{prefix}
7452 Pretend that @code{%name-prefix "@var{prefix}"} was specified.
7453 @xref{Decl Summary}.
7454
7455 @item -l
7456 @itemx --no-lines
7457 Don't put any @code{#line} preprocessor commands in the parser file.
7458 Ordinarily Bison puts them in the parser file so that the C compiler
7459 and debuggers will associate errors with your source file, the
7460 grammar file. This option causes them to associate errors with the
7461 parser file, treating it as an independent source file in its own right.
7462
7463 @item -S @var{file}
7464 @itemx --skeleton=@var{file}
7465 Specify the skeleton to use, similar to @code{%skeleton}
7466 (@pxref{Decl Summary, , Bison Declaration Summary}).
7467
7468 You probably don't need this option unless you are developing Bison.
7469 You should use @option{--language} if you want to specify the skeleton for a
7470 different language, because it is clearer and because it will always
7471 choose the correct skeleton for non-deterministic or push parsers.
7472
7473 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
7474 file in the Bison installation directory.
7475 If it does, @var{file} is an absolute file name or a file name relative to the
7476 current working directory.
7477 This is similar to how most shells resolve commands.
7478
7479 @item -k
7480 @itemx --token-table
7481 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
7482 @end table
7483
7484 @noindent
7485 Adjust the output:
7486
7487 @table @option
7488 @item -d
7489 @itemx --defines
7490 Pretend that @code{%defines} was specified, i.e., write an extra output
7491 file containing macro definitions for the token type names defined in
7492 the grammar, as well as a few other declarations. @xref{Decl Summary}.
7493
7494 @item --defines=@var{defines-file}
7495 Same as above, but save in the file @var{defines-file}.
7496
7497 @item -b @var{file-prefix}
7498 @itemx --file-prefix=@var{prefix}
7499 Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
7500 for all Bison output file names. @xref{Decl Summary}.
7501
7502 @item -r @var{things}
7503 @itemx --report=@var{things}
7504 Write an extra output file containing verbose description of the comma
7505 separated list of @var{things} among:
7506
7507 @table @code
7508 @item state
7509 Description of the grammar, conflicts (resolved and unresolved), and
7510 @acronym{LALR} automaton.
7511
7512 @item lookahead
7513 Implies @code{state} and augments the description of the automaton with
7514 each rule's lookahead set.
7515
7516 @item itemset
7517 Implies @code{state} and augments the description of the automaton with
7518 the full set of items for each state, instead of its core only.
7519 @end table
7520
7521 @item -v
7522 @itemx --verbose
7523 Pretend that @code{%verbose} was specified, i.e., write an extra output
7524 file containing verbose descriptions of the grammar and
7525 parser. @xref{Decl Summary}.
7526
7527 @item -o @var{file}
7528 @itemx --output=@var{file}
7529 Specify the @var{file} for the parser file.
7530
7531 The other output files' names are constructed from @var{file} as
7532 described under the @samp{-v} and @samp{-d} options.
7533
7534 @item -g
7535 Output a graphical representation of the @acronym{LALR}(1) grammar
7536 automaton computed by Bison, in @uref{http://www.graphviz.org/, Graphviz}
7537 @uref{http://www.graphviz.org/doc/info/lang.html, @acronym{DOT}} format.
7538 If the grammar file is @file{foo.y}, the output file will
7539 be @file{foo.dot}.
7540
7541 @item --graph=@var{graph-file}
7542 The behavior of @var{--graph} is the same than @samp{-g}. The only
7543 difference is that it has an optional argument which is the name of
7544 the output graph file.
7545 @end table
7546
7547 @node Option Cross Key
7548 @section Option Cross Key
7549
7550 @c FIXME: How about putting the directives too?
7551 Here is a list of options, alphabetized by long option, to help you find
7552 the corresponding short option.
7553
7554 @multitable {@option{--defines=@var{defines-file}}} {@option{-b @var{file-prefix}XXX}}
7555 @headitem Long Option @tab Short Option
7556 @item @option{--debug} @tab @option{-t}
7557 @item @option{--defines=@var{defines-file}} @tab @option{-d}
7558 @item @option{--file-prefix=@var{prefix}} @tab @option{-b @var{file-prefix}}
7559 @item @option{--graph=@var{graph-file}} @tab @option{-d}
7560 @item @option{--help} @tab @option{-h}
7561 @item @option{--name-prefix=@var{prefix}} @tab @option{-p @var{name-prefix}}
7562 @item @option{--no-lines} @tab @option{-l}
7563 @item @option{--output=@var{outfile}} @tab @option{-o @var{outfile}}
7564 @item @option{--print-localedir} @tab
7565 @item @option{--token-table} @tab @option{-k}
7566 @item @option{--verbose} @tab @option{-v}
7567 @item @option{--version} @tab @option{-V}
7568 @item @option{--yacc} @tab @option{-y}
7569 @end multitable
7570
7571 @node Yacc Library
7572 @section Yacc Library
7573
7574 The Yacc library contains default implementations of the
7575 @code{yyerror} and @code{main} functions. These default
7576 implementations are normally not useful, but @acronym{POSIX} requires
7577 them. To use the Yacc library, link your program with the
7578 @option{-ly} option. Note that Bison's implementation of the Yacc
7579 library is distributed under the terms of the @acronym{GNU} General
7580 Public License (@pxref{Copying}).
7581
7582 If you use the Yacc library's @code{yyerror} function, you should
7583 declare @code{yyerror} as follows:
7584
7585 @example
7586 int yyerror (char const *);
7587 @end example
7588
7589 Bison ignores the @code{int} value returned by this @code{yyerror}.
7590 If you use the Yacc library's @code{main} function, your
7591 @code{yyparse} function should have the following type signature:
7592
7593 @example
7594 int yyparse (void);
7595 @end example
7596
7597 @c ================================================= C++ Bison
7598
7599 @node Other Languages
7600 @chapter Parsers Written In Other Languages
7601
7602 @menu
7603 * C++ Parsers:: The interface to generate C++ parser classes
7604 * Java Parsers:: The interface to generate Java parser classes
7605 @end menu
7606
7607 @node C++ Parsers
7608 @section C++ Parsers
7609
7610 @menu
7611 * C++ Bison Interface:: Asking for C++ parser generation
7612 * C++ Semantic Values:: %union vs. C++
7613 * C++ Location Values:: The position and location classes
7614 * C++ Parser Interface:: Instantiating and running the parser
7615 * C++ Scanner Interface:: Exchanges between yylex and parse
7616 * A Complete C++ Example:: Demonstrating their use
7617 @end menu
7618
7619 @node C++ Bison Interface
7620 @subsection C++ Bison Interface
7621 @c - %language "C++"
7622 @c - Always pure
7623 @c - initial action
7624
7625 The C++ @acronym{LALR}(1) parser is selected using the language directive,
7626 @samp{%language "C++"}, or the synonymous command-line option
7627 @option{--language=c++}.
7628 @xref{Decl Summary}.
7629
7630 When run, @command{bison} will create several
7631 entities in the @samp{yy} namespace. Use the @samp{%name-prefix}
7632 directive to change the namespace name, see @ref{Decl Summary}. The
7633 various classes are generated in the following files:
7634
7635 @table @file
7636 @item position.hh
7637 @itemx location.hh
7638 The definition of the classes @code{position} and @code{location},
7639 used for location tracking. @xref{C++ Location Values}.
7640
7641 @item stack.hh
7642 An auxiliary class @code{stack} used by the parser.
7643
7644 @item @var{file}.hh
7645 @itemx @var{file}.cc
7646 (Assuming the extension of the input file was @samp{.yy}.) The
7647 declaration and implementation of the C++ parser class. The basename
7648 and extension of these two files follow the same rules as with regular C
7649 parsers (@pxref{Invocation}).
7650
7651 The header is @emph{mandatory}; you must either pass
7652 @option{-d}/@option{--defines} to @command{bison}, or use the
7653 @samp{%defines} directive.
7654 @end table
7655
7656 All these files are documented using Doxygen; run @command{doxygen}
7657 for a complete and accurate documentation.
7658
7659 @node C++ Semantic Values
7660 @subsection C++ Semantic Values
7661 @c - No objects in unions
7662 @c - YYSTYPE
7663 @c - Printer and destructor
7664
7665 The @code{%union} directive works as for C, see @ref{Union Decl, ,The
7666 Collection of Value Types}. In particular it produces a genuine
7667 @code{union}@footnote{In the future techniques to allow complex types
7668 within pseudo-unions (similar to Boost variants) might be implemented to
7669 alleviate these issues.}, which have a few specific features in C++.
7670 @itemize @minus
7671 @item
7672 The type @code{YYSTYPE} is defined but its use is discouraged: rather
7673 you should refer to the parser's encapsulated type
7674 @code{yy::parser::semantic_type}.
7675 @item
7676 Non POD (Plain Old Data) types cannot be used. C++ forbids any
7677 instance of classes with constructors in unions: only @emph{pointers}
7678 to such objects are allowed.
7679 @end itemize
7680
7681 Because objects have to be stored via pointers, memory is not
7682 reclaimed automatically: using the @code{%destructor} directive is the
7683 only means to avoid leaks. @xref{Destructor Decl, , Freeing Discarded
7684 Symbols}.
7685
7686
7687 @node C++ Location Values
7688 @subsection C++ Location Values
7689 @c - %locations
7690 @c - class Position
7691 @c - class Location
7692 @c - %define filename_type "const symbol::Symbol"
7693
7694 When the directive @code{%locations} is used, the C++ parser supports
7695 location tracking, see @ref{Locations, , Locations Overview}. Two
7696 auxiliary classes define a @code{position}, a single point in a file,
7697 and a @code{location}, a range composed of a pair of
7698 @code{position}s (possibly spanning several files).
7699
7700 @deftypemethod {position} {std::string*} file
7701 The name of the file. It will always be handled as a pointer, the
7702 parser will never duplicate nor deallocate it. As an experimental
7703 feature you may change it to @samp{@var{type}*} using @samp{%define
7704 filename_type "@var{type}"}.
7705 @end deftypemethod
7706
7707 @deftypemethod {position} {unsigned int} line
7708 The line, starting at 1.
7709 @end deftypemethod
7710
7711 @deftypemethod {position} {unsigned int} lines (int @var{height} = 1)
7712 Advance by @var{height} lines, resetting the column number.
7713 @end deftypemethod
7714
7715 @deftypemethod {position} {unsigned int} column
7716 The column, starting at 0.
7717 @end deftypemethod
7718
7719 @deftypemethod {position} {unsigned int} columns (int @var{width} = 1)
7720 Advance by @var{width} columns, without changing the line number.
7721 @end deftypemethod
7722
7723 @deftypemethod {position} {position&} operator+= (position& @var{pos}, int @var{width})
7724 @deftypemethodx {position} {position} operator+ (const position& @var{pos}, int @var{width})
7725 @deftypemethodx {position} {position&} operator-= (const position& @var{pos}, int @var{width})
7726 @deftypemethodx {position} {position} operator- (position& @var{pos}, int @var{width})
7727 Various forms of syntactic sugar for @code{columns}.
7728 @end deftypemethod
7729
7730 @deftypemethod {position} {position} operator<< (std::ostream @var{o}, const position& @var{p})
7731 Report @var{p} on @var{o} like this:
7732 @samp{@var{file}:@var{line}.@var{column}}, or
7733 @samp{@var{line}.@var{column}} if @var{file} is null.
7734 @end deftypemethod
7735
7736 @deftypemethod {location} {position} begin
7737 @deftypemethodx {location} {position} end
7738 The first, inclusive, position of the range, and the first beyond.
7739 @end deftypemethod
7740
7741 @deftypemethod {location} {unsigned int} columns (int @var{width} = 1)
7742 @deftypemethodx {location} {unsigned int} lines (int @var{height} = 1)
7743 Advance the @code{end} position.
7744 @end deftypemethod
7745
7746 @deftypemethod {location} {location} operator+ (const location& @var{begin}, const location& @var{end})
7747 @deftypemethodx {location} {location} operator+ (const location& @var{begin}, int @var{width})
7748 @deftypemethodx {location} {location} operator+= (const location& @var{loc}, int @var{width})
7749 Various forms of syntactic sugar.
7750 @end deftypemethod
7751
7752 @deftypemethod {location} {void} step ()
7753 Move @code{begin} onto @code{end}.
7754 @end deftypemethod
7755
7756
7757 @node C++ Parser Interface
7758 @subsection C++ Parser Interface
7759 @c - define parser_class_name
7760 @c - Ctor
7761 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
7762 @c debug_stream.
7763 @c - Reporting errors
7764
7765 The output files @file{@var{output}.hh} and @file{@var{output}.cc}
7766 declare and define the parser class in the namespace @code{yy}. The
7767 class name defaults to @code{parser}, but may be changed using
7768 @samp{%define parser_class_name "@var{name}"}. The interface of
7769 this class is detailed below. It can be extended using the
7770 @code{%parse-param} feature: its semantics is slightly changed since
7771 it describes an additional member of the parser class, and an
7772 additional argument for its constructor.
7773
7774 @defcv {Type} {parser} {semantic_value_type}
7775 @defcvx {Type} {parser} {location_value_type}
7776 The types for semantics value and locations.
7777 @end defcv
7778
7779 @deftypemethod {parser} {} parser (@var{type1} @var{arg1}, ...)
7780 Build a new parser object. There are no arguments by default, unless
7781 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
7782 @end deftypemethod
7783
7784 @deftypemethod {parser} {int} parse ()
7785 Run the syntactic analysis, and return 0 on success, 1 otherwise.
7786 @end deftypemethod
7787
7788 @deftypemethod {parser} {std::ostream&} debug_stream ()
7789 @deftypemethodx {parser} {void} set_debug_stream (std::ostream& @var{o})
7790 Get or set the stream used for tracing the parsing. It defaults to
7791 @code{std::cerr}.
7792 @end deftypemethod
7793
7794 @deftypemethod {parser} {debug_level_type} debug_level ()
7795 @deftypemethodx {parser} {void} set_debug_level (debug_level @var{l})
7796 Get or set the tracing level. Currently its value is either 0, no trace,
7797 or nonzero, full tracing.
7798 @end deftypemethod
7799
7800 @deftypemethod {parser} {void} error (const location_type& @var{l}, const std::string& @var{m})
7801 The definition for this member function must be supplied by the user:
7802 the parser uses it to report a parser error occurring at @var{l},
7803 described by @var{m}.
7804 @end deftypemethod
7805
7806
7807 @node C++ Scanner Interface
7808 @subsection C++ Scanner Interface
7809 @c - prefix for yylex.
7810 @c - Pure interface to yylex
7811 @c - %lex-param
7812
7813 The parser invokes the scanner by calling @code{yylex}. Contrary to C
7814 parsers, C++ parsers are always pure: there is no point in using the
7815 @code{%pure-parser} directive. Therefore the interface is as follows.
7816
7817 @deftypemethod {parser} {int} yylex (semantic_value_type& @var{yylval}, location_type& @var{yylloc}, @var{type1} @var{arg1}, ...)
7818 Return the next token. Its type is the return value, its semantic
7819 value and location being @var{yylval} and @var{yylloc}. Invocations of
7820 @samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
7821 @end deftypemethod
7822
7823
7824 @node A Complete C++ Example
7825 @subsection A Complete C++ Example
7826
7827 This section demonstrates the use of a C++ parser with a simple but
7828 complete example. This example should be available on your system,
7829 ready to compile, in the directory @dfn{../bison/examples/calc++}. It
7830 focuses on the use of Bison, therefore the design of the various C++
7831 classes is very naive: no accessors, no encapsulation of members etc.
7832 We will use a Lex scanner, and more precisely, a Flex scanner, to
7833 demonstrate the various interaction. A hand written scanner is
7834 actually easier to interface with.
7835
7836 @menu
7837 * Calc++ --- C++ Calculator:: The specifications
7838 * Calc++ Parsing Driver:: An active parsing context
7839 * Calc++ Parser:: A parser class
7840 * Calc++ Scanner:: A pure C++ Flex scanner
7841 * Calc++ Top Level:: Conducting the band
7842 @end menu
7843
7844 @node Calc++ --- C++ Calculator
7845 @subsubsection Calc++ --- C++ Calculator
7846
7847 Of course the grammar is dedicated to arithmetics, a single
7848 expression, possibly preceded by variable assignments. An
7849 environment containing possibly predefined variables such as
7850 @code{one} and @code{two}, is exchanged with the parser. An example
7851 of valid input follows.
7852
7853 @example
7854 three := 3
7855 seven := one + two * three
7856 seven * seven
7857 @end example
7858
7859 @node Calc++ Parsing Driver
7860 @subsubsection Calc++ Parsing Driver
7861 @c - An env
7862 @c - A place to store error messages
7863 @c - A place for the result
7864
7865 To support a pure interface with the parser (and the scanner) the
7866 technique of the ``parsing context'' is convenient: a structure
7867 containing all the data to exchange. Since, in addition to simply
7868 launch the parsing, there are several auxiliary tasks to execute (open
7869 the file for parsing, instantiate the parser etc.), we recommend
7870 transforming the simple parsing context structure into a fully blown
7871 @dfn{parsing driver} class.
7872
7873 The declaration of this driver class, @file{calc++-driver.hh}, is as
7874 follows. The first part includes the CPP guard and imports the
7875 required standard library components, and the declaration of the parser
7876 class.
7877
7878 @comment file: calc++-driver.hh
7879 @example
7880 #ifndef CALCXX_DRIVER_HH
7881 # define CALCXX_DRIVER_HH
7882 # include <string>
7883 # include <map>
7884 # include "calc++-parser.hh"
7885 @end example
7886
7887
7888 @noindent
7889 Then comes the declaration of the scanning function. Flex expects
7890 the signature of @code{yylex} to be defined in the macro
7891 @code{YY_DECL}, and the C++ parser expects it to be declared. We can
7892 factor both as follows.
7893
7894 @comment file: calc++-driver.hh
7895 @example
7896 // Tell Flex the lexer's prototype ...
7897 # define YY_DECL \
7898 yy::calcxx_parser::token_type \
7899 yylex (yy::calcxx_parser::semantic_type* yylval, \
7900 yy::calcxx_parser::location_type* yylloc, \
7901 calcxx_driver& driver)
7902 // ... and declare it for the parser's sake.
7903 YY_DECL;
7904 @end example
7905
7906 @noindent
7907 The @code{calcxx_driver} class is then declared with its most obvious
7908 members.
7909
7910 @comment file: calc++-driver.hh
7911 @example
7912 // Conducting the whole scanning and parsing of Calc++.
7913 class calcxx_driver
7914 @{
7915 public:
7916 calcxx_driver ();
7917 virtual ~calcxx_driver ();
7918
7919 std::map<std::string, int> variables;
7920
7921 int result;
7922 @end example
7923
7924 @noindent
7925 To encapsulate the coordination with the Flex scanner, it is useful to
7926 have two members function to open and close the scanning phase.
7927
7928 @comment file: calc++-driver.hh
7929 @example
7930 // Handling the scanner.
7931 void scan_begin ();
7932 void scan_end ();
7933 bool trace_scanning;
7934 @end example
7935
7936 @noindent
7937 Similarly for the parser itself.
7938
7939 @comment file: calc++-driver.hh
7940 @example
7941 // Run the parser. Return 0 on success.
7942 int parse (const std::string& f);
7943 std::string file;
7944 bool trace_parsing;
7945 @end example
7946
7947 @noindent
7948 To demonstrate pure handling of parse errors, instead of simply
7949 dumping them on the standard error output, we will pass them to the
7950 compiler driver using the following two member functions. Finally, we
7951 close the class declaration and CPP guard.
7952
7953 @comment file: calc++-driver.hh
7954 @example
7955 // Error handling.
7956 void error (const yy::location& l, const std::string& m);
7957 void error (const std::string& m);
7958 @};
7959 #endif // ! CALCXX_DRIVER_HH
7960 @end example
7961
7962 The implementation of the driver is straightforward. The @code{parse}
7963 member function deserves some attention. The @code{error} functions
7964 are simple stubs, they should actually register the located error
7965 messages and set error state.
7966
7967 @comment file: calc++-driver.cc
7968 @example
7969 #include "calc++-driver.hh"
7970 #include "calc++-parser.hh"
7971
7972 calcxx_driver::calcxx_driver ()
7973 : trace_scanning (false), trace_parsing (false)
7974 @{
7975 variables["one"] = 1;
7976 variables["two"] = 2;
7977 @}
7978
7979 calcxx_driver::~calcxx_driver ()
7980 @{
7981 @}
7982
7983 int
7984 calcxx_driver::parse (const std::string &f)
7985 @{
7986 file = f;
7987 scan_begin ();
7988 yy::calcxx_parser parser (*this);
7989 parser.set_debug_level (trace_parsing);
7990 int res = parser.parse ();
7991 scan_end ();
7992 return res;
7993 @}
7994
7995 void
7996 calcxx_driver::error (const yy::location& l, const std::string& m)
7997 @{
7998 std::cerr << l << ": " << m << std::endl;
7999 @}
8000
8001 void
8002 calcxx_driver::error (const std::string& m)
8003 @{
8004 std::cerr << m << std::endl;
8005 @}
8006 @end example
8007
8008 @node Calc++ Parser
8009 @subsubsection Calc++ Parser
8010
8011 The parser definition file @file{calc++-parser.yy} starts by asking for
8012 the C++ LALR(1) skeleton, the creation of the parser header file, and
8013 specifies the name of the parser class. Because the C++ skeleton
8014 changed several times, it is safer to require the version you designed
8015 the grammar for.
8016
8017 @comment file: calc++-parser.yy
8018 @example
8019 %language "C++" /* -*- C++ -*- */
8020 %require "@value{VERSION}"
8021 %defines
8022 %define parser_class_name "calcxx_parser"
8023 @end example
8024
8025 @noindent
8026 @findex %code requires
8027 Then come the declarations/inclusions needed to define the
8028 @code{%union}. Because the parser uses the parsing driver and
8029 reciprocally, both cannot include the header of the other. Because the
8030 driver's header needs detailed knowledge about the parser class (in
8031 particular its inner types), it is the parser's header which will simply
8032 use a forward declaration of the driver.
8033 @xref{Decl Summary, ,%code}.
8034
8035 @comment file: calc++-parser.yy
8036 @example
8037 %code requires @{
8038 # include <string>
8039 class calcxx_driver;
8040 @}
8041 @end example
8042
8043 @noindent
8044 The driver is passed by reference to the parser and to the scanner.
8045 This provides a simple but effective pure interface, not relying on
8046 global variables.
8047
8048 @comment file: calc++-parser.yy
8049 @example
8050 // The parsing context.
8051 %parse-param @{ calcxx_driver& driver @}
8052 %lex-param @{ calcxx_driver& driver @}
8053 @end example
8054
8055 @noindent
8056 Then we request the location tracking feature, and initialize the
8057 first location's file name. Afterwards new locations are computed
8058 relatively to the previous locations: the file name will be
8059 automatically propagated.
8060
8061 @comment file: calc++-parser.yy
8062 @example
8063 %locations
8064 %initial-action
8065 @{
8066 // Initialize the initial location.
8067 @@$.begin.filename = @@$.end.filename = &driver.file;
8068 @};
8069 @end example
8070
8071 @noindent
8072 Use the two following directives to enable parser tracing and verbose
8073 error messages.
8074
8075 @comment file: calc++-parser.yy
8076 @example
8077 %debug
8078 %error-verbose
8079 @end example
8080
8081 @noindent
8082 Semantic values cannot use ``real'' objects, but only pointers to
8083 them.
8084
8085 @comment file: calc++-parser.yy
8086 @example
8087 // Symbols.
8088 %union
8089 @{
8090 int ival;
8091 std::string *sval;
8092 @};
8093 @end example
8094
8095 @noindent
8096 @findex %code
8097 The code between @samp{%code @{} and @samp{@}} is output in the
8098 @file{*.cc} file; it needs detailed knowledge about the driver.
8099
8100 @comment file: calc++-parser.yy
8101 @example
8102 %code @{
8103 # include "calc++-driver.hh"
8104 @}
8105 @end example
8106
8107
8108 @noindent
8109 The token numbered as 0 corresponds to end of file; the following line
8110 allows for nicer error messages referring to ``end of file'' instead
8111 of ``$end''. Similarly user friendly named are provided for each
8112 symbol. Note that the tokens names are prefixed by @code{TOKEN_} to
8113 avoid name clashes.
8114
8115 @comment file: calc++-parser.yy
8116 @example
8117 %token END 0 "end of file"
8118 %token ASSIGN ":="
8119 %token <sval> IDENTIFIER "identifier"
8120 %token <ival> NUMBER "number"
8121 %type <ival> exp
8122 @end example
8123
8124 @noindent
8125 To enable memory deallocation during error recovery, use
8126 @code{%destructor}.
8127
8128 @c FIXME: Document %printer, and mention that it takes a braced-code operand.
8129 @comment file: calc++-parser.yy
8130 @example
8131 %printer @{ debug_stream () << *$$; @} "identifier"
8132 %destructor @{ delete $$; @} "identifier"
8133
8134 %printer @{ debug_stream () << $$; @} <ival>
8135 @end example
8136
8137 @noindent
8138 The grammar itself is straightforward.
8139
8140 @comment file: calc++-parser.yy
8141 @example
8142 %%
8143 %start unit;
8144 unit: assignments exp @{ driver.result = $2; @};
8145
8146 assignments: assignments assignment @{@}
8147 | /* Nothing. */ @{@};
8148
8149 assignment:
8150 "identifier" ":=" exp
8151 @{ driver.variables[*$1] = $3; delete $1; @};
8152
8153 %left '+' '-';
8154 %left '*' '/';
8155 exp: exp '+' exp @{ $$ = $1 + $3; @}
8156 | exp '-' exp @{ $$ = $1 - $3; @}
8157 | exp '*' exp @{ $$ = $1 * $3; @}
8158 | exp '/' exp @{ $$ = $1 / $3; @}
8159 | "identifier" @{ $$ = driver.variables[*$1]; delete $1; @}
8160 | "number" @{ $$ = $1; @};
8161 %%
8162 @end example
8163
8164 @noindent
8165 Finally the @code{error} member function registers the errors to the
8166 driver.
8167
8168 @comment file: calc++-parser.yy
8169 @example
8170 void
8171 yy::calcxx_parser::error (const yy::calcxx_parser::location_type& l,
8172 const std::string& m)
8173 @{
8174 driver.error (l, m);
8175 @}
8176 @end example
8177
8178 @node Calc++ Scanner
8179 @subsubsection Calc++ Scanner
8180
8181 The Flex scanner first includes the driver declaration, then the
8182 parser's to get the set of defined tokens.
8183
8184 @comment file: calc++-scanner.ll
8185 @example
8186 %@{ /* -*- C++ -*- */
8187 # include <cstdlib>
8188 # include <errno.h>
8189 # include <limits.h>
8190 # include <string>
8191 # include "calc++-driver.hh"
8192 # include "calc++-parser.hh"
8193
8194 /* Work around an incompatibility in flex (at least versions
8195 2.5.31 through 2.5.33): it generates code that does
8196 not conform to C89. See Debian bug 333231
8197 <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>. */
8198 # undef yywrap
8199 # define yywrap() 1
8200
8201 /* By default yylex returns int, we use token_type.
8202 Unfortunately yyterminate by default returns 0, which is
8203 not of token_type. */
8204 #define yyterminate() return token::END
8205 %@}
8206 @end example
8207
8208 @noindent
8209 Because there is no @code{#include}-like feature we don't need
8210 @code{yywrap}, we don't need @code{unput} either, and we parse an
8211 actual file, this is not an interactive session with the user.
8212 Finally we enable the scanner tracing features.
8213
8214 @comment file: calc++-scanner.ll
8215 @example
8216 %option noyywrap nounput batch debug
8217 @end example
8218
8219 @noindent
8220 Abbreviations allow for more readable rules.
8221
8222 @comment file: calc++-scanner.ll
8223 @example
8224 id [a-zA-Z][a-zA-Z_0-9]*
8225 int [0-9]+
8226 blank [ \t]
8227 @end example
8228
8229 @noindent
8230 The following paragraph suffices to track locations accurately. Each
8231 time @code{yylex} is invoked, the begin position is moved onto the end
8232 position. Then when a pattern is matched, the end position is
8233 advanced of its width. In case it matched ends of lines, the end
8234 cursor is adjusted, and each time blanks are matched, the begin cursor
8235 is moved onto the end cursor to effectively ignore the blanks
8236 preceding tokens. Comments would be treated equally.
8237
8238 @comment file: calc++-scanner.ll
8239 @example
8240 %@{
8241 # define YY_USER_ACTION yylloc->columns (yyleng);
8242 %@}
8243 %%
8244 %@{
8245 yylloc->step ();
8246 %@}
8247 @{blank@}+ yylloc->step ();
8248 [\n]+ yylloc->lines (yyleng); yylloc->step ();
8249 @end example
8250
8251 @noindent
8252 The rules are simple, just note the use of the driver to report errors.
8253 It is convenient to use a typedef to shorten
8254 @code{yy::calcxx_parser::token::identifier} into
8255 @code{token::identifier} for instance.
8256
8257 @comment file: calc++-scanner.ll
8258 @example
8259 %@{
8260 typedef yy::calcxx_parser::token token;
8261 %@}
8262 /* Convert ints to the actual type of tokens. */
8263 [-+*/] return yy::calcxx_parser::token_type (yytext[0]);
8264 ":=" return token::ASSIGN;
8265 @{int@} @{
8266 errno = 0;
8267 long n = strtol (yytext, NULL, 10);
8268 if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
8269 driver.error (*yylloc, "integer is out of range");
8270 yylval->ival = n;
8271 return token::NUMBER;
8272 @}
8273 @{id@} yylval->sval = new std::string (yytext); return token::IDENTIFIER;
8274 . driver.error (*yylloc, "invalid character");
8275 %%
8276 @end example
8277
8278 @noindent
8279 Finally, because the scanner related driver's member function depend
8280 on the scanner's data, it is simpler to implement them in this file.
8281
8282 @comment file: calc++-scanner.ll
8283 @example
8284 void
8285 calcxx_driver::scan_begin ()
8286 @{
8287 yy_flex_debug = trace_scanning;
8288 if (file == "-")
8289 yyin = stdin;
8290 else if (!(yyin = fopen (file.c_str (), "r")))
8291 @{
8292 error (std::string ("cannot open ") + file);
8293 exit (1);
8294 @}
8295 @}
8296
8297 void
8298 calcxx_driver::scan_end ()
8299 @{
8300 fclose (yyin);
8301 @}
8302 @end example
8303
8304 @node Calc++ Top Level
8305 @subsubsection Calc++ Top Level
8306
8307 The top level file, @file{calc++.cc}, poses no problem.
8308
8309 @comment file: calc++.cc
8310 @example
8311 #include <iostream>
8312 #include "calc++-driver.hh"
8313
8314 int
8315 main (int argc, char *argv[])
8316 @{
8317 calcxx_driver driver;
8318 for (++argv; argv[0]; ++argv)
8319 if (*argv == std::string ("-p"))
8320 driver.trace_parsing = true;
8321 else if (*argv == std::string ("-s"))
8322 driver.trace_scanning = true;
8323 else if (!driver.parse (*argv))
8324 std::cout << driver.result << std::endl;
8325 @}
8326 @end example
8327
8328 @node Java Parsers
8329 @section Java Parsers
8330
8331 @menu
8332 * Java Bison Interface:: Asking for Java parser generation
8333 * Java Semantic Values:: %type and %token vs. Java
8334 * Java Location Values:: The position and location classes
8335 * Java Parser Interface:: Instantiating and running the parser
8336 * Java Scanner Interface:: Java scanners, and pure parsers
8337 * Java Differences:: Differences between C/C++ and Java Grammars
8338 @end menu
8339
8340 @node Java Bison Interface
8341 @subsection Java Bison Interface
8342 @c - %language "Java"
8343 @c - initial action
8344
8345 The Java parser skeletons are selected using a language directive,
8346 @samp{%language "Java"}, or the synonymous command-line option
8347 @option{--language=java}.
8348
8349 When run, @command{bison} will create several entities whose name
8350 starts with @samp{YY}. Use the @samp{%name-prefix} directive to
8351 change the prefix, see @ref{Decl Summary}; classes can be placed
8352 in an arbitrary Java package using a @samp{%define package} section.
8353
8354 The parser class defines an inner class, @code{Location}, that is used
8355 for location tracking. If the parser is pure, it also defines an
8356 inner interface, @code{Lexer}; see~@ref{Java Scanner Interface} for the
8357 meaning of pure parsers when the Java language is chosen. Other than
8358 these inner class/interface, and the members described in~@ref{Java
8359 Parser Interface}, all the other members and fields are preceded
8360 with a @code{yy} prefix to avoid clashes with user code.
8361
8362 No header file can be generated for Java parsers; you must not pass
8363 @option{-d}/@option{--defines} to @command{bison}, nor use the
8364 @samp{%defines} directive.
8365
8366 By default, the @samp{YYParser} class has package visibility. A
8367 declaration @samp{%define "public"} will change to public visibility.
8368 Remember that, according to the Java language specification, the name
8369 of the @file{.java} file should match the name of the class in this
8370 case.
8371
8372 Similarly, a declaration @samp{%define "abstract"} will make your
8373 class abstract.
8374
8375 You can create documentation for generated parsers using Javadoc.
8376
8377 @node Java Semantic Values
8378 @subsection Java Semantic Values
8379 @c - No %union, specify type in %type/%token.
8380 @c - YYSTYPE
8381 @c - Printer and destructor
8382
8383 There is no @code{%union} directive in Java parsers. Instead, the
8384 semantic values' types (class names) should be specified in the
8385 @code{%type} or @code{%token} directive:
8386
8387 @example
8388 %type <Expression> expr assignment_expr term factor
8389 %type <Integer> number
8390 @end example
8391
8392 By default, the semantic stack is declared to have @code{Object} members,
8393 which means that the class types you specify can be of any class.
8394 To improve the type safety of the parser, you can declare the common
8395 superclass of all the semantic values using the @samp{%define} directive.
8396 For example, after the following declaration:
8397
8398 @example
8399 %define "stype" "ASTNode"
8400 @end example
8401
8402 @noindent
8403 any @code{%type} or @code{%token} specifying a semantic type which
8404 is not a subclass of ASTNode, will cause a compile-time error.
8405
8406 Types used in the directives may be qualified with a package name.
8407 Primitive data types are accepted for Java version 1.5 or later. Note
8408 that in this case the autoboxing feature of Java 1.5 will be used.
8409
8410 Java parsers do not support @code{%destructor}, since the language
8411 adopts garbage collection. The parser will try to hold references
8412 to semantic values for as little time as needed.
8413
8414 Java parsers do not support @code{%printer}, as @code{toString()}
8415 can be used to print the semantic values. This however may change
8416 (in a backwards-compatible way) in future versions of Bison.
8417
8418
8419 @node Java Location Values
8420 @subsection Java Location Values
8421 @c - %locations
8422 @c - class Position
8423 @c - class Location
8424
8425 When the directive @code{%locations} is used, the Java parser
8426 supports location tracking, see @ref{Locations, , Locations Overview}.
8427 An auxiliary user-defined class defines a @dfn{position}, a single point
8428 in a file; Bison itself defines a class representing a @dfn{location},
8429 a range composed of a pair of positions (possibly spanning several
8430 files). The location class is an inner class of the parser; the name
8431 is @code{Location} by default, may also be renamed using @code{%define
8432 "location_type" "@var{class-name}}.
8433
8434 The location class treats the position as a completely opaque value.
8435 By default, the class name is @code{Position}, but this can be changed
8436 with @code{%define "position_type" "@var{class-name}"}.
8437
8438
8439 @deftypemethod {Location} {Position} begin
8440 @deftypemethodx {Location} {Position} end
8441 The first, inclusive, position of the range, and the first beyond.
8442 @end deftypemethod
8443
8444 @deftypemethod {Location} {void} toString ()
8445 Prints the range represented by the location. For this to work
8446 properly, the position class should override the @code{equals} and
8447 @code{toString} methods appropriately.
8448 @end deftypemethod
8449
8450
8451 @node Java Parser Interface
8452 @subsection Java Parser Interface
8453 @c - define parser_class_name
8454 @c - Ctor
8455 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
8456 @c debug_stream.
8457 @c - Reporting errors
8458
8459 The output file defines the parser class in the package optionally
8460 indicated in the @code{%define package} section. The class name defaults
8461 to @code{YYParser}. The @code{YY} prefix may be changed using
8462 @samp{%name-prefix}; alternatively, you can use @samp{%define
8463 "parser_class_name" "@var{name}"} to give a custom name to the class.
8464 The interface of this class is detailed below. It can be extended using
8465 the @code{%parse-param} directive; each occurrence of the directive will
8466 add a field to the parser class, and an argument to its constructor.
8467
8468 @deftypemethod {YYParser} {} YYParser (@var{type1} @var{arg1}, ...)
8469 Build a new parser object. There are no arguments by default, unless
8470 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
8471 @end deftypemethod
8472
8473 @deftypemethod {YYParser} {boolean} parse ()
8474 Run the syntactic analysis, and return @code{true} on success,
8475 @code{false} otherwise.
8476 @end deftypemethod
8477
8478 @deftypemethod {YYParser} {boolean} recovering ()
8479 During the syntactic analysis, return @code{true} if recovering
8480 from a syntax error. @xref{Error Recovery}.
8481 @end deftypemethod
8482
8483 @deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
8484 @deftypemethodx {YYParser} {void} setDebugStream (java.io.printStream @var{o})
8485 Get or set the stream used for tracing the parsing. It defaults to
8486 @code{System.err}.
8487 @end deftypemethod
8488
8489 @deftypemethod {YYParser} {int} getDebugLevel ()
8490 @deftypemethodx {YYParser} {void} setDebugLevel (int @var{l})
8491 Get or set the tracing level. Currently its value is either 0, no trace,
8492 or nonzero, full tracing.
8493 @end deftypemethod
8494
8495 @deftypemethod {YYParser} {void} error (Location @var{l}, String @var{m})
8496 The definition for this member function must be supplied by the user
8497 in the same way as the scanner interface (@pxref{Java Scanner
8498 Interface}); the parser uses it to report a parser error occurring at
8499 @var{l}, described by @var{m}.
8500 @end deftypemethod
8501
8502
8503 @node Java Scanner Interface
8504 @subsection Java Scanner Interface
8505 @c - %code lexer
8506 @c - %lex-param
8507 @c - Lexer interface
8508
8509 Contrary to C parsers, Java parsers do not use global variables; the
8510 state of the parser is always local to an instance of the parser class.
8511 Therefore, all Java parsers are ``pure'', and the @code{%pure-parser}
8512 directive does not do anything when used in Java.
8513
8514 The scanner always resides in a separate class than the parser.
8515 Still, Java also two possible ways to interface a Bison-generated Java
8516 parser with a scanner, that is, the scanner may reside in a separate file
8517 than the Bison grammar, or in the same file. The interface
8518 to the scanner is similar in the two cases.
8519
8520 In the first case, where the scanner in the same file as the grammar, the
8521 scanner code has to be placed in @code{%code lexer} blocks. If you want
8522 to pass parameters from the parser constructor to the scanner constructor,
8523 specify them with @code{%lex-param}; they are passed before
8524 @code{%parse-param}s to the constructor.
8525
8526 In the second case, the scanner has to implement interface @code{Lexer},
8527 which is defined within the parser class (e.g., @code{YYParser.Lexer}).
8528 The constructor of the parser object will then accept an object
8529 implementing the interface; @code{%lex-param} is not used in this
8530 case.
8531
8532 In both cases, the scanner has to implement the following methods.
8533
8534 @deftypemethod {Lexer} {void} yyerror (Location @var{l}, String @var{m})
8535 As explained in @pxref{Java Parser Interface}, this method is defined
8536 by the user to emit an error message. The first parameter is omitted
8537 if location tracking is not active. Its type can be changed using
8538 @samp{%define "location_type" "@var{class-name}".}
8539 @end deftypemethod
8540
8541 @deftypemethod {Lexer} {int} yylex (@var{type1} @var{arg1}, ...)
8542 Return the next token. Its type is the return value, its semantic
8543 value and location are saved and returned by the ther methods in the
8544 interface. Invocations of @samp{%lex-param @{@var{type1}
8545 @var{arg1}@}} yield additional arguments.
8546 @end deftypemethod
8547
8548 @deftypemethod {Lexer} {Position} getStartPos ()
8549 @deftypemethodx {Lexer} {Position} getEndPos ()
8550 Return respectively the first position of the last token that
8551 @code{yylex} returned, and the first position beyond it. These
8552 methods are not needed unless location tracking is active.
8553
8554 The return type can be changed using @samp{%define "position_type"
8555 "@var{class-name}".}
8556 @end deftypemethod
8557
8558 @deftypemethod {Lexer} {Object} getLVal ()
8559 Return respectively the first position of the last token that yylex
8560 returned, and the first position beyond it.
8561
8562 The return type can be changed using @samp{%define "stype"
8563 "@var{class-name}".}
8564 @end deftypemethod
8565
8566
8567 If @code{%pure-parser} is not specified, the lexer interface
8568 resides in the same class (@code{YYParser}) as the Bison-generated
8569 parser. The fields and methods that are provided to
8570 this end are as follows.
8571
8572 @deftypemethod {YYParser} {void} error (Location @var{l}, String @var{m})
8573 As explained in @pxref{Java Parser Interface}, this method is defined
8574 by the user to emit an error message. The first parameter is not used
8575 unless location tracking is active. Its type can be changed using
8576 @samp{%define "location_type" "@var{class-name}".}
8577 @end deftypemethod
8578
8579 @deftypemethod {YYParser} {int} yylex (@var{type1} @var{arg1}, ...)
8580 Return the next token. Its type is the return value, its semantic
8581 value and location are saved into @code{yylval}, @code{yystartpos},
8582 @code{yyendpos}. Invocations of @samp{%lex-param @{@var{type1}
8583 @var{arg1}@}} yield additional arguments.
8584 @end deftypemethod
8585
8586 @deftypecv {Field} {YYParser} Position yystartpos
8587 @deftypecvx {Field} {YYParser} Position yyendpos
8588 Contain respectively the first position of the last token that yylex
8589 returned, and the first position beyond it. These methods are not
8590 needed unless location tracking is active.
8591
8592 The field's type can be changed using @samp{%define "position_type"
8593 "@var{class-name}".}
8594 @end deftypecv
8595
8596 @deftypecv {Field} {YYParser} Object yylval
8597 Return respectively the first position of the last token that yylex
8598 returned, and the first position beyond it.
8599
8600 The field's type can be changed using @samp{%define "stype"
8601 "@var{class-name}".}
8602 @end deftypecv
8603
8604 @node Java Differences
8605 @subsection Differences between C/C++ and Java Grammars
8606
8607 The different structure of the Java language forces several differences
8608 between C/C++ grammars, and grammars designed for Java parsers. This
8609 section summarizes these differences.
8610
8611 @itemize
8612 @item
8613 Java lacks a preprocessor, so the @code{YYERROR}, @code{YYACCEPT},
8614 @code{YYABORT} symbols (@pxref{Table of Symbols}) cannot obviously be
8615 macros. Instead, they should be preceded by @code{return} when they
8616 appear in an action. The actual definition of these symbols is
8617 opaque to the Bison grammar, and it might change in the future. The
8618 only meaningful operation that you can do, is to return them.
8619
8620 Note that of these three symbols, only @code{YYACCEPT} and
8621 @code{YYABORT} will cause a return from the @code{yyparse}
8622 method@footnote{Java parsers include the actions in a separate
8623 method than @code{yyparse} in order to have an intuitive syntax that
8624 corresponds to these C macros.}.
8625
8626 @item
8627 The prolog declarations have a different meaning than in C/C++ code.
8628 @table @asis
8629 @item @code{%code imports}
8630 blocks are placed at the beginning of the Java source code. They may
8631 include copyright notices. For a @code{package} declarations, it is
8632 suggested to use @code{%define package} instead.
8633
8634 @item unqualified @code{%code}
8635 blocks are placed inside the parser class.
8636
8637 @item @code{%code lexer}
8638 blocks, if specified, should include the implementation of the
8639 scanner. If there is no such block, the scanner can be any class
8640 that implements the appropriate interface (see @pxref{Java Scanner
8641 Interface}).
8642 @end table
8643
8644 Other @code{%code} blocks are not supported in Java parsers.
8645 The epilogue has the same meaning as in C/C++ code and it can
8646 be used to define other classes used by the parser.
8647 @end itemize
8648
8649 @c ================================================= FAQ
8650
8651 @node FAQ
8652 @chapter Frequently Asked Questions
8653 @cindex frequently asked questions
8654 @cindex questions
8655
8656 Several questions about Bison come up occasionally. Here some of them
8657 are addressed.
8658
8659 @menu
8660 * Memory Exhausted:: Breaking the Stack Limits
8661 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
8662 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
8663 * Implementing Gotos/Loops:: Control Flow in the Calculator
8664 * Multiple start-symbols:: Factoring closely related grammars
8665 * Secure? Conform?:: Is Bison @acronym{POSIX} safe?
8666 * I can't build Bison:: Troubleshooting
8667 * Where can I find help?:: Troubleshouting
8668 * Bug Reports:: Troublereporting
8669 * More Languages:: Parsers in C++, Java, and so on
8670 * Beta Testing:: Experimenting development versions
8671 * Mailing Lists:: Meeting other Bison users
8672 @end menu
8673
8674 @node Memory Exhausted
8675 @section Memory Exhausted
8676
8677 @display
8678 My parser returns with error with a @samp{memory exhausted}
8679 message. What can I do?
8680 @end display
8681
8682 This question is already addressed elsewhere, @xref{Recursion,
8683 ,Recursive Rules}.
8684
8685 @node How Can I Reset the Parser
8686 @section How Can I Reset the Parser
8687
8688 The following phenomenon has several symptoms, resulting in the
8689 following typical questions:
8690
8691 @display
8692 I invoke @code{yyparse} several times, and on correct input it works
8693 properly; but when a parse error is found, all the other calls fail
8694 too. How can I reset the error flag of @code{yyparse}?
8695 @end display
8696
8697 @noindent
8698 or
8699
8700 @display
8701 My parser includes support for an @samp{#include}-like feature, in
8702 which case I run @code{yyparse} from @code{yyparse}. This fails
8703 although I did specify I needed a @code{%pure-parser}.
8704 @end display
8705
8706 These problems typically come not from Bison itself, but from
8707 Lex-generated scanners. Because these scanners use large buffers for
8708 speed, they might not notice a change of input file. As a
8709 demonstration, consider the following source file,
8710 @file{first-line.l}:
8711
8712 @verbatim
8713 %{
8714 #include <stdio.h>
8715 #include <stdlib.h>
8716 %}
8717 %%
8718 .*\n ECHO; return 1;
8719 %%
8720 int
8721 yyparse (char const *file)
8722 {
8723 yyin = fopen (file, "r");
8724 if (!yyin)
8725 exit (2);
8726 /* One token only. */
8727 yylex ();
8728 if (fclose (yyin) != 0)
8729 exit (3);
8730 return 0;
8731 }
8732
8733 int
8734 main (void)
8735 {
8736 yyparse ("input");
8737 yyparse ("input");
8738 return 0;
8739 }
8740 @end verbatim
8741
8742 @noindent
8743 If the file @file{input} contains
8744
8745 @verbatim
8746 input:1: Hello,
8747 input:2: World!
8748 @end verbatim
8749
8750 @noindent
8751 then instead of getting the first line twice, you get:
8752
8753 @example
8754 $ @kbd{flex -ofirst-line.c first-line.l}
8755 $ @kbd{gcc -ofirst-line first-line.c -ll}
8756 $ @kbd{./first-line}
8757 input:1: Hello,
8758 input:2: World!
8759 @end example
8760
8761 Therefore, whenever you change @code{yyin}, you must tell the
8762 Lex-generated scanner to discard its current buffer and switch to the
8763 new one. This depends upon your implementation of Lex; see its
8764 documentation for more. For Flex, it suffices to call
8765 @samp{YY_FLUSH_BUFFER} after each change to @code{yyin}. If your
8766 Flex-generated scanner needs to read from several input streams to
8767 handle features like include files, you might consider using Flex
8768 functions like @samp{yy_switch_to_buffer} that manipulate multiple
8769 input buffers.
8770
8771 If your Flex-generated scanner uses start conditions (@pxref{Start
8772 conditions, , Start conditions, flex, The Flex Manual}), you might
8773 also want to reset the scanner's state, i.e., go back to the initial
8774 start condition, through a call to @samp{BEGIN (0)}.
8775
8776 @node Strings are Destroyed
8777 @section Strings are Destroyed
8778
8779 @display
8780 My parser seems to destroy old strings, or maybe it loses track of
8781 them. Instead of reporting @samp{"foo", "bar"}, it reports
8782 @samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
8783 @end display
8784
8785 This error is probably the single most frequent ``bug report'' sent to
8786 Bison lists, but is only concerned with a misunderstanding of the role
8787 of the scanner. Consider the following Lex code:
8788
8789 @verbatim
8790 %{
8791 #include <stdio.h>
8792 char *yylval = NULL;
8793 %}
8794 %%
8795 .* yylval = yytext; return 1;
8796 \n /* IGNORE */
8797 %%
8798 int
8799 main ()
8800 {
8801 /* Similar to using $1, $2 in a Bison action. */
8802 char *fst = (yylex (), yylval);
8803 char *snd = (yylex (), yylval);
8804 printf ("\"%s\", \"%s\"\n", fst, snd);
8805 return 0;
8806 }
8807 @end verbatim
8808
8809 If you compile and run this code, you get:
8810
8811 @example
8812 $ @kbd{flex -osplit-lines.c split-lines.l}
8813 $ @kbd{gcc -osplit-lines split-lines.c -ll}
8814 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
8815 "one
8816 two", "two"
8817 @end example
8818
8819 @noindent
8820 this is because @code{yytext} is a buffer provided for @emph{reading}
8821 in the action, but if you want to keep it, you have to duplicate it
8822 (e.g., using @code{strdup}). Note that the output may depend on how
8823 your implementation of Lex handles @code{yytext}. For instance, when
8824 given the Lex compatibility option @option{-l} (which triggers the
8825 option @samp{%array}) Flex generates a different behavior:
8826
8827 @example
8828 $ @kbd{flex -l -osplit-lines.c split-lines.l}
8829 $ @kbd{gcc -osplit-lines split-lines.c -ll}
8830 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
8831 "two", "two"
8832 @end example
8833
8834
8835 @node Implementing Gotos/Loops
8836 @section Implementing Gotos/Loops
8837
8838 @display
8839 My simple calculator supports variables, assignments, and functions,
8840 but how can I implement gotos, or loops?
8841 @end display
8842
8843 Although very pedagogical, the examples included in the document blur
8844 the distinction to make between the parser---whose job is to recover
8845 the structure of a text and to transmit it to subsequent modules of
8846 the program---and the processing (such as the execution) of this
8847 structure. This works well with so called straight line programs,
8848 i.e., precisely those that have a straightforward execution model:
8849 execute simple instructions one after the others.
8850
8851 @cindex abstract syntax tree
8852 @cindex @acronym{AST}
8853 If you want a richer model, you will probably need to use the parser
8854 to construct a tree that does represent the structure it has
8855 recovered; this tree is usually called the @dfn{abstract syntax tree},
8856 or @dfn{@acronym{AST}} for short. Then, walking through this tree,
8857 traversing it in various ways, will enable treatments such as its
8858 execution or its translation, which will result in an interpreter or a
8859 compiler.
8860
8861 This topic is way beyond the scope of this manual, and the reader is
8862 invited to consult the dedicated literature.
8863
8864
8865 @node Multiple start-symbols
8866 @section Multiple start-symbols
8867
8868 @display
8869 I have several closely related grammars, and I would like to share their
8870 implementations. In fact, I could use a single grammar but with
8871 multiple entry points.
8872 @end display
8873
8874 Bison does not support multiple start-symbols, but there is a very
8875 simple means to simulate them. If @code{foo} and @code{bar} are the two
8876 pseudo start-symbols, then introduce two new tokens, say
8877 @code{START_FOO} and @code{START_BAR}, and use them as switches from the
8878 real start-symbol:
8879
8880 @example
8881 %token START_FOO START_BAR;
8882 %start start;
8883 start: START_FOO foo
8884 | START_BAR bar;
8885 @end example
8886
8887 These tokens prevents the introduction of new conflicts. As far as the
8888 parser goes, that is all that is needed.
8889
8890 Now the difficult part is ensuring that the scanner will send these
8891 tokens first. If your scanner is hand-written, that should be
8892 straightforward. If your scanner is generated by Lex, them there is
8893 simple means to do it: recall that anything between @samp{%@{ ... %@}}
8894 after the first @code{%%} is copied verbatim in the top of the generated
8895 @code{yylex} function. Make sure a variable @code{start_token} is
8896 available in the scanner (e.g., a global variable or using
8897 @code{%lex-param} etc.), and use the following:
8898
8899 @example
8900 /* @r{Prologue.} */
8901 %%
8902 %@{
8903 if (start_token)
8904 @{
8905 int t = start_token;
8906 start_token = 0;
8907 return t;
8908 @}
8909 %@}
8910 /* @r{The rules.} */
8911 @end example
8912
8913
8914 @node Secure? Conform?
8915 @section Secure? Conform?
8916
8917 @display
8918 Is Bison secure? Does it conform to POSIX?
8919 @end display
8920
8921 If you're looking for a guarantee or certification, we don't provide it.
8922 However, Bison is intended to be a reliable program that conforms to the
8923 @acronym{POSIX} specification for Yacc. If you run into problems,
8924 please send us a bug report.
8925
8926 @node I can't build Bison
8927 @section I can't build Bison
8928
8929 @display
8930 I can't build Bison because @command{make} complains that
8931 @code{msgfmt} is not found.
8932 What should I do?
8933 @end display
8934
8935 Like most GNU packages with internationalization support, that feature
8936 is turned on by default. If you have problems building in the @file{po}
8937 subdirectory, it indicates that your system's internationalization
8938 support is lacking. You can re-configure Bison with
8939 @option{--disable-nls} to turn off this support, or you can install GNU
8940 gettext from @url{ftp://ftp.gnu.org/gnu/gettext/} and re-configure
8941 Bison. See the file @file{ABOUT-NLS} for more information.
8942
8943
8944 @node Where can I find help?
8945 @section Where can I find help?
8946
8947 @display
8948 I'm having trouble using Bison. Where can I find help?
8949 @end display
8950
8951 First, read this fine manual. Beyond that, you can send mail to
8952 @email{help-bison@@gnu.org}. This mailing list is intended to be
8953 populated with people who are willing to answer questions about using
8954 and installing Bison. Please keep in mind that (most of) the people on
8955 the list have aspects of their lives which are not related to Bison (!),
8956 so you may not receive an answer to your question right away. This can
8957 be frustrating, but please try not to honk them off; remember that any
8958 help they provide is purely voluntary and out of the kindness of their
8959 hearts.
8960
8961 @node Bug Reports
8962 @section Bug Reports
8963
8964 @display
8965 I found a bug. What should I include in the bug report?
8966 @end display
8967
8968 Before you send a bug report, make sure you are using the latest
8969 version. Check @url{ftp://ftp.gnu.org/pub/gnu/bison/} or one of its
8970 mirrors. Be sure to include the version number in your bug report. If
8971 the bug is present in the latest version but not in a previous version,
8972 try to determine the most recent version which did not contain the bug.
8973
8974 If the bug is parser-related, you should include the smallest grammar
8975 you can which demonstrates the bug. The grammar file should also be
8976 complete (i.e., I should be able to run it through Bison without having
8977 to edit or add anything). The smaller and simpler the grammar, the
8978 easier it will be to fix the bug.
8979
8980 Include information about your compilation environment, including your
8981 operating system's name and version and your compiler's name and
8982 version. If you have trouble compiling, you should also include a
8983 transcript of the build session, starting with the invocation of
8984 `configure'. Depending on the nature of the bug, you may be asked to
8985 send additional files as well (such as `config.h' or `config.cache').
8986
8987 Patches are most welcome, but not required. That is, do not hesitate to
8988 send a bug report just because you can not provide a fix.
8989
8990 Send bug reports to @email{bug-bison@@gnu.org}.
8991
8992 @node More Languages
8993 @section More Languages
8994
8995 @display
8996 Will Bison ever have C++ and Java support? How about @var{insert your
8997 favorite language here}?
8998 @end display
8999
9000 C++ and Java support is there now, and is documented. We'd love to add other
9001 languages; contributions are welcome.
9002
9003 @node Beta Testing
9004 @section Beta Testing
9005
9006 @display
9007 What is involved in being a beta tester?
9008 @end display
9009
9010 It's not terribly involved. Basically, you would download a test
9011 release, compile it, and use it to build and run a parser or two. After
9012 that, you would submit either a bug report or a message saying that
9013 everything is okay. It is important to report successes as well as
9014 failures because test releases eventually become mainstream releases,
9015 but only if they are adequately tested. If no one tests, development is
9016 essentially halted.
9017
9018 Beta testers are particularly needed for operating systems to which the
9019 developers do not have easy access. They currently have easy access to
9020 recent GNU/Linux and Solaris versions. Reports about other operating
9021 systems are especially welcome.
9022
9023 @node Mailing Lists
9024 @section Mailing Lists
9025
9026 @display
9027 How do I join the help-bison and bug-bison mailing lists?
9028 @end display
9029
9030 See @url{http://lists.gnu.org/}.
9031
9032 @c ================================================= Table of Symbols
9033
9034 @node Table of Symbols
9035 @appendix Bison Symbols
9036 @cindex Bison symbols, table of
9037 @cindex symbols in Bison, table of
9038
9039 @deffn {Variable} @@$
9040 In an action, the location of the left-hand side of the rule.
9041 @xref{Locations, , Locations Overview}.
9042 @end deffn
9043
9044 @deffn {Variable} @@@var{n}
9045 In an action, the location of the @var{n}-th symbol of the right-hand
9046 side of the rule. @xref{Locations, , Locations Overview}.
9047 @end deffn
9048
9049 @deffn {Variable} $$
9050 In an action, the semantic value of the left-hand side of the rule.
9051 @xref{Actions}.
9052 @end deffn
9053
9054 @deffn {Variable} $@var{n}
9055 In an action, the semantic value of the @var{n}-th symbol of the
9056 right-hand side of the rule. @xref{Actions}.
9057 @end deffn
9058
9059 @deffn {Delimiter} %%
9060 Delimiter used to separate the grammar rule section from the
9061 Bison declarations section or the epilogue.
9062 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
9063 @end deffn
9064
9065 @c Don't insert spaces, or check the DVI output.
9066 @deffn {Delimiter} %@{@var{code}%@}
9067 All code listed between @samp{%@{} and @samp{%@}} is copied directly to
9068 the output file uninterpreted. Such code forms the prologue of the input
9069 file. @xref{Grammar Outline, ,Outline of a Bison
9070 Grammar}.
9071 @end deffn
9072
9073 @deffn {Construct} /*@dots{}*/
9074 Comment delimiters, as in C.
9075 @end deffn
9076
9077 @deffn {Delimiter} :
9078 Separates a rule's result from its components. @xref{Rules, ,Syntax of
9079 Grammar Rules}.
9080 @end deffn
9081
9082 @deffn {Delimiter} ;
9083 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
9084 @end deffn
9085
9086 @deffn {Delimiter} |
9087 Separates alternate rules for the same result nonterminal.
9088 @xref{Rules, ,Syntax of Grammar Rules}.
9089 @end deffn
9090
9091 @deffn {Directive} <*>
9092 Used to define a default tagged @code{%destructor} or default tagged
9093 @code{%printer}.
9094
9095 This feature is experimental.
9096 More user feedback will help to determine whether it should become a permanent
9097 feature.
9098
9099 @xref{Destructor Decl, , Freeing Discarded Symbols}.
9100 @end deffn
9101
9102 @deffn {Directive} <>
9103 Used to define a default tagless @code{%destructor} or default tagless
9104 @code{%printer}.
9105
9106 This feature is experimental.
9107 More user feedback will help to determine whether it should become a permanent
9108 feature.
9109
9110 @xref{Destructor Decl, , Freeing Discarded Symbols}.
9111 @end deffn
9112
9113 @deffn {Symbol} $accept
9114 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
9115 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
9116 Start-Symbol}. It cannot be used in the grammar.
9117 @end deffn
9118
9119 @deffn {Directive} %code @{@var{code}@}
9120 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
9121 Insert @var{code} verbatim into output parser source.
9122 @xref{Decl Summary,,%code}.
9123 @end deffn
9124
9125 @deffn {Directive} %debug
9126 Equip the parser for debugging. @xref{Decl Summary}.
9127 @end deffn
9128
9129 @deffn {Directive} %debug
9130 Equip the parser for debugging. @xref{Decl Summary}.
9131 @end deffn
9132
9133 @ifset defaultprec
9134 @deffn {Directive} %default-prec
9135 Assign a precedence to rules that lack an explicit @samp{%prec}
9136 modifier. @xref{Contextual Precedence, ,Context-Dependent
9137 Precedence}.
9138 @end deffn
9139 @end ifset
9140
9141 @deffn {Directive} %define @var{define-variable}
9142 @deffnx {Directive} %define @var{define-variable} @var{value}
9143 Define a variable to adjust Bison's behavior.
9144 @xref{Decl Summary,,%define}.
9145 @end deffn
9146
9147 @deffn {Directive} %defines
9148 Bison declaration to create a header file meant for the scanner.
9149 @xref{Decl Summary}.
9150 @end deffn
9151
9152 @deffn {Directive} %defines @var{defines-file}
9153 Same as above, but save in the file @var{defines-file}.
9154 @xref{Decl Summary}.
9155 @end deffn
9156
9157 @deffn {Directive} %destructor
9158 Specify how the parser should reclaim the memory associated to
9159 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
9160 @end deffn
9161
9162 @deffn {Directive} %dprec
9163 Bison declaration to assign a precedence to a rule that is used at parse
9164 time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
9165 @acronym{GLR} Parsers}.
9166 @end deffn
9167
9168 @deffn {Symbol} $end
9169 The predefined token marking the end of the token stream. It cannot be
9170 used in the grammar.
9171 @end deffn
9172
9173 @deffn {Symbol} error
9174 A token name reserved for error recovery. This token may be used in
9175 grammar rules so as to allow the Bison parser to recognize an error in
9176 the grammar without halting the process. In effect, a sentence
9177 containing an error may be recognized as valid. On a syntax error, the
9178 token @code{error} becomes the current lookahead token. Actions
9179 corresponding to @code{error} are then executed, and the lookahead
9180 token is reset to the token that originally caused the violation.
9181 @xref{Error Recovery}.
9182 @end deffn
9183
9184 @deffn {Directive} %error-verbose
9185 Bison declaration to request verbose, specific error message strings
9186 when @code{yyerror} is called.
9187 @end deffn
9188
9189 @deffn {Directive} %file-prefix "@var{prefix}"
9190 Bison declaration to set the prefix of the output files. @xref{Decl
9191 Summary}.
9192 @end deffn
9193
9194 @deffn {Directive} %glr-parser
9195 Bison declaration to produce a @acronym{GLR} parser. @xref{GLR
9196 Parsers, ,Writing @acronym{GLR} Parsers}.
9197 @end deffn
9198
9199 @deffn {Directive} %initial-action
9200 Run user code before parsing. @xref{Initial Action Decl, , Performing Actions before Parsing}.
9201 @end deffn
9202
9203 @deffn {Directive} %language
9204 Specify the programming language for the generated parser.
9205 @xref{Decl Summary}.
9206 @end deffn
9207
9208 @deffn {Directive} %left
9209 Bison declaration to assign left associativity to token(s).
9210 @xref{Precedence Decl, ,Operator Precedence}.
9211 @end deffn
9212
9213 @deffn {Directive} %lex-param @{@var{argument-declaration}@}
9214 Bison declaration to specifying an additional parameter that
9215 @code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
9216 for Pure Parsers}.
9217 @end deffn
9218
9219 @deffn {Directive} %merge
9220 Bison declaration to assign a merging function to a rule. If there is a
9221 reduce/reduce conflict with a rule having the same merging function, the
9222 function is applied to the two semantic values to get a single result.
9223 @xref{GLR Parsers, ,Writing @acronym{GLR} Parsers}.
9224 @end deffn
9225
9226 @deffn {Directive} %name-prefix "@var{prefix}"
9227 Bison declaration to rename the external symbols. @xref{Decl Summary}.
9228 @end deffn
9229
9230 @ifset defaultprec
9231 @deffn {Directive} %no-default-prec
9232 Do not assign a precedence to rules that lack an explicit @samp{%prec}
9233 modifier. @xref{Contextual Precedence, ,Context-Dependent
9234 Precedence}.
9235 @end deffn
9236 @end ifset
9237
9238 @deffn {Directive} %no-lines
9239 Bison declaration to avoid generating @code{#line} directives in the
9240 parser file. @xref{Decl Summary}.
9241 @end deffn
9242
9243 @deffn {Directive} %nonassoc
9244 Bison declaration to assign nonassociativity to token(s).
9245 @xref{Precedence Decl, ,Operator Precedence}.
9246 @end deffn
9247
9248 @deffn {Directive} %output "@var{file}"
9249 Bison declaration to set the name of the parser file. @xref{Decl
9250 Summary}.
9251 @end deffn
9252
9253 @deffn {Directive} %parse-param @{@var{argument-declaration}@}
9254 Bison declaration to specifying an additional parameter that
9255 @code{yyparse} should accept. @xref{Parser Function,, The Parser
9256 Function @code{yyparse}}.
9257 @end deffn
9258
9259 @deffn {Directive} %prec
9260 Bison declaration to assign a precedence to a specific rule.
9261 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
9262 @end deffn
9263
9264 @deffn {Directive} %pure-parser
9265 Bison declaration to request a pure (reentrant) parser.
9266 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
9267 @end deffn
9268
9269 @deffn {Directive} %require "@var{version}"
9270 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
9271 Require a Version of Bison}.
9272 @end deffn
9273
9274 @deffn {Directive} %right
9275 Bison declaration to assign right associativity to token(s).
9276 @xref{Precedence Decl, ,Operator Precedence}.
9277 @end deffn
9278
9279 @deffn {Directive} %skeleton
9280 Specify the skeleton to use; usually for development.
9281 @xref{Decl Summary}.
9282 @end deffn
9283
9284 @deffn {Directive} %start
9285 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
9286 Start-Symbol}.
9287 @end deffn
9288
9289 @deffn {Directive} %token
9290 Bison declaration to declare token(s) without specifying precedence.
9291 @xref{Token Decl, ,Token Type Names}.
9292 @end deffn
9293
9294 @deffn {Directive} %token-table
9295 Bison declaration to include a token name table in the parser file.
9296 @xref{Decl Summary}.
9297 @end deffn
9298
9299 @deffn {Directive} %type
9300 Bison declaration to declare nonterminals. @xref{Type Decl,
9301 ,Nonterminal Symbols}.
9302 @end deffn
9303
9304 @deffn {Symbol} $undefined
9305 The predefined token onto which all undefined values returned by
9306 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
9307 @code{error}.
9308 @end deffn
9309
9310 @deffn {Directive} %union
9311 Bison declaration to specify several possible data types for semantic
9312 values. @xref{Union Decl, ,The Collection of Value Types}.
9313 @end deffn
9314
9315 @deffn {Macro} YYABORT
9316 Macro to pretend that an unrecoverable syntax error has occurred, by
9317 making @code{yyparse} return 1 immediately. The error reporting
9318 function @code{yyerror} is not called. @xref{Parser Function, ,The
9319 Parser Function @code{yyparse}}.
9320
9321 For Java parsers, this functionality is invoked using @code{return YYABORT;}
9322 instead.
9323 @end deffn
9324
9325 @deffn {Macro} YYACCEPT
9326 Macro to pretend that a complete utterance of the language has been
9327 read, by making @code{yyparse} return 0 immediately.
9328 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
9329
9330 For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
9331 instead.
9332 @end deffn
9333
9334 @deffn {Macro} YYBACKUP
9335 Macro to discard a value from the parser stack and fake a lookahead
9336 token. @xref{Action Features, ,Special Features for Use in Actions}.
9337 @end deffn
9338
9339 @deffn {Variable} yychar
9340 External integer variable that contains the integer value of the
9341 lookahead token. (In a pure parser, it is a local variable within
9342 @code{yyparse}.) Error-recovery rule actions may examine this variable.
9343 @xref{Action Features, ,Special Features for Use in Actions}.
9344 @end deffn
9345
9346 @deffn {Variable} yyclearin
9347 Macro used in error-recovery rule actions. It clears the previous
9348 lookahead token. @xref{Error Recovery}.
9349 @end deffn
9350
9351 @deffn {Macro} YYDEBUG
9352 Macro to define to equip the parser with tracing code. @xref{Tracing,
9353 ,Tracing Your Parser}.
9354 @end deffn
9355
9356 @deffn {Variable} yydebug
9357 External integer variable set to zero by default. If @code{yydebug}
9358 is given a nonzero value, the parser will output information on input
9359 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
9360 @end deffn
9361
9362 @deffn {Macro} yyerrok
9363 Macro to cause parser to recover immediately to its normal mode
9364 after a syntax error. @xref{Error Recovery}.
9365 @end deffn
9366
9367 @deffn {Macro} YYERROR
9368 Macro to pretend that a syntax error has just been detected: call
9369 @code{yyerror} and then perform normal error recovery if possible
9370 (@pxref{Error Recovery}), or (if recovery is impossible) make
9371 @code{yyparse} return 1. @xref{Error Recovery}.
9372
9373 For Java parsers, this functionality is invoked using @code{return YYERROR;}
9374 instead.
9375 @end deffn
9376
9377 @deffn {Function} yyerror
9378 User-supplied function to be called by @code{yyparse} on error.
9379 @xref{Error Reporting, ,The Error
9380 Reporting Function @code{yyerror}}.
9381 @end deffn
9382
9383 @deffn {Macro} YYERROR_VERBOSE
9384 An obsolete macro that you define with @code{#define} in the prologue
9385 to request verbose, specific error message strings
9386 when @code{yyerror} is called. It doesn't matter what definition you
9387 use for @code{YYERROR_VERBOSE}, just whether you define it. Using
9388 @code{%error-verbose} is preferred.
9389 @end deffn
9390
9391 @deffn {Macro} YYINITDEPTH
9392 Macro for specifying the initial size of the parser stack.
9393 @xref{Memory Management}.
9394 @end deffn
9395
9396 @deffn {Function} yylex
9397 User-supplied lexical analyzer function, called with no arguments to get
9398 the next token. @xref{Lexical, ,The Lexical Analyzer Function
9399 @code{yylex}}.
9400 @end deffn
9401
9402 @deffn {Macro} YYLEX_PARAM
9403 An obsolete macro for specifying an extra argument (or list of extra
9404 arguments) for @code{yyparse} to pass to @code{yylex}. The use of this
9405 macro is deprecated, and is supported only for Yacc like parsers.
9406 @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
9407 @end deffn
9408
9409 @deffn {Variable} yylloc
9410 External variable in which @code{yylex} should place the line and column
9411 numbers associated with a token. (In a pure parser, it is a local
9412 variable within @code{yyparse}, and its address is passed to
9413 @code{yylex}.)
9414 You can ignore this variable if you don't use the @samp{@@} feature in the
9415 grammar actions.
9416 @xref{Token Locations, ,Textual Locations of Tokens}.
9417 In semantic actions, it stores the location of the lookahead token.
9418 @xref{Actions and Locations, ,Actions and Locations}.
9419 @end deffn
9420
9421 @deffn {Type} YYLTYPE
9422 Data type of @code{yylloc}; by default, a structure with four
9423 members. @xref{Location Type, , Data Types of Locations}.
9424 @end deffn
9425
9426 @deffn {Variable} yylval
9427 External variable in which @code{yylex} should place the semantic
9428 value associated with a token. (In a pure parser, it is a local
9429 variable within @code{yyparse}, and its address is passed to
9430 @code{yylex}.)
9431 @xref{Token Values, ,Semantic Values of Tokens}.
9432 In semantic actions, it stores the semantic value of the lookahead token.
9433 @xref{Actions, ,Actions}.
9434 @end deffn
9435
9436 @deffn {Macro} YYMAXDEPTH
9437 Macro for specifying the maximum size of the parser stack. @xref{Memory
9438 Management}.
9439 @end deffn
9440
9441 @deffn {Variable} yynerrs
9442 Global variable which Bison increments each time it reports a syntax error.
9443 (In a pure parser, it is a local variable within @code{yyparse}.)
9444 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
9445 @end deffn
9446
9447 @deffn {Function} yyparse
9448 The parser function produced by Bison; call this function to start
9449 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
9450 @end deffn
9451
9452 @deffn {Macro} YYPARSE_PARAM
9453 An obsolete macro for specifying the name of a parameter that
9454 @code{yyparse} should accept. The use of this macro is deprecated, and
9455 is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
9456 Conventions for Pure Parsers}.
9457 @end deffn
9458
9459 @deffn {Macro} YYRECOVERING
9460 The expression @code{YYRECOVERING ()} yields 1 when the parser
9461 is recovering from a syntax error, and 0 otherwise.
9462 @xref{Action Features, ,Special Features for Use in Actions}.
9463 @end deffn
9464
9465 @deffn {Macro} YYSTACK_USE_ALLOCA
9466 Macro used to control the use of @code{alloca} when the C
9467 @acronym{LALR}(1) parser needs to extend its stacks. If defined to 0,
9468 the parser will use @code{malloc} to extend its stacks. If defined to
9469 1, the parser will use @code{alloca}. Values other than 0 and 1 are
9470 reserved for future Bison extensions. If not defined,
9471 @code{YYSTACK_USE_ALLOCA} defaults to 0.
9472
9473 In the all-too-common case where your code may run on a host with a
9474 limited stack and with unreliable stack-overflow checking, you should
9475 set @code{YYMAXDEPTH} to a value that cannot possibly result in
9476 unchecked stack overflow on any of your target hosts when
9477 @code{alloca} is called. You can inspect the code that Bison
9478 generates in order to determine the proper numeric values. This will
9479 require some expertise in low-level implementation details.
9480 @end deffn
9481
9482 @deffn {Type} YYSTYPE
9483 Data type of semantic values; @code{int} by default.
9484 @xref{Value Type, ,Data Types of Semantic Values}.
9485 @end deffn
9486
9487 @node Glossary
9488 @appendix Glossary
9489 @cindex glossary
9490
9491 @table @asis
9492 @item Backus-Naur Form (@acronym{BNF}; also called ``Backus Normal Form'')
9493 Formal method of specifying context-free grammars originally proposed
9494 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
9495 committee document contributing to what became the Algol 60 report.
9496 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9497
9498 @item Context-free grammars
9499 Grammars specified as rules that can be applied regardless of context.
9500 Thus, if there is a rule which says that an integer can be used as an
9501 expression, integers are allowed @emph{anywhere} an expression is
9502 permitted. @xref{Language and Grammar, ,Languages and Context-Free
9503 Grammars}.
9504
9505 @item Dynamic allocation
9506 Allocation of memory that occurs during execution, rather than at
9507 compile time or on entry to a function.
9508
9509 @item Empty string
9510 Analogous to the empty set in set theory, the empty string is a
9511 character string of length zero.
9512
9513 @item Finite-state stack machine
9514 A ``machine'' that has discrete states in which it is said to exist at
9515 each instant in time. As input to the machine is processed, the
9516 machine moves from state to state as specified by the logic of the
9517 machine. In the case of the parser, the input is the language being
9518 parsed, and the states correspond to various stages in the grammar
9519 rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
9520
9521 @item Generalized @acronym{LR} (@acronym{GLR})
9522 A parsing algorithm that can handle all context-free grammars, including those
9523 that are not @acronym{LALR}(1). It resolves situations that Bison's
9524 usual @acronym{LALR}(1)
9525 algorithm cannot by effectively splitting off multiple parsers, trying all
9526 possible parsers, and discarding those that fail in the light of additional
9527 right context. @xref{Generalized LR Parsing, ,Generalized
9528 @acronym{LR} Parsing}.
9529
9530 @item Grouping
9531 A language construct that is (in general) grammatically divisible;
9532 for example, `expression' or `declaration' in C@.
9533 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9534
9535 @item Infix operator
9536 An arithmetic operator that is placed between the operands on which it
9537 performs some operation.
9538
9539 @item Input stream
9540 A continuous flow of data between devices or programs.
9541
9542 @item Language construct
9543 One of the typical usage schemas of the language. For example, one of
9544 the constructs of the C language is the @code{if} statement.
9545 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9546
9547 @item Left associativity
9548 Operators having left associativity are analyzed from left to right:
9549 @samp{a+b+c} first computes @samp{a+b} and then combines with
9550 @samp{c}. @xref{Precedence, ,Operator Precedence}.
9551
9552 @item Left recursion
9553 A rule whose result symbol is also its first component symbol; for
9554 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
9555 Rules}.
9556
9557 @item Left-to-right parsing
9558 Parsing a sentence of a language by analyzing it token by token from
9559 left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
9560
9561 @item Lexical analyzer (scanner)
9562 A function that reads an input stream and returns tokens one by one.
9563 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
9564
9565 @item Lexical tie-in
9566 A flag, set by actions in the grammar rules, which alters the way
9567 tokens are parsed. @xref{Lexical Tie-ins}.
9568
9569 @item Literal string token
9570 A token which consists of two or more fixed characters. @xref{Symbols}.
9571
9572 @item Lookahead token
9573 A token already read but not yet shifted. @xref{Lookahead, ,Lookahead
9574 Tokens}.
9575
9576 @item @acronym{LALR}(1)
9577 The class of context-free grammars that Bison (like most other parser
9578 generators) can handle; a subset of @acronym{LR}(1). @xref{Mystery
9579 Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
9580
9581 @item @acronym{LR}(1)
9582 The class of context-free grammars in which at most one token of
9583 lookahead is needed to disambiguate the parsing of any piece of input.
9584
9585 @item Nonterminal symbol
9586 A grammar symbol standing for a grammatical construct that can
9587 be expressed through rules in terms of smaller constructs; in other
9588 words, a construct that is not a token. @xref{Symbols}.
9589
9590 @item Parser
9591 A function that recognizes valid sentences of a language by analyzing
9592 the syntax structure of a set of tokens passed to it from a lexical
9593 analyzer.
9594
9595 @item Postfix operator
9596 An arithmetic operator that is placed after the operands upon which it
9597 performs some operation.
9598
9599 @item Reduction
9600 Replacing a string of nonterminals and/or terminals with a single
9601 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
9602 Parser Algorithm}.
9603
9604 @item Reentrant
9605 A reentrant subprogram is a subprogram which can be in invoked any
9606 number of times in parallel, without interference between the various
9607 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
9608
9609 @item Reverse polish notation
9610 A language in which all operators are postfix operators.
9611
9612 @item Right recursion
9613 A rule whose result symbol is also its last component symbol; for
9614 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
9615 Rules}.
9616
9617 @item Semantics
9618 In computer languages, the semantics are specified by the actions
9619 taken for each instance of the language, i.e., the meaning of
9620 each statement. @xref{Semantics, ,Defining Language Semantics}.
9621
9622 @item Shift
9623 A parser is said to shift when it makes the choice of analyzing
9624 further input from the stream rather than reducing immediately some
9625 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
9626
9627 @item Single-character literal
9628 A single character that is recognized and interpreted as is.
9629 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
9630
9631 @item Start symbol
9632 The nonterminal symbol that stands for a complete valid utterance in
9633 the language being parsed. The start symbol is usually listed as the
9634 first nonterminal symbol in a language specification.
9635 @xref{Start Decl, ,The Start-Symbol}.
9636
9637 @item Symbol table
9638 A data structure where symbol names and associated data are stored
9639 during parsing to allow for recognition and use of existing
9640 information in repeated uses of a symbol. @xref{Multi-function Calc}.
9641
9642 @item Syntax error
9643 An error encountered during parsing of an input stream due to invalid
9644 syntax. @xref{Error Recovery}.
9645
9646 @item Token
9647 A basic, grammatically indivisible unit of a language. The symbol
9648 that describes a token in the grammar is a terminal symbol.
9649 The input of the Bison parser is a stream of tokens which comes from
9650 the lexical analyzer. @xref{Symbols}.
9651
9652 @item Terminal symbol
9653 A grammar symbol that has no rules in the grammar and therefore is
9654 grammatically indivisible. The piece of text it represents is a token.
9655 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
9656 @end table
9657
9658 @node Copying This Manual
9659 @appendix Copying This Manual
9660 @include fdl.texi
9661
9662 @node Index
9663 @unnumbered Index
9664
9665 @printindex cp
9666
9667 @bye
9668
9669 @c LocalWords: texinfo setfilename settitle setchapternewpage finalout
9670 @c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex
9671 @c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry
9672 @c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa
9673 @c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc
9674 @c LocalWords: rpcalc Lexer Gen Comp Expr ltcalc mfcalc Decl Symtab yylex
9675 @c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref
9676 @c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex
9677 @c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init stmtMerge
9678 @c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG
9679 @c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit
9680 @c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok
9681 @c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln
9682 @c LocalWords: smallexample symrec val tptr FNCT fnctptr func struct sym
9683 @c LocalWords: fnct putsym getsym fname arith fncts atan ptr malloc sizeof
9684 @c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum
9685 @c LocalWords: ptypes itype YYPRINT trigraphs yytname expseq vindex dtype
9686 @c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs
9687 @c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES
9688 @c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param
9689 @c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP
9690 @c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword
9691 @c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH
9692 @c LocalWords: YYINITDEPTH stmnts ref stmnt initdcl maybeasm notype
9693 @c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args
9694 @c LocalWords: infile ypp yxx outfile itemx tex leaderfill
9695 @c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll
9696 @c LocalWords: nbar yytext fst snd osplit ntwo strdup AST
9697 @c LocalWords: YYSTACK DVI fdl printindex