]> git.saurik.com Git - bison.git/blob - doc/bison.texinfo
doc: clean up naming of various Bison files.
[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 (@value{UPDATED}) is for GNU Bison (version
34 @value{VERSION}), the GNU parser generator.
35
36 Copyright @copyright{} 1988-1993, 1995, 1998-2011 Free Software
37 Foundation, Inc.
38
39 @quotation
40 Permission is granted to copy, distribute and/or modify this document
41 under the terms of the GNU Free Documentation License,
42 Version 1.3 or any later version published by the Free Software
43 Foundation; with no Invariant Sections, with the Front-Cover texts
44 being ``A 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 ``GNU Free Documentation License.''
47
48 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
49 modify this GNU manual. Buying copies from the FSF
50 supports it in developing GNU and promoting software
51 freedom.''
52 @end quotation
53 @end copying
54
55 @dircategory Software development
56 @direntry
57 * bison: (bison). 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 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 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 implementation).
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 GLR Parsers
134
135 * Simple GLR Parsers:: Using GLR parsers on unambiguous grammars.
136 * Merging GLR Parses:: Using GLR parsers to resolve ambiguities.
137 * GLR Semantic Actions:: Considerations for semantic values and deferred actions.
138 * Semantic Predicates:: Controlling a parse with arbitrary computations.
139 * Compiler Requirements:: GLR parsers require a modern C compiler.
140
141 Examples
142
143 * RPN Calc:: Reverse polish notation calculator;
144 a first example with no operator precedence.
145 * Infix Calc:: Infix (algebraic) notation calculator.
146 Operator precedence is introduced.
147 * Simple Error Recovery:: Continuing after syntax errors.
148 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
149 * Multi-function Calc:: Calculator with memory and trig functions.
150 It uses multiple data-types for semantic values.
151 * Exercises:: Ideas for improving the multi-function calculator.
152
153 Reverse Polish Notation Calculator
154
155 * Rpcalc Declarations:: Prologue (declarations) for rpcalc.
156 * Rpcalc Rules:: Grammar Rules for rpcalc, with explanation.
157 * Rpcalc Lexer:: The lexical analyzer.
158 * Rpcalc Main:: The controlling function.
159 * Rpcalc Error:: The error reporting function.
160 * Rpcalc Generate:: Running Bison on the grammar file.
161 * Rpcalc Compile:: Run the C compiler on the output code.
162
163 Grammar Rules for @code{rpcalc}
164
165 * Rpcalc Input::
166 * Rpcalc Line::
167 * Rpcalc Expr::
168
169 Location Tracking Calculator: @code{ltcalc}
170
171 * Ltcalc Declarations:: Bison and C declarations for ltcalc.
172 * Ltcalc Rules:: Grammar rules for ltcalc, with explanations.
173 * Ltcalc Lexer:: The lexical analyzer.
174
175 Multi-Function Calculator: @code{mfcalc}
176
177 * Mfcalc Declarations:: Bison declarations for multi-function calculator.
178 * Mfcalc Rules:: Grammar rules for the calculator.
179 * Mfcalc Symbol Table:: Symbol table management subroutines.
180
181 Bison Grammar Files
182
183 * Grammar Outline:: Overall layout of the grammar file.
184 * Symbols:: Terminal and nonterminal symbols.
185 * Rules:: How to write grammar rules.
186 * Recursion:: Writing recursive rules.
187 * Semantics:: Semantic values and actions.
188 * Locations:: Locations and actions.
189 * Declarations:: All kinds of Bison declarations are described here.
190 * Multiple Parsers:: Putting more than one Bison parser in one program.
191
192 Outline of a Bison Grammar
193
194 * Prologue:: Syntax and usage of the prologue.
195 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
196 * Bison Declarations:: Syntax and usage of the Bison declarations section.
197 * Grammar Rules:: Syntax and usage of the grammar rules section.
198 * Epilogue:: Syntax and usage of the epilogue.
199
200 Defining Language Semantics
201
202 * Value Type:: Specifying one data type for all semantic values.
203 * Multiple Types:: Specifying several alternative data types.
204 * Actions:: An action is the semantic definition of a grammar rule.
205 * Action Types:: Specifying data types for actions to operate on.
206 * Mid-Rule Actions:: Most actions go at the end of a rule.
207 This says when, why and how to use the exceptional
208 action in the middle of a rule.
209 * Named References:: Using named references in actions.
210
211 Tracking Locations
212
213 * Location Type:: Specifying a data type for locations.
214 * Actions and Locations:: Using locations in actions.
215 * Location Default Action:: Defining a general way to compute locations.
216
217 Bison Declarations
218
219 * Require Decl:: Requiring a Bison version.
220 * Token Decl:: Declaring terminal symbols.
221 * Precedence Decl:: Declaring terminals with precedence and associativity.
222 * Union Decl:: Declaring the set of all semantic value types.
223 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
224 * Initial Action Decl:: Code run before parsing starts.
225 * Destructor Decl:: Declaring how symbols are freed.
226 * Expect Decl:: Suppressing warnings about parsing conflicts.
227 * Start Decl:: Specifying the start symbol.
228 * Pure Decl:: Requesting a reentrant parser.
229 * Push Decl:: Requesting a push parser.
230 * Decl Summary:: Table of all Bison declarations.
231
232 Parser C-Language Interface
233
234 * Parser Function:: How to call @code{yyparse} and what it returns.
235 * Push Parser Function:: How to call @code{yypush_parse} and what it returns.
236 * Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
237 * Parser Create Function:: How to call @code{yypstate_new} and what it returns.
238 * Parser Delete Function:: How to call @code{yypstate_delete} and what it returns.
239 * Lexical:: You must supply a function @code{yylex}
240 which reads tokens.
241 * Error Reporting:: You must supply a function @code{yyerror}.
242 * Action Features:: Special features for use in actions.
243 * Internationalization:: How to let the parser speak in the user's
244 native language.
245
246 The Lexical Analyzer Function @code{yylex}
247
248 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
249 * Token Values:: How @code{yylex} must return the semantic value
250 of the token it has read.
251 * Token Locations:: How @code{yylex} must return the text location
252 (line number, etc.) of the token, if the
253 actions want that.
254 * Pure Calling:: How the calling convention differs in a pure parser
255 (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
256
257 The Bison Parser Algorithm
258
259 * Lookahead:: Parser looks one token ahead when deciding what to do.
260 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
261 * Precedence:: Operator precedence works by resolving conflicts.
262 * Contextual Precedence:: When an operator's precedence depends on context.
263 * Parser States:: The parser is a finite-state-machine with stack.
264 * Reduce/Reduce:: When two rules are applicable in the same situation.
265 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
266 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
267 * Memory Management:: What happens when memory is exhausted. How to avoid it.
268
269 Operator Precedence
270
271 * Why Precedence:: An example showing why precedence is needed.
272 * Using Precedence:: How to specify precedence and associativity.
273 * Precedence Only:: How to specify precedence only.
274 * Precedence Examples:: How these features are used in the previous example.
275 * How Precedence:: How they work.
276
277 Handling Context Dependencies
278
279 * Semantic Tokens:: Token parsing can depend on the semantic context.
280 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
281 * Tie-in Recovery:: Lexical tie-ins have implications for how
282 error recovery rules must be written.
283
284 Debugging Your Parser
285
286 * Understanding:: Understanding the structure of your parser.
287 * Tracing:: Tracing the execution of your parser.
288
289 Invoking Bison
290
291 * Bison Options:: All the options described in detail,
292 in alphabetical order by short options.
293 * Option Cross Key:: Alphabetical list of long options.
294 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
295
296 Parsers Written In Other Languages
297
298 * C++ Parsers:: The interface to generate C++ parser classes
299 * Java Parsers:: The interface to generate Java parser classes
300
301 C++ Parsers
302
303 * C++ Bison Interface:: Asking for C++ parser generation
304 * C++ Semantic Values:: %union vs. C++
305 * C++ Location Values:: The position and location classes
306 * C++ Parser Interface:: Instantiating and running the parser
307 * C++ Scanner Interface:: Exchanges between yylex and parse
308 * A Complete C++ Example:: Demonstrating their use
309
310 A Complete C++ Example
311
312 * Calc++ --- C++ Calculator:: The specifications
313 * Calc++ Parsing Driver:: An active parsing context
314 * Calc++ Parser:: A parser class
315 * Calc++ Scanner:: A pure C++ Flex scanner
316 * Calc++ Top Level:: Conducting the band
317
318 Java Parsers
319
320 * Java Bison Interface:: Asking for Java parser generation
321 * Java Semantic Values:: %type and %token vs. Java
322 * Java Location Values:: The position and location classes
323 * Java Parser Interface:: Instantiating and running the parser
324 * Java Scanner Interface:: Specifying the scanner for the parser
325 * Java Action Features:: Special features for use in actions
326 * Java Differences:: Differences between C/C++ and Java Grammars
327 * Java Declarations Summary:: List of Bison declarations used with Java
328
329 Frequently Asked Questions
330
331 * Memory Exhausted:: Breaking the Stack Limits
332 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
333 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
334 * Implementing Gotos/Loops:: Control Flow in the Calculator
335 * Multiple start-symbols:: Factoring closely related grammars
336 * Secure? Conform?:: Is Bison POSIX safe?
337 * I can't build Bison:: Troubleshooting
338 * Where can I find help?:: Troubleshouting
339 * Bug Reports:: Troublereporting
340 * More Languages:: Parsers in C++, Java, and so on
341 * Beta Testing:: Experimenting development versions
342 * Mailing Lists:: Meeting other Bison users
343
344 Copying This Manual
345
346 * Copying This Manual:: License for copying this manual.
347
348 @end detailmenu
349 @end menu
350
351 @node Introduction
352 @unnumbered Introduction
353 @cindex introduction
354
355 @dfn{Bison} is a general-purpose parser generator that converts an
356 annotated context-free grammar into a deterministic LR or generalized
357 LR (GLR) parser employing LALR(1) parser tables. As an experimental
358 feature, Bison can also generate IELR(1) or canonical LR(1) parser
359 tables. Once you are proficient with Bison, you can use it to develop
360 a wide range of language parsers, from those used in simple desk
361 calculators to complex programming languages.
362
363 Bison is upward compatible with Yacc: all properly-written Yacc
364 grammars ought to work with Bison with no change. Anyone familiar
365 with Yacc should be able to use Bison with little trouble. You need
366 to be fluent in C or C++ programming in order to use Bison or to
367 understand this manual. Java is also supported as an experimental
368 feature.
369
370 We begin with tutorial chapters that explain the basic concepts of
371 using Bison and show three explained examples, each building on the
372 last. If you don't know Bison or Yacc, start by reading these
373 chapters. Reference chapters follow, which describe specific aspects
374 of Bison in detail.
375
376 Bison was written originally by Robert Corbett. Richard Stallman made
377 it Yacc-compatible. Wilfred Hansen of Carnegie Mellon University
378 added multi-character string literals and other features. Since then,
379 Bison has grown more robust and evolved many other new features thanks
380 to the hard work of a long list of volunteers. For details, see the
381 @file{THANKS} and @file{ChangeLog} files included in the Bison
382 distribution.
383
384 This edition corresponds to version @value{VERSION} of Bison.
385
386 @node Conditions
387 @unnumbered Conditions for Using Bison
388
389 The distribution terms for Bison-generated parsers permit using the
390 parsers in nonfree programs. Before Bison version 2.2, these extra
391 permissions applied only when Bison was generating LALR(1)
392 parsers in C@. And before Bison version 1.24, Bison-generated
393 parsers could be used only in programs that were free software.
394
395 The other GNU programming tools, such as the GNU C
396 compiler, have never
397 had such a requirement. They could always be used for nonfree
398 software. The reason Bison was different was not due to a special
399 policy decision; it resulted from applying the usual General Public
400 License to all of the Bison source code.
401
402 The main output of the Bison utility---the Bison parser implementation
403 file---contains a verbatim copy of a sizable piece of Bison, which is
404 the code for the parser's implementation. (The actions from your
405 grammar are inserted into this implementation at one point, but most
406 of the rest of the implementation is not changed.) When we applied
407 the GPL terms to the skeleton code for the parser's implementation,
408 the effect was to restrict the use of Bison output to free software.
409
410 We didn't change the terms because of sympathy for people who want to
411 make software proprietary. @strong{Software should be free.} But we
412 concluded that limiting Bison's use to free software was doing little to
413 encourage people to make other software free. So we decided to make the
414 practical conditions for using Bison match the practical conditions for
415 using the other GNU tools.
416
417 This exception applies when Bison is generating code for a parser.
418 You can tell whether the exception applies to a Bison output file by
419 inspecting the file for text beginning with ``As a special
420 exception@dots{}''. The text spells out the exact terms of the
421 exception.
422
423 @node Copying
424 @unnumbered GNU GENERAL PUBLIC LICENSE
425 @include gpl-3.0.texi
426
427 @node Concepts
428 @chapter The Concepts of Bison
429
430 This chapter introduces many of the basic concepts without which the
431 details of Bison will not make sense. If you do not already know how to
432 use Bison or Yacc, we suggest you start by reading this chapter carefully.
433
434 @menu
435 * Language and Grammar:: Languages and context-free grammars,
436 as mathematical ideas.
437 * Grammar in Bison:: How we represent grammars for Bison's sake.
438 * Semantic Values:: Each token or syntactic grouping can have
439 a semantic value (the value of an integer,
440 the name of an identifier, etc.).
441 * Semantic Actions:: Each rule can have an action containing C code.
442 * GLR Parsers:: Writing parsers for general context-free languages.
443 * Locations Overview:: Tracking Locations.
444 * Bison Parser:: What are Bison's input and output,
445 how is the output used?
446 * Stages:: Stages in writing and running Bison grammars.
447 * Grammar Layout:: Overall structure of a Bison grammar file.
448 @end menu
449
450 @node Language and Grammar
451 @section Languages and Context-Free Grammars
452
453 @cindex context-free grammar
454 @cindex grammar, context-free
455 In order for Bison to parse a language, it must be described by a
456 @dfn{context-free grammar}. This means that you specify one or more
457 @dfn{syntactic groupings} and give rules for constructing them from their
458 parts. For example, in the C language, one kind of grouping is called an
459 `expression'. One rule for making an expression might be, ``An expression
460 can be made of a minus sign and another expression''. Another would be,
461 ``An expression can be an integer''. As you can see, rules are often
462 recursive, but there must be at least one rule which leads out of the
463 recursion.
464
465 @cindex BNF
466 @cindex Backus-Naur form
467 The most common formal system for presenting such rules for humans to read
468 is @dfn{Backus-Naur Form} or ``BNF'', which was developed in
469 order to specify the language Algol 60. Any grammar expressed in
470 BNF is a context-free grammar. The input to Bison is
471 essentially machine-readable BNF.
472
473 @cindex LALR(1) grammars
474 @cindex IELR(1) grammars
475 @cindex LR(1) grammars
476 There are various important subclasses of context-free grammars.
477 Although it can handle almost all context-free grammars, Bison is
478 optimized for what are called LR(1) grammars.
479 In brief, in these grammars, it must be possible to tell how to parse
480 any portion of an input string with just a single token of lookahead.
481 For historical reasons, Bison by default is limited by the additional
482 restrictions of LALR(1), which is hard to explain simply.
483 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}, for
484 more information on this.
485 As an experimental feature, you can escape these additional restrictions by
486 requesting IELR(1) or canonical LR(1) parser tables.
487 @xref{Decl Summary,,lr.type}, to learn how.
488
489 @cindex GLR parsing
490 @cindex generalized LR (GLR) parsing
491 @cindex ambiguous grammars
492 @cindex nondeterministic parsing
493
494 Parsers for LR(1) grammars are @dfn{deterministic}, meaning
495 roughly that the next grammar rule to apply at any point in the input is
496 uniquely determined by the preceding input and a fixed, finite portion
497 (called a @dfn{lookahead}) of the remaining input. A context-free
498 grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
499 apply the grammar rules to get the same inputs. Even unambiguous
500 grammars can be @dfn{nondeterministic}, meaning that no fixed
501 lookahead always suffices to determine the next grammar rule to apply.
502 With the proper declarations, Bison is also able to parse these more
503 general context-free grammars, using a technique known as GLR
504 parsing (for Generalized LR). Bison's GLR parsers
505 are able to handle any context-free grammar for which the number of
506 possible parses of any given string is finite.
507
508 @cindex symbols (abstract)
509 @cindex token
510 @cindex syntactic grouping
511 @cindex grouping, syntactic
512 In the formal grammatical rules for a language, each kind of syntactic
513 unit or grouping is named by a @dfn{symbol}. Those which are built by
514 grouping smaller constructs according to grammatical rules are called
515 @dfn{nonterminal symbols}; those which can't be subdivided are called
516 @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
517 corresponding to a single terminal symbol a @dfn{token}, and a piece
518 corresponding to a single nonterminal symbol a @dfn{grouping}.
519
520 We can use the C language as an example of what symbols, terminal and
521 nonterminal, mean. The tokens of C are identifiers, constants (numeric
522 and string), and the various keywords, arithmetic operators and
523 punctuation marks. So the terminal symbols of a grammar for C include
524 `identifier', `number', `string', plus one symbol for each keyword,
525 operator or punctuation mark: `if', `return', `const', `static', `int',
526 `char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
527 (These tokens can be subdivided into characters, but that is a matter of
528 lexicography, not grammar.)
529
530 Here is a simple C function subdivided into tokens:
531
532 @ifinfo
533 @example
534 int /* @r{keyword `int'} */
535 square (int x) /* @r{identifier, open-paren, keyword `int',}
536 @r{identifier, close-paren} */
537 @{ /* @r{open-brace} */
538 return x * x; /* @r{keyword `return', identifier, asterisk,}
539 @r{identifier, semicolon} */
540 @} /* @r{close-brace} */
541 @end example
542 @end ifinfo
543 @ifnotinfo
544 @example
545 int /* @r{keyword `int'} */
546 square (int x) /* @r{identifier, open-paren, keyword `int', identifier, close-paren} */
547 @{ /* @r{open-brace} */
548 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
549 @} /* @r{close-brace} */
550 @end example
551 @end ifnotinfo
552
553 The syntactic groupings of C include the expression, the statement, the
554 declaration, and the function definition. These are represented in the
555 grammar of C by nonterminal symbols `expression', `statement',
556 `declaration' and `function definition'. The full grammar uses dozens of
557 additional language constructs, each with its own nonterminal symbol, in
558 order to express the meanings of these four. The example above is a
559 function definition; it contains one declaration, and one statement. In
560 the statement, each @samp{x} is an expression and so is @samp{x * x}.
561
562 Each nonterminal symbol must have grammatical rules showing how it is made
563 out of simpler constructs. For example, one kind of C statement is the
564 @code{return} statement; this would be described with a grammar rule which
565 reads informally as follows:
566
567 @quotation
568 A `statement' can be made of a `return' keyword, an `expression' and a
569 `semicolon'.
570 @end quotation
571
572 @noindent
573 There would be many other rules for `statement', one for each kind of
574 statement in C.
575
576 @cindex start symbol
577 One nonterminal symbol must be distinguished as the special one which
578 defines a complete utterance in the language. It is called the @dfn{start
579 symbol}. In a compiler, this means a complete input program. In the C
580 language, the nonterminal symbol `sequence of definitions and declarations'
581 plays this role.
582
583 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
584 program---but it is not valid as an @emph{entire} C program. In the
585 context-free grammar of C, this follows from the fact that `expression' is
586 not the start symbol.
587
588 The Bison parser reads a sequence of tokens as its input, and groups the
589 tokens using the grammar rules. If the input is valid, the end result is
590 that the entire token sequence reduces to a single grouping whose symbol is
591 the grammar's start symbol. If we use a grammar for C, the entire input
592 must be a `sequence of definitions and declarations'. If not, the parser
593 reports a syntax error.
594
595 @node Grammar in Bison
596 @section From Formal Rules to Bison Input
597 @cindex Bison grammar
598 @cindex grammar, Bison
599 @cindex formal grammar
600
601 A formal grammar is a mathematical construct. To define the language
602 for Bison, you must write a file expressing the grammar in Bison syntax:
603 a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
604
605 A nonterminal symbol in the formal grammar is represented in Bison input
606 as an identifier, like an identifier in C@. By convention, it should be
607 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
608
609 The Bison representation for a terminal symbol is also called a @dfn{token
610 type}. Token types as well can be represented as C-like identifiers. By
611 convention, these identifiers should be upper case to distinguish them from
612 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
613 @code{RETURN}. A terminal symbol that stands for a particular keyword in
614 the language should be named after that keyword converted to upper case.
615 The terminal symbol @code{error} is reserved for error recovery.
616 @xref{Symbols}.
617
618 A terminal symbol can also be represented as a character literal, just like
619 a C character constant. You should do this whenever a token is just a
620 single character (parenthesis, plus-sign, etc.): use that same character in
621 a literal as the terminal symbol for that token.
622
623 A third way to represent a terminal symbol is with a C string constant
624 containing several characters. @xref{Symbols}, for more information.
625
626 The grammar rules also have an expression in Bison syntax. For example,
627 here is the Bison rule for a C @code{return} statement. The semicolon in
628 quotes is a literal character token, representing part of the C syntax for
629 the statement; the naked semicolon, and the colon, are Bison punctuation
630 used in every rule.
631
632 @example
633 stmt: RETURN expr ';'
634 ;
635 @end example
636
637 @noindent
638 @xref{Rules, ,Syntax of Grammar Rules}.
639
640 @node Semantic Values
641 @section Semantic Values
642 @cindex semantic value
643 @cindex value, semantic
644
645 A formal grammar selects tokens only by their classifications: for example,
646 if a rule mentions the terminal symbol `integer constant', it means that
647 @emph{any} integer constant is grammatically valid in that position. The
648 precise value of the constant is irrelevant to how to parse the input: if
649 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
650 grammatical.
651
652 But the precise value is very important for what the input means once it is
653 parsed. A compiler is useless if it fails to distinguish between 4, 1 and
654 3989 as constants in the program! Therefore, each token in a Bison grammar
655 has both a token type and a @dfn{semantic value}. @xref{Semantics,
656 ,Defining Language Semantics},
657 for details.
658
659 The token type is a terminal symbol defined in the grammar, such as
660 @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
661 you need to know to decide where the token may validly appear and how to
662 group it with other tokens. The grammar rules know nothing about tokens
663 except their types.
664
665 The semantic value has all the rest of the information about the
666 meaning of the token, such as the value of an integer, or the name of an
667 identifier. (A token such as @code{','} which is just punctuation doesn't
668 need to have any semantic value.)
669
670 For example, an input token might be classified as token type
671 @code{INTEGER} and have the semantic value 4. Another input token might
672 have the same token type @code{INTEGER} but value 3989. When a grammar
673 rule says that @code{INTEGER} is allowed, either of these tokens is
674 acceptable because each is an @code{INTEGER}. When the parser accepts the
675 token, it keeps track of the token's semantic value.
676
677 Each grouping can also have a semantic value as well as its nonterminal
678 symbol. For example, in a calculator, an expression typically has a
679 semantic value that is a number. In a compiler for a programming
680 language, an expression typically has a semantic value that is a tree
681 structure describing the meaning of the expression.
682
683 @node Semantic Actions
684 @section Semantic Actions
685 @cindex semantic actions
686 @cindex actions, semantic
687
688 In order to be useful, a program must do more than parse input; it must
689 also produce some output based on the input. In a Bison grammar, a grammar
690 rule can have an @dfn{action} made up of C statements. Each time the
691 parser recognizes a match for that rule, the action is executed.
692 @xref{Actions}.
693
694 Most of the time, the purpose of an action is to compute the semantic value
695 of the whole construct from the semantic values of its parts. For example,
696 suppose we have a rule which says an expression can be the sum of two
697 expressions. When the parser recognizes such a sum, each of the
698 subexpressions has a semantic value which describes how it was built up.
699 The action for this rule should create a similar sort of value for the
700 newly recognized larger expression.
701
702 For example, here is a rule that says an expression can be the sum of
703 two subexpressions:
704
705 @example
706 expr: expr '+' expr @{ $$ = $1 + $3; @}
707 ;
708 @end example
709
710 @noindent
711 The action says how to produce the semantic value of the sum expression
712 from the values of the two subexpressions.
713
714 @node GLR Parsers
715 @section Writing GLR Parsers
716 @cindex GLR parsing
717 @cindex generalized LR (GLR) parsing
718 @findex %glr-parser
719 @cindex conflicts
720 @cindex shift/reduce conflicts
721 @cindex reduce/reduce conflicts
722
723 In some grammars, Bison's deterministic
724 LR(1) parsing algorithm cannot decide whether to apply a
725 certain grammar rule at a given point. That is, it may not be able to
726 decide (on the basis of the input read so far) which of two possible
727 reductions (applications of a grammar rule) applies, or whether to apply
728 a reduction or read more of the input and apply a reduction later in the
729 input. These are known respectively as @dfn{reduce/reduce} conflicts
730 (@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
731 (@pxref{Shift/Reduce}).
732
733 To use a grammar that is not easily modified to be LR(1), a
734 more general parsing algorithm is sometimes necessary. If you include
735 @code{%glr-parser} among the Bison declarations in your file
736 (@pxref{Grammar Outline}), the result is a Generalized LR
737 (GLR) parser. These parsers handle Bison grammars that
738 contain no unresolved conflicts (i.e., after applying precedence
739 declarations) identically to deterministic parsers. However, when
740 faced with unresolved shift/reduce and reduce/reduce conflicts,
741 GLR parsers use the simple expedient of doing both,
742 effectively cloning the parser to follow both possibilities. Each of
743 the resulting parsers can again split, so that at any given time, there
744 can be any number of possible parses being explored. The parsers
745 proceed in lockstep; that is, all of them consume (shift) a given input
746 symbol before any of them proceed to the next. Each of the cloned
747 parsers eventually meets one of two possible fates: either it runs into
748 a parsing error, in which case it simply vanishes, or it merges with
749 another parser, because the two of them have reduced the input to an
750 identical set of symbols.
751
752 During the time that there are multiple parsers, semantic actions are
753 recorded, but not performed. When a parser disappears, its recorded
754 semantic actions disappear as well, and are never performed. When a
755 reduction makes two parsers identical, causing them to merge, Bison
756 records both sets of semantic actions. Whenever the last two parsers
757 merge, reverting to the single-parser case, Bison resolves all the
758 outstanding actions either by precedences given to the grammar rules
759 involved, or by performing both actions, and then calling a designated
760 user-defined function on the resulting values to produce an arbitrary
761 merged result.
762
763 @menu
764 * Simple GLR Parsers:: Using GLR parsers on unambiguous grammars.
765 * Merging GLR Parses:: Using GLR parsers to resolve ambiguities.
766 * GLR Semantic Actions:: Considerations for semantic values and deferred actions.
767 * Semantic Predicates:: Controlling a parse with arbitrary computations.
768 * Compiler Requirements:: GLR parsers require a modern C compiler.
769 @end menu
770
771 @node Simple GLR Parsers
772 @subsection Using GLR on Unambiguous Grammars
773 @cindex GLR parsing, unambiguous grammars
774 @cindex generalized LR (GLR) parsing, unambiguous grammars
775 @findex %glr-parser
776 @findex %expect-rr
777 @cindex conflicts
778 @cindex reduce/reduce conflicts
779 @cindex shift/reduce conflicts
780
781 In the simplest cases, you can use the GLR algorithm
782 to parse grammars that are unambiguous but fail to be LR(1).
783 Such grammars typically require more than one symbol of lookahead.
784
785 Consider a problem that
786 arises in the declaration of enumerated and subrange types in the
787 programming language Pascal. Here are some examples:
788
789 @example
790 type subrange = lo .. hi;
791 type enum = (a, b, c);
792 @end example
793
794 @noindent
795 The original language standard allows only numeric
796 literals and constant identifiers for the subrange bounds (@samp{lo}
797 and @samp{hi}), but Extended Pascal (ISO/IEC
798 10206) and many other
799 Pascal implementations allow arbitrary expressions there. This gives
800 rise to the following situation, containing a superfluous pair of
801 parentheses:
802
803 @example
804 type subrange = (a) .. b;
805 @end example
806
807 @noindent
808 Compare this to the following declaration of an enumerated
809 type with only one value:
810
811 @example
812 type enum = (a);
813 @end example
814
815 @noindent
816 (These declarations are contrived, but they are syntactically
817 valid, and more-complicated cases can come up in practical programs.)
818
819 These two declarations look identical until the @samp{..} token.
820 With normal LR(1) one-token lookahead it is not
821 possible to decide between the two forms when the identifier
822 @samp{a} is parsed. It is, however, desirable
823 for a parser to decide this, since in the latter case
824 @samp{a} must become a new identifier to represent the enumeration
825 value, while in the former case @samp{a} must be evaluated with its
826 current meaning, which may be a constant or even a function call.
827
828 You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
829 to be resolved later, but this typically requires substantial
830 contortions in both semantic actions and large parts of the
831 grammar, where the parentheses are nested in the recursive rules for
832 expressions.
833
834 You might think of using the lexer to distinguish between the two
835 forms by returning different tokens for currently defined and
836 undefined identifiers. But if these declarations occur in a local
837 scope, and @samp{a} is defined in an outer scope, then both forms
838 are possible---either locally redefining @samp{a}, or using the
839 value of @samp{a} from the outer scope. So this approach cannot
840 work.
841
842 A simple solution to this problem is to declare the parser to
843 use the GLR algorithm.
844 When the GLR parser reaches the critical state, it
845 merely splits into two branches and pursues both syntax rules
846 simultaneously. Sooner or later, one of them runs into a parsing
847 error. If there is a @samp{..} token before the next
848 @samp{;}, the rule for enumerated types fails since it cannot
849 accept @samp{..} anywhere; otherwise, the subrange type rule
850 fails since it requires a @samp{..} token. So one of the branches
851 fails silently, and the other one continues normally, performing
852 all the intermediate actions that were postponed during the split.
853
854 If the input is syntactically incorrect, both branches fail and the parser
855 reports a syntax error as usual.
856
857 The effect of all this is that the parser seems to ``guess'' the
858 correct branch to take, or in other words, it seems to use more
859 lookahead than the underlying LR(1) algorithm actually allows
860 for. In this example, LR(2) would suffice, but also some cases
861 that are not LR(@math{k}) for any @math{k} can be handled this way.
862
863 In general, a GLR parser can take quadratic or cubic worst-case time,
864 and the current Bison parser even takes exponential time and space
865 for some grammars. In practice, this rarely happens, and for many
866 grammars it is possible to prove that it cannot happen.
867 The present example contains only one conflict between two
868 rules, and the type-declaration context containing the conflict
869 cannot be nested. So the number of
870 branches that can exist at any time is limited by the constant 2,
871 and the parsing time is still linear.
872
873 Here is a Bison grammar corresponding to the example above. It
874 parses a vastly simplified form of Pascal type declarations.
875
876 @example
877 %token TYPE DOTDOT ID
878
879 @group
880 %left '+' '-'
881 %left '*' '/'
882 @end group
883
884 %%
885
886 @group
887 type_decl : TYPE ID '=' type ';'
888 ;
889 @end group
890
891 @group
892 type : '(' id_list ')'
893 | expr DOTDOT expr
894 ;
895 @end group
896
897 @group
898 id_list : ID
899 | id_list ',' ID
900 ;
901 @end group
902
903 @group
904 expr : '(' expr ')'
905 | expr '+' expr
906 | expr '-' expr
907 | expr '*' expr
908 | expr '/' expr
909 | ID
910 ;
911 @end group
912 @end example
913
914 When used as a normal LR(1) grammar, Bison correctly complains
915 about one reduce/reduce conflict. In the conflicting situation the
916 parser chooses one of the alternatives, arbitrarily the one
917 declared first. Therefore the following correct input is not
918 recognized:
919
920 @example
921 type t = (a) .. b;
922 @end example
923
924 The parser can be turned into a GLR parser, while also telling Bison
925 to be silent about the one known reduce/reduce conflict, by adding
926 these two declarations to the Bison grammar file (before the first
927 @samp{%%}):
928
929 @example
930 %glr-parser
931 %expect-rr 1
932 @end example
933
934 @noindent
935 No change in the grammar itself is required. Now the
936 parser recognizes all valid declarations, according to the
937 limited syntax above, transparently. In fact, the user does not even
938 notice when the parser splits.
939
940 So here we have a case where we can use the benefits of GLR,
941 almost without disadvantages. Even in simple cases like this, however,
942 there are at least two potential problems to beware. First, always
943 analyze the conflicts reported by Bison to make sure that GLR
944 splitting is only done where it is intended. A GLR parser
945 splitting inadvertently may cause problems less obvious than an
946 LR parser statically choosing the wrong alternative in a
947 conflict. Second, consider interactions with the lexer (@pxref{Semantic
948 Tokens}) with great care. Since a split parser consumes tokens without
949 performing any actions during the split, the lexer cannot obtain
950 information via parser actions. Some cases of lexer interactions can be
951 eliminated by using GLR to shift the complications from the
952 lexer to the parser. You must check the remaining cases for
953 correctness.
954
955 In our example, it would be safe for the lexer to return tokens based on
956 their current meanings in some symbol table, because no new symbols are
957 defined in the middle of a type declaration. Though it is possible for
958 a parser to define the enumeration constants as they are parsed, before
959 the type declaration is completed, it actually makes no difference since
960 they cannot be used within the same enumerated type declaration.
961
962 @node Merging GLR Parses
963 @subsection Using GLR to Resolve Ambiguities
964 @cindex GLR parsing, ambiguous grammars
965 @cindex generalized LR (GLR) parsing, ambiguous grammars
966 @findex %dprec
967 @findex %merge
968 @cindex conflicts
969 @cindex reduce/reduce conflicts
970
971 Let's consider an example, vastly simplified from a C++ grammar.
972
973 @example
974 %@{
975 #include <stdio.h>
976 #define YYSTYPE char const *
977 int yylex (void);
978 void yyerror (char const *);
979 %@}
980
981 %token TYPENAME ID
982
983 %right '='
984 %left '+'
985
986 %glr-parser
987
988 %%
989
990 prog :
991 | prog stmt @{ printf ("\n"); @}
992 ;
993
994 stmt : expr ';' %dprec 1
995 | decl %dprec 2
996 ;
997
998 expr : ID @{ printf ("%s ", $$); @}
999 | TYPENAME '(' expr ')'
1000 @{ printf ("%s <cast> ", $1); @}
1001 | expr '+' expr @{ printf ("+ "); @}
1002 | expr '=' expr @{ printf ("= "); @}
1003 ;
1004
1005 decl : TYPENAME declarator ';'
1006 @{ printf ("%s <declare> ", $1); @}
1007 | TYPENAME declarator '=' expr ';'
1008 @{ printf ("%s <init-declare> ", $1); @}
1009 ;
1010
1011 declarator : ID @{ printf ("\"%s\" ", $1); @}
1012 | '(' declarator ')'
1013 ;
1014 @end example
1015
1016 @noindent
1017 This models a problematic part of the C++ grammar---the ambiguity between
1018 certain declarations and statements. For example,
1019
1020 @example
1021 T (x) = y+z;
1022 @end example
1023
1024 @noindent
1025 parses as either an @code{expr} or a @code{stmt}
1026 (assuming that @samp{T} is recognized as a @code{TYPENAME} and
1027 @samp{x} as an @code{ID}).
1028 Bison detects this as a reduce/reduce conflict between the rules
1029 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
1030 time it encounters @code{x} in the example above. Since this is a
1031 GLR parser, it therefore splits the problem into two parses, one for
1032 each choice of resolving the reduce/reduce conflict.
1033 Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1034 however, neither of these parses ``dies,'' because the grammar as it stands is
1035 ambiguous. One of the parsers eventually reduces @code{stmt : expr ';'} and
1036 the other reduces @code{stmt : decl}, after which both parsers are in an
1037 identical state: they've seen @samp{prog stmt} and have the same unprocessed
1038 input remaining. We say that these parses have @dfn{merged.}
1039
1040 At this point, the GLR parser requires a specification in the
1041 grammar of how to choose between the competing parses.
1042 In the example above, the two @code{%dprec}
1043 declarations specify that Bison is to give precedence
1044 to the parse that interprets the example as a
1045 @code{decl}, which implies that @code{x} is a declarator.
1046 The parser therefore prints
1047
1048 @example
1049 "x" y z + T <init-declare>
1050 @end example
1051
1052 The @code{%dprec} declarations only come into play when more than one
1053 parse survives. Consider a different input string for this parser:
1054
1055 @example
1056 T (x) + y;
1057 @end example
1058
1059 @noindent
1060 This is another example of using GLR to parse an unambiguous
1061 construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
1062 Here, there is no ambiguity (this cannot be parsed as a declaration).
1063 However, at the time the Bison parser encounters @code{x}, it does not
1064 have enough information to resolve the reduce/reduce conflict (again,
1065 between @code{x} as an @code{expr} or a @code{declarator}). In this
1066 case, no precedence declaration is used. Again, the parser splits
1067 into two, one assuming that @code{x} is an @code{expr}, and the other
1068 assuming @code{x} is a @code{declarator}. The second of these parsers
1069 then vanishes when it sees @code{+}, and the parser prints
1070
1071 @example
1072 x T <cast> y +
1073 @end example
1074
1075 Suppose that instead of resolving the ambiguity, you wanted to see all
1076 the possibilities. For this purpose, you must merge the semantic
1077 actions of the two possible parsers, rather than choosing one over the
1078 other. To do so, you could change the declaration of @code{stmt} as
1079 follows:
1080
1081 @example
1082 stmt : expr ';' %merge <stmtMerge>
1083 | decl %merge <stmtMerge>
1084 ;
1085 @end example
1086
1087 @noindent
1088 and define the @code{stmtMerge} function as:
1089
1090 @example
1091 static YYSTYPE
1092 stmtMerge (YYSTYPE x0, YYSTYPE x1)
1093 @{
1094 printf ("<OR> ");
1095 return "";
1096 @}
1097 @end example
1098
1099 @noindent
1100 with an accompanying forward declaration
1101 in the C declarations at the beginning of the file:
1102
1103 @example
1104 %@{
1105 #define YYSTYPE char const *
1106 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
1107 %@}
1108 @end example
1109
1110 @noindent
1111 With these declarations, the resulting parser parses the first example
1112 as both an @code{expr} and a @code{decl}, and prints
1113
1114 @example
1115 "x" y z + T <init-declare> x T <cast> y z + = <OR>
1116 @end example
1117
1118 Bison requires that all of the
1119 productions that participate in any particular merge have identical
1120 @samp{%merge} clauses. Otherwise, the ambiguity would be unresolvable,
1121 and the parser will report an error during any parse that results in
1122 the offending merge.
1123
1124 @node GLR Semantic Actions
1125 @subsection GLR Semantic Actions
1126
1127 The nature of GLR parsing and the structure of the generated
1128 parsers give rise to certain restrictions on semantic values and actions.
1129
1130 @subsubsection Deferred semantic actions
1131 @cindex deferred semantic actions
1132 By definition, a deferred semantic action is not performed at the same time as
1133 the associated reduction.
1134 This raises caveats for several Bison features you might use in a semantic
1135 action in a GLR parser.
1136
1137 @vindex yychar
1138 @cindex GLR parsers and @code{yychar}
1139 @vindex yylval
1140 @cindex GLR parsers and @code{yylval}
1141 @vindex yylloc
1142 @cindex GLR parsers and @code{yylloc}
1143 In any semantic action, you can examine @code{yychar} to determine the type of
1144 the lookahead token present at the time of the associated reduction.
1145 After checking that @code{yychar} is not set to @code{YYEMPTY} or @code{YYEOF},
1146 you can then examine @code{yylval} and @code{yylloc} to determine the
1147 lookahead token's semantic value and location, if any.
1148 In a nondeferred semantic action, you can also modify any of these variables to
1149 influence syntax analysis.
1150 @xref{Lookahead, ,Lookahead Tokens}.
1151
1152 @findex yyclearin
1153 @cindex GLR parsers and @code{yyclearin}
1154 In a deferred semantic action, it's too late to influence syntax analysis.
1155 In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1156 shallow copies of the values they had at the time of the associated reduction.
1157 For this reason alone, modifying them is dangerous.
1158 Moreover, the result of modifying them is undefined and subject to change with
1159 future versions of Bison.
1160 For example, if a semantic action might be deferred, you should never write it
1161 to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1162 memory referenced by @code{yylval}.
1163
1164 @subsubsection YYERROR
1165 @findex YYERROR
1166 @cindex GLR parsers and @code{YYERROR}
1167 Another Bison feature requiring special consideration is @code{YYERROR}
1168 (@pxref{Action Features}), which you can invoke in a semantic action to
1169 initiate error recovery.
1170 During deterministic GLR operation, the effect of @code{YYERROR} is
1171 the same as its effect in a deterministic parser.
1172 The effect in a deferred action is similar, but the precise point of the
1173 error is undefined; instead, the parser reverts to deterministic operation,
1174 selecting an unspecified stack on which to continue with a syntax error.
1175 In a semantic predicate (see @ref{Semantic Predicates}) during nondeterministic
1176 parsing, @code{YYERROR} silently prunes
1177 the parse that invoked the test.
1178
1179 @subsubsection Restrictions on semantic values and locations
1180 GLR parsers require that you use POD (Plain Old Data) types for
1181 semantic values and location types when using the generated parsers as
1182 C++ code.
1183
1184 @node Semantic Predicates
1185 @subsection Controlling a Parse with Arbitrary Predicates
1186 @findex %?
1187 @cindex Semantic predicates in GLR parsers
1188
1189 In addition to the @code{%dprec} and @code{%merge} directives,
1190 GLR parsers
1191 allow you to reject parses on the basis of arbitrary computations executed
1192 in user code, without having Bison treat this rejection as an error
1193 if there are alternative parses. (This feature is experimental and may
1194 evolve. We welcome user feedback.) For example,
1195
1196 @smallexample
1197 widget :
1198 %?@{ new_syntax @} "widget" id new_args @{ $$ = f($3, $4); @}
1199 | %?@{ !new_syntax @} "widget" id old_args @{ $$ = f($3, $4); @}
1200 ;
1201 @end smallexample
1202
1203 @noindent
1204 is one way to allow the same parser to handle two different syntaxes for
1205 widgets. The clause preceded by @code{%?} is treated like an ordinary
1206 action, except that its text is treated as an expression and is always
1207 evaluated immediately (even when in nondeterministic mode). If the
1208 expression yields 0 (false), the clause is treated as a syntax error,
1209 which, in a nondeterministic parser, causes the stack in which it is reduced
1210 to die. In a deterministic parser, it acts like YYERROR.
1211
1212 As the example shows, predicates otherwise look like semantic actions, and
1213 therefore you must be take them into account when determining the numbers
1214 to use for denoting the semantic values of right-hand side symbols.
1215 Predicate actions, however, have no defined value, and may not be given
1216 labels.
1217
1218 There is a subtle difference between semantic predicates and ordinary
1219 actions in nondeterministic mode, since the latter are deferred.
1220 For example, we could try to rewrite the previous example as
1221
1222 @smallexample
1223 widget :
1224 @{ if (!new_syntax) YYERROR; @} "widget" id new_args @{ $$ = f($3, $4); @}
1225 | @{ if (new_syntax) YYERROR; @} "widget" id old_args @{ $$ = f($3, $4); @}
1226 ;
1227 @end smallexample
1228
1229 @noindent
1230 (reversing the sense of the predicate tests to cause an error when they are
1231 false). However, this
1232 does @emph{not} have the same effect if @code{new_args} and @code{old_args}
1233 have overlapping syntax.
1234 Since the mid-rule actions testing @code{new_syntax} are deferred,
1235 a GLR parser first encounters the unresolved ambiguous reduction
1236 for cases where @code{new_args} and @code{old_args} recognize the same string
1237 @emph{before} performing the tests of @code{new_syntax}. It therefore
1238 reports an error.
1239
1240 Finally, be careful in writing predicates: deferred actions have not been
1241 evaluated, so that using them in a predicate will have undefined effects.
1242
1243 @node Compiler Requirements
1244 @subsection Considerations when Compiling GLR Parsers
1245 @cindex @code{inline}
1246 @cindex GLR parsers and @code{inline}
1247
1248 The GLR parsers require a compiler for ISO C89 or
1249 later. In addition, they use the @code{inline} keyword, which is not
1250 C89, but is C99 and is a common extension in pre-C99 compilers. It is
1251 up to the user of these parsers to handle
1252 portability issues. For instance, if using Autoconf and the Autoconf
1253 macro @code{AC_C_INLINE}, a mere
1254
1255 @example
1256 %@{
1257 #include <config.h>
1258 %@}
1259 @end example
1260
1261 @noindent
1262 will suffice. Otherwise, we suggest
1263
1264 @example
1265 %@{
1266 #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
1267 #define inline
1268 #endif
1269 %@}
1270 @end example
1271
1272 @node Locations Overview
1273 @section Locations
1274 @cindex location
1275 @cindex textual location
1276 @cindex location, textual
1277
1278 Many applications, like interpreters or compilers, have to produce verbose
1279 and useful error messages. To achieve this, one must be able to keep track of
1280 the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
1281 Bison provides a mechanism for handling these locations.
1282
1283 Each token has a semantic value. In a similar fashion, each token has an
1284 associated location, but the type of locations is the same for all tokens and
1285 groupings. Moreover, the output parser is equipped with a default data
1286 structure for storing locations (@pxref{Locations}, for more details).
1287
1288 Like semantic values, locations can be reached in actions using a dedicated
1289 set of constructs. In the example above, the location of the whole grouping
1290 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1291 @code{@@3}.
1292
1293 When a rule is matched, a default action is used to compute the semantic value
1294 of its left hand side (@pxref{Actions}). In the same way, another default
1295 action is used for locations. However, the action for locations is general
1296 enough for most cases, meaning there is usually no need to describe for each
1297 rule how @code{@@$} should be formed. When building a new location for a given
1298 grouping, the default behavior of the output parser is to take the beginning
1299 of the first symbol, and the end of the last symbol.
1300
1301 @node Bison Parser
1302 @section Bison Output: the Parser Implementation File
1303 @cindex Bison parser
1304 @cindex Bison utility
1305 @cindex lexical analyzer, purpose
1306 @cindex parser
1307
1308 When you run Bison, you give it a Bison grammar file as input. The
1309 most important output is a C source file that implements a parser for
1310 the language described by the grammar. This parser is called a
1311 @dfn{Bison parser}, and this file is called a @dfn{Bison parser
1312 implementation file}. Keep in mind that the Bison utility and the
1313 Bison parser are two distinct programs: the Bison utility is a program
1314 whose output is the Bison parser implementation file that becomes part
1315 of your program.
1316
1317 The job of the Bison parser is to group tokens into groupings according to
1318 the grammar rules---for example, to build identifiers and operators into
1319 expressions. As it does this, it runs the actions for the grammar rules it
1320 uses.
1321
1322 The tokens come from a function called the @dfn{lexical analyzer} that
1323 you must supply in some fashion (such as by writing it in C). The Bison
1324 parser calls the lexical analyzer each time it wants a new token. It
1325 doesn't know what is ``inside'' the tokens (though their semantic values
1326 may reflect this). Typically the lexical analyzer makes the tokens by
1327 parsing characters of text, but Bison does not depend on this.
1328 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
1329
1330 The Bison parser implementation file is C code which defines a
1331 function named @code{yyparse} which implements that grammar. This
1332 function does not make a complete C program: you must supply some
1333 additional functions. One is the lexical analyzer. Another is an
1334 error-reporting function which the parser calls to report an error.
1335 In addition, a complete C program must start with a function called
1336 @code{main}; you have to provide this, and arrange for it to call
1337 @code{yyparse} or the parser will never run. @xref{Interface, ,Parser
1338 C-Language Interface}.
1339
1340 Aside from the token type names and the symbols in the actions you
1341 write, all symbols defined in the Bison parser implementation file
1342 itself begin with @samp{yy} or @samp{YY}. This includes interface
1343 functions such as the lexical analyzer function @code{yylex}, the
1344 error reporting function @code{yyerror} and the parser function
1345 @code{yyparse} itself. This also includes numerous identifiers used
1346 for internal purposes. Therefore, you should avoid using C
1347 identifiers starting with @samp{yy} or @samp{YY} in the Bison grammar
1348 file except for the ones defined in this manual. Also, you should
1349 avoid using the C identifiers @samp{malloc} and @samp{free} for
1350 anything other than their usual meanings.
1351
1352 In some cases the Bison parser implementation file includes system
1353 headers, and in those cases your code should respect the identifiers
1354 reserved by those headers. On some non-GNU hosts, @code{<alloca.h>},
1355 @code{<malloc.h>}, @code{<stddef.h>}, and @code{<stdlib.h>} are
1356 included as needed to declare memory allocators and related types.
1357 @code{<libintl.h>} is included if message translation is in use
1358 (@pxref{Internationalization}). Other system headers may be included
1359 if you define @code{YYDEBUG} to a nonzero value (@pxref{Tracing,
1360 ,Tracing Your Parser}).
1361
1362 @node Stages
1363 @section Stages in Using Bison
1364 @cindex stages in using Bison
1365 @cindex using Bison
1366
1367 The actual language-design process using Bison, from grammar specification
1368 to a working compiler or interpreter, has these parts:
1369
1370 @enumerate
1371 @item
1372 Formally specify the grammar in a form recognized by Bison
1373 (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
1374 in the language, describe the action that is to be taken when an
1375 instance of that rule is recognized. The action is described by a
1376 sequence of C statements.
1377
1378 @item
1379 Write a lexical analyzer to process input and pass tokens to the parser.
1380 The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
1381 Lexical Analyzer Function @code{yylex}}). It could also be produced
1382 using Lex, but the use of Lex is not discussed in this manual.
1383
1384 @item
1385 Write a controlling function that calls the Bison-produced parser.
1386
1387 @item
1388 Write error-reporting routines.
1389 @end enumerate
1390
1391 To turn this source code as written into a runnable program, you
1392 must follow these steps:
1393
1394 @enumerate
1395 @item
1396 Run Bison on the grammar to produce the parser.
1397
1398 @item
1399 Compile the code output by Bison, as well as any other source files.
1400
1401 @item
1402 Link the object files to produce the finished product.
1403 @end enumerate
1404
1405 @node Grammar Layout
1406 @section The Overall Layout of a Bison Grammar
1407 @cindex grammar file
1408 @cindex file format
1409 @cindex format of grammar file
1410 @cindex layout of Bison grammar
1411
1412 The input file for the Bison utility is a @dfn{Bison grammar file}. The
1413 general form of a Bison grammar file is as follows:
1414
1415 @example
1416 %@{
1417 @var{Prologue}
1418 %@}
1419
1420 @var{Bison declarations}
1421
1422 %%
1423 @var{Grammar rules}
1424 %%
1425 @var{Epilogue}
1426 @end example
1427
1428 @noindent
1429 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1430 in every Bison grammar file to separate the sections.
1431
1432 The prologue may define types and variables used in the actions. You can
1433 also use preprocessor commands to define macros used there, and use
1434 @code{#include} to include header files that do any of these things.
1435 You need to declare the lexical analyzer @code{yylex} and the error
1436 printer @code{yyerror} here, along with any other global identifiers
1437 used by the actions in the grammar rules.
1438
1439 The Bison declarations declare the names of the terminal and nonterminal
1440 symbols, and may also describe operator precedence and the data types of
1441 semantic values of various symbols.
1442
1443 The grammar rules define how to construct each nonterminal symbol from its
1444 parts.
1445
1446 The epilogue can contain any code you want to use. Often the
1447 definitions of functions declared in the prologue go here. In a
1448 simple program, all the rest of the program can go here.
1449
1450 @node Examples
1451 @chapter Examples
1452 @cindex simple examples
1453 @cindex examples, simple
1454
1455 Now we show and explain three sample programs written using Bison: a
1456 reverse polish notation calculator, an algebraic (infix) notation
1457 calculator, and a multi-function calculator. All three have been tested
1458 under BSD Unix 4.3; each produces a usable, though limited, interactive
1459 desk-top calculator.
1460
1461 These examples are simple, but Bison grammars for real programming
1462 languages are written the same way. You can copy these examples into a
1463 source file to try them.
1464
1465 @menu
1466 * RPN Calc:: Reverse polish notation calculator;
1467 a first example with no operator precedence.
1468 * Infix Calc:: Infix (algebraic) notation calculator.
1469 Operator precedence is introduced.
1470 * Simple Error Recovery:: Continuing after syntax errors.
1471 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1472 * Multi-function Calc:: Calculator with memory and trig functions.
1473 It uses multiple data-types for semantic values.
1474 * Exercises:: Ideas for improving the multi-function calculator.
1475 @end menu
1476
1477 @node RPN Calc
1478 @section Reverse Polish Notation Calculator
1479 @cindex reverse polish notation
1480 @cindex polish notation calculator
1481 @cindex @code{rpcalc}
1482 @cindex calculator, simple
1483
1484 The first example is that of a simple double-precision @dfn{reverse polish
1485 notation} calculator (a calculator using postfix operators). This example
1486 provides a good starting point, since operator precedence is not an issue.
1487 The second example will illustrate how operator precedence is handled.
1488
1489 The source code for this calculator is named @file{rpcalc.y}. The
1490 @samp{.y} extension is a convention used for Bison grammar files.
1491
1492 @menu
1493 * Rpcalc Declarations:: Prologue (declarations) for rpcalc.
1494 * Rpcalc Rules:: Grammar Rules for rpcalc, with explanation.
1495 * Rpcalc Lexer:: The lexical analyzer.
1496 * Rpcalc Main:: The controlling function.
1497 * Rpcalc Error:: The error reporting function.
1498 * Rpcalc Generate:: Running Bison on the grammar file.
1499 * Rpcalc Compile:: Run the C compiler on the output code.
1500 @end menu
1501
1502 @node Rpcalc Declarations
1503 @subsection Declarations for @code{rpcalc}
1504
1505 Here are the C and Bison declarations for the reverse polish notation
1506 calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1507
1508 @example
1509 /* Reverse polish notation calculator. */
1510
1511 %@{
1512 #define YYSTYPE double
1513 #include <math.h>
1514 int yylex (void);
1515 void yyerror (char const *);
1516 %@}
1517
1518 %token NUM
1519
1520 %% /* Grammar rules and actions follow. */
1521 @end example
1522
1523 The declarations section (@pxref{Prologue, , The prologue}) contains two
1524 preprocessor directives and two forward declarations.
1525
1526 The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1527 specifying the C data type for semantic values of both tokens and
1528 groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1529 Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1530 don't define it, @code{int} is the default. Because we specify
1531 @code{double}, each token and each expression has an associated value,
1532 which is a floating point number.
1533
1534 The @code{#include} directive is used to declare the exponentiation
1535 function @code{pow}.
1536
1537 The forward declarations for @code{yylex} and @code{yyerror} are
1538 needed because the C language requires that functions be declared
1539 before they are used. These functions will be defined in the
1540 epilogue, but the parser calls them so they must be declared in the
1541 prologue.
1542
1543 The second section, Bison declarations, provides information to Bison
1544 about the token types (@pxref{Bison Declarations, ,The Bison
1545 Declarations Section}). Each terminal symbol that is not a
1546 single-character literal must be declared here. (Single-character
1547 literals normally don't need to be declared.) In this example, all the
1548 arithmetic operators are designated by single-character literals, so the
1549 only terminal symbol that needs to be declared is @code{NUM}, the token
1550 type for numeric constants.
1551
1552 @node Rpcalc Rules
1553 @subsection Grammar Rules for @code{rpcalc}
1554
1555 Here are the grammar rules for the reverse polish notation calculator.
1556
1557 @example
1558 input: /* empty */
1559 | input line
1560 ;
1561
1562 line: '\n'
1563 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1564 ;
1565
1566 exp: NUM @{ $$ = $1; @}
1567 | exp exp '+' @{ $$ = $1 + $2; @}
1568 | exp exp '-' @{ $$ = $1 - $2; @}
1569 | exp exp '*' @{ $$ = $1 * $2; @}
1570 | exp exp '/' @{ $$ = $1 / $2; @}
1571 /* Exponentiation */
1572 | exp exp '^' @{ $$ = pow ($1, $2); @}
1573 /* Unary minus */
1574 | exp 'n' @{ $$ = -$1; @}
1575 ;
1576 %%
1577 @end example
1578
1579 The groupings of the rpcalc ``language'' defined here are the expression
1580 (given the name @code{exp}), the line of input (@code{line}), and the
1581 complete input transcript (@code{input}). Each of these nonterminal
1582 symbols has several alternate rules, joined by the vertical bar @samp{|}
1583 which is read as ``or''. The following sections explain what these rules
1584 mean.
1585
1586 The semantics of the language is determined by the actions taken when a
1587 grouping is recognized. The actions are the C code that appears inside
1588 braces. @xref{Actions}.
1589
1590 You must specify these actions in C, but Bison provides the means for
1591 passing semantic values between the rules. In each action, the
1592 pseudo-variable @code{$$} stands for the semantic value for the grouping
1593 that the rule is going to construct. Assigning a value to @code{$$} is the
1594 main job of most actions. The semantic values of the components of the
1595 rule are referred to as @code{$1}, @code{$2}, and so on.
1596
1597 @menu
1598 * Rpcalc Input::
1599 * Rpcalc Line::
1600 * Rpcalc Expr::
1601 @end menu
1602
1603 @node Rpcalc Input
1604 @subsubsection Explanation of @code{input}
1605
1606 Consider the definition of @code{input}:
1607
1608 @example
1609 input: /* empty */
1610 | input line
1611 ;
1612 @end example
1613
1614 This definition reads as follows: ``A complete input is either an empty
1615 string, or a complete input followed by an input line''. Notice that
1616 ``complete input'' is defined in terms of itself. This definition is said
1617 to be @dfn{left recursive} since @code{input} appears always as the
1618 leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1619
1620 The first alternative is empty because there are no symbols between the
1621 colon and the first @samp{|}; this means that @code{input} can match an
1622 empty string of input (no tokens). We write the rules this way because it
1623 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1624 It's conventional to put an empty alternative first and write the comment
1625 @samp{/* empty */} in it.
1626
1627 The second alternate rule (@code{input line}) handles all nontrivial input.
1628 It means, ``After reading any number of lines, read one more line if
1629 possible.'' The left recursion makes this rule into a loop. Since the
1630 first alternative matches empty input, the loop can be executed zero or
1631 more times.
1632
1633 The parser function @code{yyparse} continues to process input until a
1634 grammatical error is seen or the lexical analyzer says there are no more
1635 input tokens; we will arrange for the latter to happen at end-of-input.
1636
1637 @node Rpcalc Line
1638 @subsubsection Explanation of @code{line}
1639
1640 Now consider the definition of @code{line}:
1641
1642 @example
1643 line: '\n'
1644 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1645 ;
1646 @end example
1647
1648 The first alternative is a token which is a newline character; this means
1649 that rpcalc accepts a blank line (and ignores it, since there is no
1650 action). The second alternative is an expression followed by a newline.
1651 This is the alternative that makes rpcalc useful. The semantic value of
1652 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1653 question is the first symbol in the alternative. The action prints this
1654 value, which is the result of the computation the user asked for.
1655
1656 This action is unusual because it does not assign a value to @code{$$}. As
1657 a consequence, the semantic value associated with the @code{line} is
1658 uninitialized (its value will be unpredictable). This would be a bug if
1659 that value were ever used, but we don't use it: once rpcalc has printed the
1660 value of the user's input line, that value is no longer needed.
1661
1662 @node Rpcalc Expr
1663 @subsubsection Explanation of @code{expr}
1664
1665 The @code{exp} grouping has several rules, one for each kind of expression.
1666 The first rule handles the simplest expressions: those that are just numbers.
1667 The second handles an addition-expression, which looks like two expressions
1668 followed by a plus-sign. The third handles subtraction, and so on.
1669
1670 @example
1671 exp: NUM
1672 | exp exp '+' @{ $$ = $1 + $2; @}
1673 | exp exp '-' @{ $$ = $1 - $2; @}
1674 @dots{}
1675 ;
1676 @end example
1677
1678 We have used @samp{|} to join all the rules for @code{exp}, but we could
1679 equally well have written them separately:
1680
1681 @example
1682 exp: NUM ;
1683 exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1684 exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1685 @dots{}
1686 @end example
1687
1688 Most of the rules have actions that compute the value of the expression in
1689 terms of the value of its parts. For example, in the rule for addition,
1690 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1691 the second one. The third component, @code{'+'}, has no meaningful
1692 associated semantic value, but if it had one you could refer to it as
1693 @code{$3}. When @code{yyparse} recognizes a sum expression using this
1694 rule, the sum of the two subexpressions' values is produced as the value of
1695 the entire expression. @xref{Actions}.
1696
1697 You don't have to give an action for every rule. When a rule has no
1698 action, Bison by default copies the value of @code{$1} into @code{$$}.
1699 This is what happens in the first rule (the one that uses @code{NUM}).
1700
1701 The formatting shown here is the recommended convention, but Bison does
1702 not require it. You can add or change white space as much as you wish.
1703 For example, this:
1704
1705 @example
1706 exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
1707 @end example
1708
1709 @noindent
1710 means the same thing as this:
1711
1712 @example
1713 exp: NUM
1714 | exp exp '+' @{ $$ = $1 + $2; @}
1715 | @dots{}
1716 ;
1717 @end example
1718
1719 @noindent
1720 The latter, however, is much more readable.
1721
1722 @node Rpcalc Lexer
1723 @subsection The @code{rpcalc} Lexical Analyzer
1724 @cindex writing a lexical analyzer
1725 @cindex lexical analyzer, writing
1726
1727 The lexical analyzer's job is low-level parsing: converting characters
1728 or sequences of characters into tokens. The Bison parser gets its
1729 tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1730 Analyzer Function @code{yylex}}.
1731
1732 Only a simple lexical analyzer is needed for the RPN
1733 calculator. This
1734 lexical analyzer skips blanks and tabs, then reads in numbers as
1735 @code{double} and returns them as @code{NUM} tokens. Any other character
1736 that isn't part of a number is a separate token. Note that the token-code
1737 for such a single-character token is the character itself.
1738
1739 The return value of the lexical analyzer function is a numeric code which
1740 represents a token type. The same text used in Bison rules to stand for
1741 this token type is also a C expression for the numeric code for the type.
1742 This works in two ways. If the token type is a character literal, then its
1743 numeric code is that of the character; you can use the same
1744 character literal in the lexical analyzer to express the number. If the
1745 token type is an identifier, that identifier is defined by Bison as a C
1746 macro whose definition is the appropriate number. In this example,
1747 therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1748
1749 The semantic value of the token (if it has one) is stored into the
1750 global variable @code{yylval}, which is where the Bison parser will look
1751 for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1752 defined at the beginning of the grammar; @pxref{Rpcalc Declarations,
1753 ,Declarations for @code{rpcalc}}.)
1754
1755 A token type code of zero is returned if the end-of-input is encountered.
1756 (Bison recognizes any nonpositive value as indicating end-of-input.)
1757
1758 Here is the code for the lexical analyzer:
1759
1760 @example
1761 @group
1762 /* The lexical analyzer returns a double floating point
1763 number on the stack and the token NUM, or the numeric code
1764 of the character read if not a number. It skips all blanks
1765 and tabs, and returns 0 for end-of-input. */
1766
1767 #include <ctype.h>
1768 @end group
1769
1770 @group
1771 int
1772 yylex (void)
1773 @{
1774 int c;
1775
1776 /* Skip white space. */
1777 while ((c = getchar ()) == ' ' || c == '\t')
1778 ;
1779 @end group
1780 @group
1781 /* Process numbers. */
1782 if (c == '.' || isdigit (c))
1783 @{
1784 ungetc (c, stdin);
1785 scanf ("%lf", &yylval);
1786 return NUM;
1787 @}
1788 @end group
1789 @group
1790 /* Return end-of-input. */
1791 if (c == EOF)
1792 return 0;
1793 /* Return a single char. */
1794 return c;
1795 @}
1796 @end group
1797 @end example
1798
1799 @node Rpcalc Main
1800 @subsection The Controlling Function
1801 @cindex controlling function
1802 @cindex main function in simple example
1803
1804 In keeping with the spirit of this example, the controlling function is
1805 kept to the bare minimum. The only requirement is that it call
1806 @code{yyparse} to start the process of parsing.
1807
1808 @example
1809 @group
1810 int
1811 main (void)
1812 @{
1813 return yyparse ();
1814 @}
1815 @end group
1816 @end example
1817
1818 @node Rpcalc Error
1819 @subsection The Error Reporting Routine
1820 @cindex error reporting routine
1821
1822 When @code{yyparse} detects a syntax error, it calls the error reporting
1823 function @code{yyerror} to print an error message (usually but not
1824 always @code{"syntax error"}). It is up to the programmer to supply
1825 @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1826 here is the definition we will use:
1827
1828 @example
1829 @group
1830 #include <stdio.h>
1831
1832 /* Called by yyparse on error. */
1833 void
1834 yyerror (char const *s)
1835 @{
1836 fprintf (stderr, "%s\n", s);
1837 @}
1838 @end group
1839 @end example
1840
1841 After @code{yyerror} returns, the Bison parser may recover from the error
1842 and continue parsing if the grammar contains a suitable error rule
1843 (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1844 have not written any error rules in this example, so any invalid input will
1845 cause the calculator program to exit. This is not clean behavior for a
1846 real calculator, but it is adequate for the first example.
1847
1848 @node Rpcalc Generate
1849 @subsection Running Bison to Make the Parser
1850 @cindex running Bison (introduction)
1851
1852 Before running Bison to produce a parser, we need to decide how to
1853 arrange all the source code in one or more source files. For such a
1854 simple example, the easiest thing is to put everything in one file,
1855 the grammar file. The definitions of @code{yylex}, @code{yyerror} and
1856 @code{main} go at the end, in the epilogue of the grammar file
1857 (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1858
1859 For a large project, you would probably have several source files, and use
1860 @code{make} to arrange to recompile them.
1861
1862 With all the source in the grammar file, you use the following command
1863 to convert it into a parser implementation file:
1864
1865 @example
1866 bison @var{file}.y
1867 @end example
1868
1869 @noindent
1870 In this example, the grammar file is called @file{rpcalc.y} (for
1871 ``Reverse Polish @sc{calc}ulator''). Bison produces a parser
1872 implementation file named @file{@var{file}.tab.c}, removing the
1873 @samp{.y} from the grammar file name. The parser implementation file
1874 contains the source code for @code{yyparse}. The additional functions
1875 in the grammar file (@code{yylex}, @code{yyerror} and @code{main}) are
1876 copied verbatim to the parser implementation file.
1877
1878 @node Rpcalc Compile
1879 @subsection Compiling the Parser Implementation File
1880 @cindex compiling the parser
1881
1882 Here is how to compile and run the parser implementation file:
1883
1884 @example
1885 @group
1886 # @r{List files in current directory.}
1887 $ @kbd{ls}
1888 rpcalc.tab.c rpcalc.y
1889 @end group
1890
1891 @group
1892 # @r{Compile the Bison parser.}
1893 # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1894 $ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
1895 @end group
1896
1897 @group
1898 # @r{List files again.}
1899 $ @kbd{ls}
1900 rpcalc rpcalc.tab.c rpcalc.y
1901 @end group
1902 @end example
1903
1904 The file @file{rpcalc} now contains the executable code. Here is an
1905 example session using @code{rpcalc}.
1906
1907 @example
1908 $ @kbd{rpcalc}
1909 @kbd{4 9 +}
1910 13
1911 @kbd{3 7 + 3 4 5 *+-}
1912 -13
1913 @kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
1914 13
1915 @kbd{5 6 / 4 n +}
1916 -3.166666667
1917 @kbd{3 4 ^} @r{Exponentiation}
1918 81
1919 @kbd{^D} @r{End-of-file indicator}
1920 $
1921 @end example
1922
1923 @node Infix Calc
1924 @section Infix Notation Calculator: @code{calc}
1925 @cindex infix notation calculator
1926 @cindex @code{calc}
1927 @cindex calculator, infix notation
1928
1929 We now modify rpcalc to handle infix operators instead of postfix. Infix
1930 notation involves the concept of operator precedence and the need for
1931 parentheses nested to arbitrary depth. Here is the Bison code for
1932 @file{calc.y}, an infix desk-top calculator.
1933
1934 @example
1935 /* Infix notation calculator. */
1936
1937 %@{
1938 #define YYSTYPE double
1939 #include <math.h>
1940 #include <stdio.h>
1941 int yylex (void);
1942 void yyerror (char const *);
1943 %@}
1944
1945 /* Bison declarations. */
1946 %token NUM
1947 %left '-' '+'
1948 %left '*' '/'
1949 %precedence NEG /* negation--unary minus */
1950 %right '^' /* exponentiation */
1951
1952 %% /* The grammar follows. */
1953 input: /* empty */
1954 | input line
1955 ;
1956
1957 line: '\n'
1958 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1959 ;
1960
1961 exp: NUM @{ $$ = $1; @}
1962 | exp '+' exp @{ $$ = $1 + $3; @}
1963 | exp '-' exp @{ $$ = $1 - $3; @}
1964 | exp '*' exp @{ $$ = $1 * $3; @}
1965 | exp '/' exp @{ $$ = $1 / $3; @}
1966 | '-' exp %prec NEG @{ $$ = -$2; @}
1967 | exp '^' exp @{ $$ = pow ($1, $3); @}
1968 | '(' exp ')' @{ $$ = $2; @}
1969 ;
1970 %%
1971 @end example
1972
1973 @noindent
1974 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1975 same as before.
1976
1977 There are two important new features shown in this code.
1978
1979 In the second section (Bison declarations), @code{%left} declares token
1980 types and says they are left-associative operators. The declarations
1981 @code{%left} and @code{%right} (right associativity) take the place of
1982 @code{%token} which is used to declare a token type name without
1983 associativity/precedence. (These tokens are single-character literals, which
1984 ordinarily don't need to be declared. We declare them here to specify
1985 the associativity/precedence.)
1986
1987 Operator precedence is determined by the line ordering of the
1988 declarations; the higher the line number of the declaration (lower on
1989 the page or screen), the higher the precedence. Hence, exponentiation
1990 has the highest precedence, unary minus (@code{NEG}) is next, followed
1991 by @samp{*} and @samp{/}, and so on. Unary minus is not associative,
1992 only precedence matters (@code{%precedence}. @xref{Precedence, ,Operator
1993 Precedence}.
1994
1995 The other important new feature is the @code{%prec} in the grammar
1996 section for the unary minus operator. The @code{%prec} simply instructs
1997 Bison that the rule @samp{| '-' exp} has the same precedence as
1998 @code{NEG}---in this case the next-to-highest. @xref{Contextual
1999 Precedence, ,Context-Dependent Precedence}.
2000
2001 Here is a sample run of @file{calc.y}:
2002
2003 @need 500
2004 @example
2005 $ @kbd{calc}
2006 @kbd{4 + 4.5 - (34/(8*3+-3))}
2007 6.880952381
2008 @kbd{-56 + 2}
2009 -54
2010 @kbd{3 ^ 2}
2011 9
2012 @end example
2013
2014 @node Simple Error Recovery
2015 @section Simple Error Recovery
2016 @cindex error recovery, simple
2017
2018 Up to this point, this manual has not addressed the issue of @dfn{error
2019 recovery}---how to continue parsing after the parser detects a syntax
2020 error. All we have handled is error reporting with @code{yyerror}.
2021 Recall that by default @code{yyparse} returns after calling
2022 @code{yyerror}. This means that an erroneous input line causes the
2023 calculator program to exit. Now we show how to rectify this deficiency.
2024
2025 The Bison language itself includes the reserved word @code{error}, which
2026 may be included in the grammar rules. In the example below it has
2027 been added to one of the alternatives for @code{line}:
2028
2029 @example
2030 @group
2031 line: '\n'
2032 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2033 | error '\n' @{ yyerrok; @}
2034 ;
2035 @end group
2036 @end example
2037
2038 This addition to the grammar allows for simple error recovery in the
2039 event of a syntax error. If an expression that cannot be evaluated is
2040 read, the error will be recognized by the third rule for @code{line},
2041 and parsing will continue. (The @code{yyerror} function is still called
2042 upon to print its message as well.) The action executes the statement
2043 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
2044 that error recovery is complete (@pxref{Error Recovery}). Note the
2045 difference between @code{yyerrok} and @code{yyerror}; neither one is a
2046 misprint.
2047
2048 This form of error recovery deals with syntax errors. There are other
2049 kinds of errors; for example, division by zero, which raises an exception
2050 signal that is normally fatal. A real calculator program must handle this
2051 signal and use @code{longjmp} to return to @code{main} and resume parsing
2052 input lines; it would also have to discard the rest of the current line of
2053 input. We won't discuss this issue further because it is not specific to
2054 Bison programs.
2055
2056 @node Location Tracking Calc
2057 @section Location Tracking Calculator: @code{ltcalc}
2058 @cindex location tracking calculator
2059 @cindex @code{ltcalc}
2060 @cindex calculator, location tracking
2061
2062 This example extends the infix notation calculator with location
2063 tracking. This feature will be used to improve the error messages. For
2064 the sake of clarity, this example is a simple integer calculator, since
2065 most of the work needed to use locations will be done in the lexical
2066 analyzer.
2067
2068 @menu
2069 * Ltcalc Declarations:: Bison and C declarations for ltcalc.
2070 * Ltcalc Rules:: Grammar rules for ltcalc, with explanations.
2071 * Ltcalc Lexer:: The lexical analyzer.
2072 @end menu
2073
2074 @node Ltcalc Declarations
2075 @subsection Declarations for @code{ltcalc}
2076
2077 The C and Bison declarations for the location tracking calculator are
2078 the same as the declarations for the infix notation calculator.
2079
2080 @example
2081 /* Location tracking calculator. */
2082
2083 %@{
2084 #define YYSTYPE int
2085 #include <math.h>
2086 int yylex (void);
2087 void yyerror (char const *);
2088 %@}
2089
2090 /* Bison declarations. */
2091 %token NUM
2092
2093 %left '-' '+'
2094 %left '*' '/'
2095 %precedence NEG
2096 %right '^'
2097
2098 %% /* The grammar follows. */
2099 @end example
2100
2101 @noindent
2102 Note there are no declarations specific to locations. Defining a data
2103 type for storing locations is not needed: we will use the type provided
2104 by default (@pxref{Location Type, ,Data Types of Locations}), which is a
2105 four member structure with the following integer fields:
2106 @code{first_line}, @code{first_column}, @code{last_line} and
2107 @code{last_column}. By conventions, and in accordance with the GNU
2108 Coding Standards and common practice, the line and column count both
2109 start at 1.
2110
2111 @node Ltcalc Rules
2112 @subsection Grammar Rules for @code{ltcalc}
2113
2114 Whether handling locations or not has no effect on the syntax of your
2115 language. Therefore, grammar rules for this example will be very close
2116 to those of the previous example: we will only modify them to benefit
2117 from the new information.
2118
2119 Here, we will use locations to report divisions by zero, and locate the
2120 wrong expressions or subexpressions.
2121
2122 @example
2123 @group
2124 input : /* empty */
2125 | input line
2126 ;
2127 @end group
2128
2129 @group
2130 line : '\n'
2131 | exp '\n' @{ printf ("%d\n", $1); @}
2132 ;
2133 @end group
2134
2135 @group
2136 exp : NUM @{ $$ = $1; @}
2137 | exp '+' exp @{ $$ = $1 + $3; @}
2138 | exp '-' exp @{ $$ = $1 - $3; @}
2139 | exp '*' exp @{ $$ = $1 * $3; @}
2140 @end group
2141 @group
2142 | exp '/' exp
2143 @{
2144 if ($3)
2145 $$ = $1 / $3;
2146 else
2147 @{
2148 $$ = 1;
2149 fprintf (stderr, "%d.%d-%d.%d: division by zero",
2150 @@3.first_line, @@3.first_column,
2151 @@3.last_line, @@3.last_column);
2152 @}
2153 @}
2154 @end group
2155 @group
2156 | '-' exp %prec NEG @{ $$ = -$2; @}
2157 | exp '^' exp @{ $$ = pow ($1, $3); @}
2158 | '(' exp ')' @{ $$ = $2; @}
2159 @end group
2160 @end example
2161
2162 This code shows how to reach locations inside of semantic actions, by
2163 using the pseudo-variables @code{@@@var{n}} for rule components, and the
2164 pseudo-variable @code{@@$} for groupings.
2165
2166 We don't need to assign a value to @code{@@$}: the output parser does it
2167 automatically. By default, before executing the C code of each action,
2168 @code{@@$} is set to range from the beginning of @code{@@1} to the end
2169 of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
2170 can be redefined (@pxref{Location Default Action, , Default Action for
2171 Locations}), and for very specific rules, @code{@@$} can be computed by
2172 hand.
2173
2174 @node Ltcalc Lexer
2175 @subsection The @code{ltcalc} Lexical Analyzer.
2176
2177 Until now, we relied on Bison's defaults to enable location
2178 tracking. The next step is to rewrite the lexical analyzer, and make it
2179 able to feed the parser with the token locations, as it already does for
2180 semantic values.
2181
2182 To this end, we must take into account every single character of the
2183 input text, to avoid the computed locations of being fuzzy or wrong:
2184
2185 @example
2186 @group
2187 int
2188 yylex (void)
2189 @{
2190 int c;
2191 @end group
2192
2193 @group
2194 /* Skip white space. */
2195 while ((c = getchar ()) == ' ' || c == '\t')
2196 ++yylloc.last_column;
2197 @end group
2198
2199 @group
2200 /* Step. */
2201 yylloc.first_line = yylloc.last_line;
2202 yylloc.first_column = yylloc.last_column;
2203 @end group
2204
2205 @group
2206 /* Process numbers. */
2207 if (isdigit (c))
2208 @{
2209 yylval = c - '0';
2210 ++yylloc.last_column;
2211 while (isdigit (c = getchar ()))
2212 @{
2213 ++yylloc.last_column;
2214 yylval = yylval * 10 + c - '0';
2215 @}
2216 ungetc (c, stdin);
2217 return NUM;
2218 @}
2219 @end group
2220
2221 /* Return end-of-input. */
2222 if (c == EOF)
2223 return 0;
2224
2225 /* Return a single char, and update location. */
2226 if (c == '\n')
2227 @{
2228 ++yylloc.last_line;
2229 yylloc.last_column = 0;
2230 @}
2231 else
2232 ++yylloc.last_column;
2233 return c;
2234 @}
2235 @end example
2236
2237 Basically, the lexical analyzer performs the same processing as before:
2238 it skips blanks and tabs, and reads numbers or single-character tokens.
2239 In addition, it updates @code{yylloc}, the global variable (of type
2240 @code{YYLTYPE}) containing the token's location.
2241
2242 Now, each time this function returns a token, the parser has its number
2243 as well as its semantic value, and its location in the text. The last
2244 needed change is to initialize @code{yylloc}, for example in the
2245 controlling function:
2246
2247 @example
2248 @group
2249 int
2250 main (void)
2251 @{
2252 yylloc.first_line = yylloc.last_line = 1;
2253 yylloc.first_column = yylloc.last_column = 0;
2254 return yyparse ();
2255 @}
2256 @end group
2257 @end example
2258
2259 Remember that computing locations is not a matter of syntax. Every
2260 character must be associated to a location update, whether it is in
2261 valid input, in comments, in literal strings, and so on.
2262
2263 @node Multi-function Calc
2264 @section Multi-Function Calculator: @code{mfcalc}
2265 @cindex multi-function calculator
2266 @cindex @code{mfcalc}
2267 @cindex calculator, multi-function
2268
2269 Now that the basics of Bison have been discussed, it is time to move on to
2270 a more advanced problem. The above calculators provided only five
2271 functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
2272 be nice to have a calculator that provides other mathematical functions such
2273 as @code{sin}, @code{cos}, etc.
2274
2275 It is easy to add new operators to the infix calculator as long as they are
2276 only single-character literals. The lexical analyzer @code{yylex} passes
2277 back all nonnumeric characters as tokens, so new grammar rules suffice for
2278 adding a new operator. But we want something more flexible: built-in
2279 functions whose syntax has this form:
2280
2281 @example
2282 @var{function_name} (@var{argument})
2283 @end example
2284
2285 @noindent
2286 At the same time, we will add memory to the calculator, by allowing you
2287 to create named variables, store values in them, and use them later.
2288 Here is a sample session with the multi-function calculator:
2289
2290 @example
2291 $ @kbd{mfcalc}
2292 @kbd{pi = 3.141592653589}
2293 3.1415926536
2294 @kbd{sin(pi)}
2295 0.0000000000
2296 @kbd{alpha = beta1 = 2.3}
2297 2.3000000000
2298 @kbd{alpha}
2299 2.3000000000
2300 @kbd{ln(alpha)}
2301 0.8329091229
2302 @kbd{exp(ln(beta1))}
2303 2.3000000000
2304 $
2305 @end example
2306
2307 Note that multiple assignment and nested function calls are permitted.
2308
2309 @menu
2310 * Mfcalc Declarations:: Bison declarations for multi-function calculator.
2311 * Mfcalc Rules:: Grammar rules for the calculator.
2312 * Mfcalc Symbol Table:: Symbol table management subroutines.
2313 @end menu
2314
2315 @node Mfcalc Declarations
2316 @subsection Declarations for @code{mfcalc}
2317
2318 Here are the C and Bison declarations for the multi-function calculator.
2319
2320 @smallexample
2321 @group
2322 %@{
2323 #include <math.h> /* For math functions, cos(), sin(), etc. */
2324 #include "calc.h" /* Contains definition of `symrec'. */
2325 int yylex (void);
2326 void yyerror (char const *);
2327 %@}
2328 @end group
2329 @group
2330 %union @{
2331 double val; /* For returning numbers. */
2332 symrec *tptr; /* For returning symbol-table pointers. */
2333 @}
2334 @end group
2335 %token <val> NUM /* Simple double precision number. */
2336 %token <tptr> VAR FNCT /* Variable and Function. */
2337 %type <val> exp
2338
2339 @group
2340 %right '='
2341 %left '-' '+'
2342 %left '*' '/'
2343 %precedence NEG /* negation--unary minus */
2344 %right '^' /* exponentiation */
2345 @end group
2346 %% /* The grammar follows. */
2347 @end smallexample
2348
2349 The above grammar introduces only two new features of the Bison language.
2350 These features allow semantic values to have various data types
2351 (@pxref{Multiple Types, ,More Than One Value Type}).
2352
2353 The @code{%union} declaration specifies the entire list of possible types;
2354 this is instead of defining @code{YYSTYPE}. The allowable types are now
2355 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
2356 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
2357
2358 Since values can now have various types, it is necessary to associate a
2359 type with each grammar symbol whose semantic value is used. These symbols
2360 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
2361 declarations are augmented with information about their data type (placed
2362 between angle brackets).
2363
2364 The Bison construct @code{%type} is used for declaring nonterminal
2365 symbols, just as @code{%token} is used for declaring token types. We
2366 have not used @code{%type} before because nonterminal symbols are
2367 normally declared implicitly by the rules that define them. But
2368 @code{exp} must be declared explicitly so we can specify its value type.
2369 @xref{Type Decl, ,Nonterminal Symbols}.
2370
2371 @node Mfcalc Rules
2372 @subsection Grammar Rules for @code{mfcalc}
2373
2374 Here are the grammar rules for the multi-function calculator.
2375 Most of them are copied directly from @code{calc}; three rules,
2376 those which mention @code{VAR} or @code{FNCT}, are new.
2377
2378 @smallexample
2379 @group
2380 input: /* empty */
2381 | input line
2382 ;
2383 @end group
2384
2385 @group
2386 line:
2387 '\n'
2388 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2389 | error '\n' @{ yyerrok; @}
2390 ;
2391 @end group
2392
2393 @group
2394 exp: NUM @{ $$ = $1; @}
2395 | VAR @{ $$ = $1->value.var; @}
2396 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
2397 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
2398 | exp '+' exp @{ $$ = $1 + $3; @}
2399 | exp '-' exp @{ $$ = $1 - $3; @}
2400 | exp '*' exp @{ $$ = $1 * $3; @}
2401 | exp '/' exp @{ $$ = $1 / $3; @}
2402 | '-' exp %prec NEG @{ $$ = -$2; @}
2403 | exp '^' exp @{ $$ = pow ($1, $3); @}
2404 | '(' exp ')' @{ $$ = $2; @}
2405 ;
2406 @end group
2407 /* End of grammar. */
2408 %%
2409 @end smallexample
2410
2411 @node Mfcalc Symbol Table
2412 @subsection The @code{mfcalc} Symbol Table
2413 @cindex symbol table example
2414
2415 The multi-function calculator requires a symbol table to keep track of the
2416 names and meanings of variables and functions. This doesn't affect the
2417 grammar rules (except for the actions) or the Bison declarations, but it
2418 requires some additional C functions for support.
2419
2420 The symbol table itself consists of a linked list of records. Its
2421 definition, which is kept in the header @file{calc.h}, is as follows. It
2422 provides for either functions or variables to be placed in the table.
2423
2424 @smallexample
2425 @group
2426 /* Function type. */
2427 typedef double (*func_t) (double);
2428 @end group
2429
2430 @group
2431 /* Data type for links in the chain of symbols. */
2432 struct symrec
2433 @{
2434 char *name; /* name of symbol */
2435 int type; /* type of symbol: either VAR or FNCT */
2436 union
2437 @{
2438 double var; /* value of a VAR */
2439 func_t fnctptr; /* value of a FNCT */
2440 @} value;
2441 struct symrec *next; /* link field */
2442 @};
2443 @end group
2444
2445 @group
2446 typedef struct symrec symrec;
2447
2448 /* The symbol table: a chain of `struct symrec'. */
2449 extern symrec *sym_table;
2450
2451 symrec *putsym (char const *, int);
2452 symrec *getsym (char const *);
2453 @end group
2454 @end smallexample
2455
2456 The new version of @code{main} includes a call to @code{init_table}, a
2457 function that initializes the symbol table. Here it is, and
2458 @code{init_table} as well:
2459
2460 @smallexample
2461 #include <stdio.h>
2462
2463 @group
2464 /* Called by yyparse on error. */
2465 void
2466 yyerror (char const *s)
2467 @{
2468 printf ("%s\n", s);
2469 @}
2470 @end group
2471
2472 @group
2473 struct init
2474 @{
2475 char const *fname;
2476 double (*fnct) (double);
2477 @};
2478 @end group
2479
2480 @group
2481 struct init const arith_fncts[] =
2482 @{
2483 "sin", sin,
2484 "cos", cos,
2485 "atan", atan,
2486 "ln", log,
2487 "exp", exp,
2488 "sqrt", sqrt,
2489 0, 0
2490 @};
2491 @end group
2492
2493 @group
2494 /* The symbol table: a chain of `struct symrec'. */
2495 symrec *sym_table;
2496 @end group
2497
2498 @group
2499 /* Put arithmetic functions in table. */
2500 void
2501 init_table (void)
2502 @{
2503 int i;
2504 symrec *ptr;
2505 for (i = 0; arith_fncts[i].fname != 0; i++)
2506 @{
2507 ptr = putsym (arith_fncts[i].fname, FNCT);
2508 ptr->value.fnctptr = arith_fncts[i].fnct;
2509 @}
2510 @}
2511 @end group
2512
2513 @group
2514 int
2515 main (void)
2516 @{
2517 init_table ();
2518 return yyparse ();
2519 @}
2520 @end group
2521 @end smallexample
2522
2523 By simply editing the initialization list and adding the necessary include
2524 files, you can add additional functions to the calculator.
2525
2526 Two important functions allow look-up and installation of symbols in the
2527 symbol table. The function @code{putsym} is passed a name and the type
2528 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2529 linked to the front of the list, and a pointer to the object is returned.
2530 The function @code{getsym} is passed the name of the symbol to look up. If
2531 found, a pointer to that symbol is returned; otherwise zero is returned.
2532
2533 @smallexample
2534 symrec *
2535 putsym (char const *sym_name, int sym_type)
2536 @{
2537 symrec *ptr;
2538 ptr = (symrec *) malloc (sizeof (symrec));
2539 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2540 strcpy (ptr->name,sym_name);
2541 ptr->type = sym_type;
2542 ptr->value.var = 0; /* Set value to 0 even if fctn. */
2543 ptr->next = (struct symrec *)sym_table;
2544 sym_table = ptr;
2545 return ptr;
2546 @}
2547
2548 symrec *
2549 getsym (char const *sym_name)
2550 @{
2551 symrec *ptr;
2552 for (ptr = sym_table; ptr != (symrec *) 0;
2553 ptr = (symrec *)ptr->next)
2554 if (strcmp (ptr->name,sym_name) == 0)
2555 return ptr;
2556 return 0;
2557 @}
2558 @end smallexample
2559
2560 The function @code{yylex} must now recognize variables, numeric values, and
2561 the single-character arithmetic operators. Strings of alphanumeric
2562 characters with a leading letter are recognized as either variables or
2563 functions depending on what the symbol table says about them.
2564
2565 The string is passed to @code{getsym} for look up in the symbol table. If
2566 the name appears in the table, a pointer to its location and its type
2567 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2568 already in the table, then it is installed as a @code{VAR} using
2569 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2570 returned to @code{yyparse}.
2571
2572 No change is needed in the handling of numeric values and arithmetic
2573 operators in @code{yylex}.
2574
2575 @smallexample
2576 @group
2577 #include <ctype.h>
2578 @end group
2579
2580 @group
2581 int
2582 yylex (void)
2583 @{
2584 int c;
2585
2586 /* Ignore white space, get first nonwhite character. */
2587 while ((c = getchar ()) == ' ' || c == '\t');
2588
2589 if (c == EOF)
2590 return 0;
2591 @end group
2592
2593 @group
2594 /* Char starts a number => parse the number. */
2595 if (c == '.' || isdigit (c))
2596 @{
2597 ungetc (c, stdin);
2598 scanf ("%lf", &yylval.val);
2599 return NUM;
2600 @}
2601 @end group
2602
2603 @group
2604 /* Char starts an identifier => read the name. */
2605 if (isalpha (c))
2606 @{
2607 symrec *s;
2608 static char *symbuf = 0;
2609 static int length = 0;
2610 int i;
2611 @end group
2612
2613 @group
2614 /* Initially make the buffer long enough
2615 for a 40-character symbol name. */
2616 if (length == 0)
2617 length = 40, symbuf = (char *)malloc (length + 1);
2618
2619 i = 0;
2620 do
2621 @end group
2622 @group
2623 @{
2624 /* If buffer is full, make it bigger. */
2625 if (i == length)
2626 @{
2627 length *= 2;
2628 symbuf = (char *) realloc (symbuf, length + 1);
2629 @}
2630 /* Add this character to the buffer. */
2631 symbuf[i++] = c;
2632 /* Get another character. */
2633 c = getchar ();
2634 @}
2635 @end group
2636 @group
2637 while (isalnum (c));
2638
2639 ungetc (c, stdin);
2640 symbuf[i] = '\0';
2641 @end group
2642
2643 @group
2644 s = getsym (symbuf);
2645 if (s == 0)
2646 s = putsym (symbuf, VAR);
2647 yylval.tptr = s;
2648 return s->type;
2649 @}
2650
2651 /* Any other character is a token by itself. */
2652 return c;
2653 @}
2654 @end group
2655 @end smallexample
2656
2657 This program is both powerful and flexible. You may easily add new
2658 functions, and it is a simple job to modify this code to install
2659 predefined variables such as @code{pi} or @code{e} as well.
2660
2661 @node Exercises
2662 @section Exercises
2663 @cindex exercises
2664
2665 @enumerate
2666 @item
2667 Add some new functions from @file{math.h} to the initialization list.
2668
2669 @item
2670 Add another array that contains constants and their values. Then
2671 modify @code{init_table} to add these constants to the symbol table.
2672 It will be easiest to give the constants type @code{VAR}.
2673
2674 @item
2675 Make the program report an error if the user refers to an
2676 uninitialized variable in any way except to store a value in it.
2677 @end enumerate
2678
2679 @node Grammar File
2680 @chapter Bison Grammar Files
2681
2682 Bison takes as input a context-free grammar specification and produces a
2683 C-language function that recognizes correct instances of the grammar.
2684
2685 The Bison grammar file conventionally has a name ending in @samp{.y}.
2686 @xref{Invocation, ,Invoking Bison}.
2687
2688 @menu
2689 * Grammar Outline:: Overall layout of the grammar file.
2690 * Symbols:: Terminal and nonterminal symbols.
2691 * Rules:: How to write grammar rules.
2692 * Recursion:: Writing recursive rules.
2693 * Semantics:: Semantic values and actions.
2694 * Locations:: Locations and actions.
2695 * Declarations:: All kinds of Bison declarations are described here.
2696 * Multiple Parsers:: Putting more than one Bison parser in one program.
2697 @end menu
2698
2699 @node Grammar Outline
2700 @section Outline of a Bison Grammar
2701
2702 A Bison grammar file has four main sections, shown here with the
2703 appropriate delimiters:
2704
2705 @example
2706 %@{
2707 @var{Prologue}
2708 %@}
2709
2710 @var{Bison declarations}
2711
2712 %%
2713 @var{Grammar rules}
2714 %%
2715
2716 @var{Epilogue}
2717 @end example
2718
2719 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2720 As a GNU extension, @samp{//} introduces a comment that
2721 continues until end of line.
2722
2723 @menu
2724 * Prologue:: Syntax and usage of the prologue.
2725 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
2726 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2727 * Grammar Rules:: Syntax and usage of the grammar rules section.
2728 * Epilogue:: Syntax and usage of the epilogue.
2729 @end menu
2730
2731 @node Prologue
2732 @subsection The prologue
2733 @cindex declarations section
2734 @cindex Prologue
2735 @cindex declarations
2736
2737 The @var{Prologue} section contains macro definitions and declarations
2738 of functions and variables that are used in the actions in the grammar
2739 rules. These are copied to the beginning of the parser implementation
2740 file so that they precede the definition of @code{yyparse}. You can
2741 use @samp{#include} to get the declarations from a header file. If
2742 you don't need any C declarations, you may omit the @samp{%@{} and
2743 @samp{%@}} delimiters that bracket this section.
2744
2745 The @var{Prologue} section is terminated by the first occurrence
2746 of @samp{%@}} that is outside a comment, a string literal, or a
2747 character constant.
2748
2749 You may have more than one @var{Prologue} section, intermixed with the
2750 @var{Bison declarations}. This allows you to have C and Bison
2751 declarations that refer to each other. For example, the @code{%union}
2752 declaration may use types defined in a header file, and you may wish to
2753 prototype functions that take arguments of type @code{YYSTYPE}. This
2754 can be done with two @var{Prologue} blocks, one before and one after the
2755 @code{%union} declaration.
2756
2757 @smallexample
2758 %@{
2759 #define _GNU_SOURCE
2760 #include <stdio.h>
2761 #include "ptypes.h"
2762 %@}
2763
2764 %union @{
2765 long int n;
2766 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2767 @}
2768
2769 %@{
2770 static void print_token_value (FILE *, int, YYSTYPE);
2771 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2772 %@}
2773
2774 @dots{}
2775 @end smallexample
2776
2777 When in doubt, it is usually safer to put prologue code before all
2778 Bison declarations, rather than after. For example, any definitions
2779 of feature test macros like @code{_GNU_SOURCE} or
2780 @code{_POSIX_C_SOURCE} should appear before all Bison declarations, as
2781 feature test macros can affect the behavior of Bison-generated
2782 @code{#include} directives.
2783
2784 @node Prologue Alternatives
2785 @subsection Prologue Alternatives
2786 @cindex Prologue Alternatives
2787
2788 @findex %code
2789 @findex %code requires
2790 @findex %code provides
2791 @findex %code top
2792
2793 The functionality of @var{Prologue} sections can often be subtle and
2794 inflexible. As an alternative, Bison provides a @code{%code}
2795 directive with an explicit qualifier field, which identifies the
2796 purpose of the code and thus the location(s) where Bison should
2797 generate it. For C/C++, the qualifier can be omitted for the default
2798 location, or it can be one of @code{requires}, @code{provides},
2799 @code{top}. @xref{Decl Summary,,%code}.
2800
2801 Look again at the example of the previous section:
2802
2803 @smallexample
2804 %@{
2805 #define _GNU_SOURCE
2806 #include <stdio.h>
2807 #include "ptypes.h"
2808 %@}
2809
2810 %union @{
2811 long int n;
2812 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2813 @}
2814
2815 %@{
2816 static void print_token_value (FILE *, int, YYSTYPE);
2817 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2818 %@}
2819
2820 @dots{}
2821 @end smallexample
2822
2823 @noindent
2824 Notice that there are two @var{Prologue} sections here, but there's a
2825 subtle distinction between their functionality. For example, if you
2826 decide to override Bison's default definition for @code{YYLTYPE}, in
2827 which @var{Prologue} section should you write your new definition?
2828 You should write it in the first since Bison will insert that code
2829 into the parser implementation file @emph{before} the default
2830 @code{YYLTYPE} definition. In which @var{Prologue} section should you
2831 prototype an internal function, @code{trace_token}, that accepts
2832 @code{YYLTYPE} and @code{yytokentype} as arguments? You should
2833 prototype it in the second since Bison will insert that code
2834 @emph{after} the @code{YYLTYPE} and @code{yytokentype} definitions.
2835
2836 This distinction in functionality between the two @var{Prologue} sections is
2837 established by the appearance of the @code{%union} between them.
2838 This behavior raises a few questions.
2839 First, why should the position of a @code{%union} affect definitions related to
2840 @code{YYLTYPE} and @code{yytokentype}?
2841 Second, what if there is no @code{%union}?
2842 In that case, the second kind of @var{Prologue} section is not available.
2843 This behavior is not intuitive.
2844
2845 To avoid this subtle @code{%union} dependency, rewrite the example using a
2846 @code{%code top} and an unqualified @code{%code}.
2847 Let's go ahead and add the new @code{YYLTYPE} definition and the
2848 @code{trace_token} prototype at the same time:
2849
2850 @smallexample
2851 %code top @{
2852 #define _GNU_SOURCE
2853 #include <stdio.h>
2854
2855 /* WARNING: The following code really belongs
2856 * in a `%code requires'; see below. */
2857
2858 #include "ptypes.h"
2859 #define YYLTYPE YYLTYPE
2860 typedef struct YYLTYPE
2861 @{
2862 int first_line;
2863 int first_column;
2864 int last_line;
2865 int last_column;
2866 char *filename;
2867 @} YYLTYPE;
2868 @}
2869
2870 %union @{
2871 long int n;
2872 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2873 @}
2874
2875 %code @{
2876 static void print_token_value (FILE *, int, YYSTYPE);
2877 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2878 static void trace_token (enum yytokentype token, YYLTYPE loc);
2879 @}
2880
2881 @dots{}
2882 @end smallexample
2883
2884 @noindent
2885 In this way, @code{%code top} and the unqualified @code{%code} achieve the same
2886 functionality as the two kinds of @var{Prologue} sections, but it's always
2887 explicit which kind you intend.
2888 Moreover, both kinds are always available even in the absence of @code{%union}.
2889
2890 The @code{%code top} block above logically contains two parts. The
2891 first two lines before the warning need to appear near the top of the
2892 parser implementation file. The first line after the warning is
2893 required by @code{YYSTYPE} and thus also needs to appear in the parser
2894 implementation file. However, if you've instructed Bison to generate
2895 a parser header file (@pxref{Decl Summary, ,%defines}), you probably
2896 want that line to appear before the @code{YYSTYPE} definition in that
2897 header file as well. The @code{YYLTYPE} definition should also appear
2898 in the parser header file to override the default @code{YYLTYPE}
2899 definition there.
2900
2901 In other words, in the @code{%code top} block above, all but the first two
2902 lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
2903 definitions.
2904 Thus, they belong in one or more @code{%code requires}:
2905
2906 @smallexample
2907 %code top @{
2908 #define _GNU_SOURCE
2909 #include <stdio.h>
2910 @}
2911
2912 %code requires @{
2913 #include "ptypes.h"
2914 @}
2915 %union @{
2916 long int n;
2917 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2918 @}
2919
2920 %code requires @{
2921 #define YYLTYPE YYLTYPE
2922 typedef struct YYLTYPE
2923 @{
2924 int first_line;
2925 int first_column;
2926 int last_line;
2927 int last_column;
2928 char *filename;
2929 @} YYLTYPE;
2930 @}
2931
2932 %code @{
2933 static void print_token_value (FILE *, int, YYSTYPE);
2934 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2935 static void trace_token (enum yytokentype token, YYLTYPE loc);
2936 @}
2937
2938 @dots{}
2939 @end smallexample
2940
2941 @noindent
2942 Now Bison will insert @code{#include "ptypes.h"} and the new
2943 @code{YYLTYPE} definition before the Bison-generated @code{YYSTYPE}
2944 and @code{YYLTYPE} definitions in both the parser implementation file
2945 and the parser header file. (By the same reasoning, @code{%code
2946 requires} would also be the appropriate place to write your own
2947 definition for @code{YYSTYPE}.)
2948
2949 When you are writing dependency code for @code{YYSTYPE} and
2950 @code{YYLTYPE}, you should prefer @code{%code requires} over
2951 @code{%code top} regardless of whether you instruct Bison to generate
2952 a parser header file. When you are writing code that you need Bison
2953 to insert only into the parser implementation file and that has no
2954 special need to appear at the top of that file, you should prefer the
2955 unqualified @code{%code} over @code{%code top}. These practices will
2956 make the purpose of each block of your code explicit to Bison and to
2957 other developers reading your grammar file. Following these
2958 practices, we expect the unqualified @code{%code} and @code{%code
2959 requires} to be the most important of the four @var{Prologue}
2960 alternatives.
2961
2962 At some point while developing your parser, you might decide to
2963 provide @code{trace_token} to modules that are external to your
2964 parser. Thus, you might wish for Bison to insert the prototype into
2965 both the parser header file and the parser implementation file. Since
2966 this function is not a dependency required by @code{YYSTYPE} or
2967 @code{YYLTYPE}, it doesn't make sense to move its prototype to a
2968 @code{%code requires}. More importantly, since it depends upon
2969 @code{YYLTYPE} and @code{yytokentype}, @code{%code requires} is not
2970 sufficient. Instead, move its prototype from the unqualified
2971 @code{%code} to a @code{%code provides}:
2972
2973 @smallexample
2974 %code top @{
2975 #define _GNU_SOURCE
2976 #include <stdio.h>
2977 @}
2978
2979 %code requires @{
2980 #include "ptypes.h"
2981 @}
2982 %union @{
2983 long int n;
2984 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2985 @}
2986
2987 %code requires @{
2988 #define YYLTYPE YYLTYPE
2989 typedef struct YYLTYPE
2990 @{
2991 int first_line;
2992 int first_column;
2993 int last_line;
2994 int last_column;
2995 char *filename;
2996 @} YYLTYPE;
2997 @}
2998
2999 %code provides @{
3000 void trace_token (enum yytokentype token, YYLTYPE loc);
3001 @}
3002
3003 %code @{
3004 static void print_token_value (FILE *, int, YYSTYPE);
3005 #define YYPRINT(F, N, L) print_token_value (F, N, L)
3006 @}
3007
3008 @dots{}
3009 @end smallexample
3010
3011 @noindent
3012 Bison will insert the @code{trace_token} prototype into both the
3013 parser header file and the parser implementation file after the
3014 definitions for @code{yytokentype}, @code{YYLTYPE}, and
3015 @code{YYSTYPE}.
3016
3017 The above examples are careful to write directives in an order that
3018 reflects the layout of the generated parser implementation and header
3019 files: @code{%code top}, @code{%code requires}, @code{%code provides},
3020 and then @code{%code}. While your grammar files may generally be
3021 easier to read if you also follow this order, Bison does not require
3022 it. Instead, Bison lets you choose an organization that makes sense
3023 to you.
3024
3025 You may declare any of these directives multiple times in the grammar file.
3026 In that case, Bison concatenates the contained code in declaration order.
3027 This is the only way in which the position of one of these directives within
3028 the grammar file affects its functionality.
3029
3030 The result of the previous two properties is greater flexibility in how you may
3031 organize your grammar file.
3032 For example, you may organize semantic-type-related directives by semantic
3033 type:
3034
3035 @smallexample
3036 %code requires @{ #include "type1.h" @}
3037 %union @{ type1 field1; @}
3038 %destructor @{ type1_free ($$); @} <field1>
3039 %printer @{ type1_print ($$); @} <field1>
3040
3041 %code requires @{ #include "type2.h" @}
3042 %union @{ type2 field2; @}
3043 %destructor @{ type2_free ($$); @} <field2>
3044 %printer @{ type2_print ($$); @} <field2>
3045 @end smallexample
3046
3047 @noindent
3048 You could even place each of the above directive groups in the rules section of
3049 the grammar file next to the set of rules that uses the associated semantic
3050 type.
3051 (In the rules section, you must terminate each of those directives with a
3052 semicolon.)
3053 And you don't have to worry that some directive (like a @code{%union}) in the
3054 definitions section is going to adversely affect their functionality in some
3055 counter-intuitive manner just because it comes first.
3056 Such an organization is not possible using @var{Prologue} sections.
3057
3058 This section has been concerned with explaining the advantages of the four
3059 @var{Prologue} alternatives over the original Yacc @var{Prologue}.
3060 However, in most cases when using these directives, you shouldn't need to
3061 think about all the low-level ordering issues discussed here.
3062 Instead, you should simply use these directives to label each block of your
3063 code according to its purpose and let Bison handle the ordering.
3064 @code{%code} is the most generic label.
3065 Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
3066 as needed.
3067
3068 @node Bison Declarations
3069 @subsection The Bison Declarations Section
3070 @cindex Bison declarations (introduction)
3071 @cindex declarations, Bison (introduction)
3072
3073 The @var{Bison declarations} section contains declarations that define
3074 terminal and nonterminal symbols, specify precedence, and so on.
3075 In some simple grammars you may not need any declarations.
3076 @xref{Declarations, ,Bison Declarations}.
3077
3078 @node Grammar Rules
3079 @subsection The Grammar Rules Section
3080 @cindex grammar rules section
3081 @cindex rules section for grammar
3082
3083 The @dfn{grammar rules} section contains one or more Bison grammar
3084 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
3085
3086 There must always be at least one grammar rule, and the first
3087 @samp{%%} (which precedes the grammar rules) may never be omitted even
3088 if it is the first thing in the file.
3089
3090 @node Epilogue
3091 @subsection The epilogue
3092 @cindex additional C code section
3093 @cindex epilogue
3094 @cindex C code, section for additional
3095
3096 The @var{Epilogue} is copied verbatim to the end of the parser
3097 implementation file, just as the @var{Prologue} is copied to the
3098 beginning. This is the most convenient place to put anything that you
3099 want to have in the parser implementation file but which need not come
3100 before the definition of @code{yyparse}. For example, the definitions
3101 of @code{yylex} and @code{yyerror} often go here. Because C requires
3102 functions to be declared before being used, you often need to declare
3103 functions like @code{yylex} and @code{yyerror} in the Prologue, even
3104 if you define them in the Epilogue. @xref{Interface, ,Parser
3105 C-Language Interface}.
3106
3107 If the last section is empty, you may omit the @samp{%%} that separates it
3108 from the grammar rules.
3109
3110 The Bison parser itself contains many macros and identifiers whose names
3111 start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3112 any such names (except those documented in this manual) in the epilogue
3113 of the grammar file.
3114
3115 @node Symbols
3116 @section Symbols, Terminal and Nonterminal
3117 @cindex nonterminal symbol
3118 @cindex terminal symbol
3119 @cindex token type
3120 @cindex symbol
3121
3122 @dfn{Symbols} in Bison grammars represent the grammatical classifications
3123 of the language.
3124
3125 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
3126 class of syntactically equivalent tokens. You use the symbol in grammar
3127 rules to mean that a token in that class is allowed. The symbol is
3128 represented in the Bison parser by a numeric code, and the @code{yylex}
3129 function returns a token type code to indicate what kind of token has
3130 been read. You don't need to know what the code value is; you can use
3131 the symbol to stand for it.
3132
3133 A @dfn{nonterminal symbol} stands for a class of syntactically
3134 equivalent groupings. The symbol name is used in writing grammar rules.
3135 By convention, it should be all lower case.
3136
3137 Symbol names can contain letters, underscores, periods, and non-initial
3138 digits and dashes. Dashes in symbol names are a GNU extension, incompatible
3139 with POSIX Yacc. Periods and dashes make symbol names less convenient to
3140 use with named references, which require brackets around such names
3141 (@pxref{Named References}). Terminal symbols that contain periods or dashes
3142 make little sense: since they are not valid symbols (in most programming
3143 languages) they are not exported as token names.
3144
3145 There are three ways of writing terminal symbols in the grammar:
3146
3147 @itemize @bullet
3148 @item
3149 A @dfn{named token type} is written with an identifier, like an
3150 identifier in C@. By convention, it should be all upper case. Each
3151 such name must be defined with a Bison declaration such as
3152 @code{%token}. @xref{Token Decl, ,Token Type Names}.
3153
3154 @item
3155 @cindex character token
3156 @cindex literal token
3157 @cindex single-character literal
3158 A @dfn{character token type} (or @dfn{literal character token}) is
3159 written in the grammar using the same syntax used in C for character
3160 constants; for example, @code{'+'} is a character token type. A
3161 character token type doesn't need to be declared unless you need to
3162 specify its semantic value data type (@pxref{Value Type, ,Data Types of
3163 Semantic Values}), associativity, or precedence (@pxref{Precedence,
3164 ,Operator Precedence}).
3165
3166 By convention, a character token type is used only to represent a
3167 token that consists of that particular character. Thus, the token
3168 type @code{'+'} is used to represent the character @samp{+} as a
3169 token. Nothing enforces this convention, but if you depart from it,
3170 your program will confuse other readers.
3171
3172 All the usual escape sequences used in character literals in C can be
3173 used in Bison as well, but you must not use the null character as a
3174 character literal because its numeric code, zero, signifies
3175 end-of-input (@pxref{Calling Convention, ,Calling Convention
3176 for @code{yylex}}). Also, unlike standard C, trigraphs have no
3177 special meaning in Bison character literals, nor is backslash-newline
3178 allowed.
3179
3180 @item
3181 @cindex string token
3182 @cindex literal string token
3183 @cindex multicharacter literal
3184 A @dfn{literal string token} is written like a C string constant; for
3185 example, @code{"<="} is a literal string token. A literal string token
3186 doesn't need to be declared unless you need to specify its semantic
3187 value data type (@pxref{Value Type}), associativity, or precedence
3188 (@pxref{Precedence}).
3189
3190 You can associate the literal string token with a symbolic name as an
3191 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
3192 Declarations}). If you don't do that, the lexical analyzer has to
3193 retrieve the token number for the literal string token from the
3194 @code{yytname} table (@pxref{Calling Convention}).
3195
3196 @strong{Warning}: literal string tokens do not work in Yacc.
3197
3198 By convention, a literal string token is used only to represent a token
3199 that consists of that particular string. Thus, you should use the token
3200 type @code{"<="} to represent the string @samp{<=} as a token. Bison
3201 does not enforce this convention, but if you depart from it, people who
3202 read your program will be confused.
3203
3204 All the escape sequences used in string literals in C can be used in
3205 Bison as well, except that you must not use a null character within a
3206 string literal. Also, unlike Standard C, trigraphs have no special
3207 meaning in Bison string literals, nor is backslash-newline allowed. A
3208 literal string token must contain two or more characters; for a token
3209 containing just one character, use a character token (see above).
3210 @end itemize
3211
3212 How you choose to write a terminal symbol has no effect on its
3213 grammatical meaning. That depends only on where it appears in rules and
3214 on when the parser function returns that symbol.
3215
3216 The value returned by @code{yylex} is always one of the terminal
3217 symbols, except that a zero or negative value signifies end-of-input.
3218 Whichever way you write the token type in the grammar rules, you write
3219 it the same way in the definition of @code{yylex}. The numeric code
3220 for a character token type is simply the positive numeric code of the
3221 character, so @code{yylex} can use the identical value to generate the
3222 requisite code, though you may need to convert it to @code{unsigned
3223 char} to avoid sign-extension on hosts where @code{char} is signed.
3224 Each named token type becomes a C macro in the parser implementation
3225 file, so @code{yylex} can use the name to stand for the code. (This
3226 is why periods don't make sense in terminal symbols.) @xref{Calling
3227 Convention, ,Calling Convention for @code{yylex}}.
3228
3229 If @code{yylex} is defined in a separate file, you need to arrange for the
3230 token-type macro definitions to be available there. Use the @samp{-d}
3231 option when you run Bison, so that it will write these macro definitions
3232 into a separate header file @file{@var{name}.tab.h} which you can include
3233 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
3234
3235 If you want to write a grammar that is portable to any Standard C
3236 host, you must use only nonnull character tokens taken from the basic
3237 execution character set of Standard C@. This set consists of the ten
3238 digits, the 52 lower- and upper-case English letters, and the
3239 characters in the following C-language string:
3240
3241 @example
3242 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3243 @end example
3244
3245 The @code{yylex} function and Bison must use a consistent character set
3246 and encoding for character tokens. For example, if you run Bison in an
3247 ASCII environment, but then compile and run the resulting
3248 program in an environment that uses an incompatible character set like
3249 EBCDIC, the resulting program may not work because the tables
3250 generated by Bison will assume ASCII numeric values for
3251 character tokens. It is standard practice for software distributions to
3252 contain C source files that were generated by Bison in an
3253 ASCII environment, so installers on platforms that are
3254 incompatible with ASCII must rebuild those files before
3255 compiling them.
3256
3257 The symbol @code{error} is a terminal symbol reserved for error recovery
3258 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
3259 In particular, @code{yylex} should never return this value. The default
3260 value of the error token is 256, unless you explicitly assigned 256 to
3261 one of your tokens with a @code{%token} declaration.
3262
3263 @node Rules
3264 @section Syntax of Grammar Rules
3265 @cindex rule syntax
3266 @cindex grammar rule syntax
3267 @cindex syntax of grammar rules
3268
3269 A Bison grammar rule has the following general form:
3270
3271 @example
3272 @group
3273 @var{result}: @var{components}@dots{}
3274 ;
3275 @end group
3276 @end example
3277
3278 @noindent
3279 where @var{result} is the nonterminal symbol that this rule describes,
3280 and @var{components} are various terminal and nonterminal symbols that
3281 are put together by this rule (@pxref{Symbols}).
3282
3283 For example,
3284
3285 @example
3286 @group
3287 exp: exp '+' exp
3288 ;
3289 @end group
3290 @end example
3291
3292 @noindent
3293 says that two groupings of type @code{exp}, with a @samp{+} token in between,
3294 can be combined into a larger grouping of type @code{exp}.
3295
3296 White space in rules is significant only to separate symbols. You can add
3297 extra white space as you wish.
3298
3299 Scattered among the components can be @var{actions} that determine
3300 the semantics of the rule. An action looks like this:
3301
3302 @example
3303 @{@var{C statements}@}
3304 @end example
3305
3306 @noindent
3307 @cindex braced code
3308 This is an example of @dfn{braced code}, that is, C code surrounded by
3309 braces, much like a compound statement in C@. Braced code can contain
3310 any sequence of C tokens, so long as its braces are balanced. Bison
3311 does not check the braced code for correctness directly; it merely
3312 copies the code to the parser implementation file, where the C
3313 compiler can check it.
3314
3315 Within braced code, the balanced-brace count is not affected by braces
3316 within comments, string literals, or character constants, but it is
3317 affected by the C digraphs @samp{<%} and @samp{%>} that represent
3318 braces. At the top level braced code must be terminated by @samp{@}}
3319 and not by a digraph. Bison does not look for trigraphs, so if braced
3320 code uses trigraphs you should ensure that they do not affect the
3321 nesting of braces or the boundaries of comments, string literals, or
3322 character constants.
3323
3324 Usually there is only one action and it follows the components.
3325 @xref{Actions}.
3326
3327 @findex |
3328 Multiple rules for the same @var{result} can be written separately or can
3329 be joined with the vertical-bar character @samp{|} as follows:
3330
3331 @example
3332 @group
3333 @var{result}: @var{rule1-components}@dots{}
3334 | @var{rule2-components}@dots{}
3335 @dots{}
3336 ;
3337 @end group
3338 @end example
3339
3340 @noindent
3341 They are still considered distinct rules even when joined in this way.
3342
3343 If @var{components} in a rule is empty, it means that @var{result} can
3344 match the empty string. For example, here is how to define a
3345 comma-separated sequence of zero or more @code{exp} groupings:
3346
3347 @example
3348 @group
3349 expseq: /* empty */
3350 | expseq1
3351 ;
3352 @end group
3353
3354 @group
3355 expseq1: exp
3356 | expseq1 ',' exp
3357 ;
3358 @end group
3359 @end example
3360
3361 @noindent
3362 It is customary to write a comment @samp{/* empty */} in each rule
3363 with no components.
3364
3365 @node Recursion
3366 @section Recursive Rules
3367 @cindex recursive rule
3368
3369 A rule is called @dfn{recursive} when its @var{result} nonterminal
3370 appears also on its right hand side. Nearly all Bison grammars need to
3371 use recursion, because that is the only way to define a sequence of any
3372 number of a particular thing. Consider this recursive definition of a
3373 comma-separated sequence of one or more expressions:
3374
3375 @example
3376 @group
3377 expseq1: exp
3378 | expseq1 ',' exp
3379 ;
3380 @end group
3381 @end example
3382
3383 @cindex left recursion
3384 @cindex right recursion
3385 @noindent
3386 Since the recursive use of @code{expseq1} is the leftmost symbol in the
3387 right hand side, we call this @dfn{left recursion}. By contrast, here
3388 the same construct is defined using @dfn{right recursion}:
3389
3390 @example
3391 @group
3392 expseq1: exp
3393 | exp ',' expseq1
3394 ;
3395 @end group
3396 @end example
3397
3398 @noindent
3399 Any kind of sequence can be defined using either left recursion or right
3400 recursion, but you should always use left recursion, because it can
3401 parse a sequence of any number of elements with bounded stack space.
3402 Right recursion uses up space on the Bison stack in proportion to the
3403 number of elements in the sequence, because all the elements must be
3404 shifted onto the stack before the rule can be applied even once.
3405 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
3406 of this.
3407
3408 @cindex mutual recursion
3409 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3410 rule does not appear directly on its right hand side, but does appear
3411 in rules for other nonterminals which do appear on its right hand
3412 side.
3413
3414 For example:
3415
3416 @example
3417 @group
3418 expr: primary
3419 | primary '+' primary
3420 ;
3421 @end group
3422
3423 @group
3424 primary: constant
3425 | '(' expr ')'
3426 ;
3427 @end group
3428 @end example
3429
3430 @noindent
3431 defines two mutually-recursive nonterminals, since each refers to the
3432 other.
3433
3434 @node Semantics
3435 @section Defining Language Semantics
3436 @cindex defining language semantics
3437 @cindex language semantics, defining
3438
3439 The grammar rules for a language determine only the syntax. The semantics
3440 are determined by the semantic values associated with various tokens and
3441 groupings, and by the actions taken when various groupings are recognized.
3442
3443 For example, the calculator calculates properly because the value
3444 associated with each expression is the proper number; it adds properly
3445 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3446 the numbers associated with @var{x} and @var{y}.
3447
3448 @menu
3449 * Value Type:: Specifying one data type for all semantic values.
3450 * Multiple Types:: Specifying several alternative data types.
3451 * Actions:: An action is the semantic definition of a grammar rule.
3452 * Action Types:: Specifying data types for actions to operate on.
3453 * Mid-Rule Actions:: Most actions go at the end of a rule.
3454 This says when, why and how to use the exceptional
3455 action in the middle of a rule.
3456 * Named References:: Using named references in actions.
3457 @end menu
3458
3459 @node Value Type
3460 @subsection Data Types of Semantic Values
3461 @cindex semantic value type
3462 @cindex value type, semantic
3463 @cindex data types of semantic values
3464 @cindex default data type
3465
3466 In a simple program it may be sufficient to use the same data type for
3467 the semantic values of all language constructs. This was true in the
3468 RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
3469 Notation Calculator}).
3470
3471 Bison normally uses the type @code{int} for semantic values if your
3472 program uses the same data type for all language constructs. To
3473 specify some other type, define @code{YYSTYPE} as a macro, like this:
3474
3475 @example
3476 #define YYSTYPE double
3477 @end example
3478
3479 @noindent
3480 @code{YYSTYPE}'s replacement list should be a type name
3481 that does not contain parentheses or square brackets.
3482 This macro definition must go in the prologue of the grammar file
3483 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
3484
3485 @node Multiple Types
3486 @subsection More Than One Value Type
3487
3488 In most programs, you will need different data types for different kinds
3489 of tokens and groupings. For example, a numeric constant may need type
3490 @code{int} or @code{long int}, while a string constant needs type
3491 @code{char *}, and an identifier might need a pointer to an entry in the
3492 symbol table.
3493
3494 To use more than one data type for semantic values in one parser, Bison
3495 requires you to do two things:
3496
3497 @itemize @bullet
3498 @item
3499 Specify the entire collection of possible data types, either by using the
3500 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
3501 Value Types}), or by using a @code{typedef} or a @code{#define} to
3502 define @code{YYSTYPE} to be a union type whose member names are
3503 the type tags.
3504
3505 @item
3506 Choose one of those types for each symbol (terminal or nonterminal) for
3507 which semantic values are used. This is done for tokens with the
3508 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
3509 and for groupings with the @code{%type} Bison declaration (@pxref{Type
3510 Decl, ,Nonterminal Symbols}).
3511 @end itemize
3512
3513 @node Actions
3514 @subsection Actions
3515 @cindex action
3516 @vindex $$
3517 @vindex $@var{n}
3518 @vindex $@var{name}
3519 @vindex $[@var{name}]
3520
3521 An action accompanies a syntactic rule and contains C code to be executed
3522 each time an instance of that rule is recognized. The task of most actions
3523 is to compute a semantic value for the grouping built by the rule from the
3524 semantic values associated with tokens or smaller groupings.
3525
3526 An action consists of braced code containing C statements, and can be
3527 placed at any position in the rule;
3528 it is executed at that position. Most rules have just one action at the
3529 end of the rule, following all the components. Actions in the middle of
3530 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
3531 Actions, ,Actions in Mid-Rule}).
3532
3533 The C code in an action can refer to the semantic values of the
3534 components matched by the rule with the construct @code{$@var{n}},
3535 which stands for the value of the @var{n}th component. The semantic
3536 value for the grouping being constructed is @code{$$}. In addition,
3537 the semantic values of symbols can be accessed with the named
3538 references construct @code{$@var{name}} or @code{$[@var{name}]}.
3539 Bison translates both of these constructs into expressions of the
3540 appropriate type when it copies the actions into the parser
3541 implementation file. @code{$$} (or @code{$@var{name}}, when it stands
3542 for the current grouping) is translated to a modifiable lvalue, so it
3543 can be assigned to.
3544
3545 Here is a typical example:
3546
3547 @example
3548 @group
3549 exp: @dots{}
3550 | exp '+' exp
3551 @{ $$ = $1 + $3; @}
3552 @end group
3553 @end example
3554
3555 Or, in terms of named references:
3556
3557 @example
3558 @group
3559 exp[result]: @dots{}
3560 | exp[left] '+' exp[right]
3561 @{ $result = $left + $right; @}
3562 @end group
3563 @end example
3564
3565 @noindent
3566 This rule constructs an @code{exp} from two smaller @code{exp} groupings
3567 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
3568 (@code{$left} and @code{$right})
3569 refer to the semantic values of the two component @code{exp} groupings,
3570 which are the first and third symbols on the right hand side of the rule.
3571 The sum is stored into @code{$$} (@code{$result}) so that it becomes the
3572 semantic value of
3573 the addition-expression just recognized by the rule. If there were a
3574 useful semantic value associated with the @samp{+} token, it could be
3575 referred to as @code{$2}.
3576
3577 @xref{Named References,,Using Named References}, for more information
3578 about using the named references construct.
3579
3580 Note that the vertical-bar character @samp{|} is really a rule
3581 separator, and actions are attached to a single rule. This is a
3582 difference with tools like Flex, for which @samp{|} stands for either
3583 ``or'', or ``the same action as that of the next rule''. In the
3584 following example, the action is triggered only when @samp{b} is found:
3585
3586 @example
3587 @group
3588 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
3589 @end group
3590 @end example
3591
3592 @cindex default action
3593 If you don't specify an action for a rule, Bison supplies a default:
3594 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule
3595 becomes the value of the whole rule. Of course, the default action is
3596 valid only if the two data types match. There is no meaningful default
3597 action for an empty rule; every empty rule must have an explicit action
3598 unless the rule's value does not matter.
3599
3600 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
3601 to tokens and groupings on the stack @emph{before} those that match the
3602 current rule. This is a very risky practice, and to use it reliably
3603 you must be certain of the context in which the rule is applied. Here
3604 is a case in which you can use this reliably:
3605
3606 @example
3607 @group
3608 foo: expr bar '+' expr @{ @dots{} @}
3609 | expr bar '-' expr @{ @dots{} @}
3610 ;
3611 @end group
3612
3613 @group
3614 bar: /* empty */
3615 @{ previous_expr = $0; @}
3616 ;
3617 @end group
3618 @end example
3619
3620 As long as @code{bar} is used only in the fashion shown here, @code{$0}
3621 always refers to the @code{expr} which precedes @code{bar} in the
3622 definition of @code{foo}.
3623
3624 @vindex yylval
3625 It is also possible to access the semantic value of the lookahead token, if
3626 any, from a semantic action.
3627 This semantic value is stored in @code{yylval}.
3628 @xref{Action Features, ,Special Features for Use in Actions}.
3629
3630 @node Action Types
3631 @subsection Data Types of Values in Actions
3632 @cindex action data types
3633 @cindex data types in actions
3634
3635 If you have chosen a single data type for semantic values, the @code{$$}
3636 and @code{$@var{n}} constructs always have that data type.
3637
3638 If you have used @code{%union} to specify a variety of data types, then you
3639 must declare a choice among these types for each terminal or nonterminal
3640 symbol that can have a semantic value. Then each time you use @code{$$} or
3641 @code{$@var{n}}, its data type is determined by which symbol it refers to
3642 in the rule. In this example,
3643
3644 @example
3645 @group
3646 exp: @dots{}
3647 | exp '+' exp
3648 @{ $$ = $1 + $3; @}
3649 @end group
3650 @end example
3651
3652 @noindent
3653 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
3654 have the data type declared for the nonterminal symbol @code{exp}. If
3655 @code{$2} were used, it would have the data type declared for the
3656 terminal symbol @code{'+'}, whatever that might be.
3657
3658 Alternatively, you can specify the data type when you refer to the value,
3659 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
3660 reference. For example, if you have defined types as shown here:
3661
3662 @example
3663 @group
3664 %union @{
3665 int itype;
3666 double dtype;
3667 @}
3668 @end group
3669 @end example
3670
3671 @noindent
3672 then you can write @code{$<itype>1} to refer to the first subunit of the
3673 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
3674
3675 @node Mid-Rule Actions
3676 @subsection Actions in Mid-Rule
3677 @cindex actions in mid-rule
3678 @cindex mid-rule actions
3679
3680 Occasionally it is useful to put an action in the middle of a rule.
3681 These actions are written just like usual end-of-rule actions, but they
3682 are executed before the parser even recognizes the following components.
3683
3684 A mid-rule action may refer to the components preceding it using
3685 @code{$@var{n}}, but it may not refer to subsequent components because
3686 it is run before they are parsed.
3687
3688 The mid-rule action itself counts as one of the components of the rule.
3689 This makes a difference when there is another action later in the same rule
3690 (and usually there is another at the end): you have to count the actions
3691 along with the symbols when working out which number @var{n} to use in
3692 @code{$@var{n}}.
3693
3694 The mid-rule action can also have a semantic value. The action can set
3695 its value with an assignment to @code{$$}, and actions later in the rule
3696 can refer to the value using @code{$@var{n}}. Since there is no symbol
3697 to name the action, there is no way to declare a data type for the value
3698 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
3699 specify a data type each time you refer to this value.
3700
3701 There is no way to set the value of the entire rule with a mid-rule
3702 action, because assignments to @code{$$} do not have that effect. The
3703 only way to set the value for the entire rule is with an ordinary action
3704 at the end of the rule.
3705
3706 Here is an example from a hypothetical compiler, handling a @code{let}
3707 statement that looks like @samp{let (@var{variable}) @var{statement}} and
3708 serves to create a variable named @var{variable} temporarily for the
3709 duration of @var{statement}. To parse this construct, we must put
3710 @var{variable} into the symbol table while @var{statement} is parsed, then
3711 remove it afterward. Here is how it is done:
3712
3713 @example
3714 @group
3715 stmt: LET '(' var ')'
3716 @{ $<context>$ = push_context ();
3717 declare_variable ($3); @}
3718 stmt @{ $$ = $6;
3719 pop_context ($<context>5); @}
3720 @end group
3721 @end example
3722
3723 @noindent
3724 As soon as @samp{let (@var{variable})} has been recognized, the first
3725 action is run. It saves a copy of the current semantic context (the
3726 list of accessible variables) as its semantic value, using alternative
3727 @code{context} in the data-type union. Then it calls
3728 @code{declare_variable} to add the new variable to that list. Once the
3729 first action is finished, the embedded statement @code{stmt} can be
3730 parsed. Note that the mid-rule action is component number 5, so the
3731 @samp{stmt} is component number 6.
3732
3733 After the embedded statement is parsed, its semantic value becomes the
3734 value of the entire @code{let}-statement. Then the semantic value from the
3735 earlier action is used to restore the prior list of variables. This
3736 removes the temporary @code{let}-variable from the list so that it won't
3737 appear to exist while the rest of the program is parsed.
3738
3739 @findex %destructor
3740 @cindex discarded symbols, mid-rule actions
3741 @cindex error recovery, mid-rule actions
3742 In the above example, if the parser initiates error recovery (@pxref{Error
3743 Recovery}) while parsing the tokens in the embedded statement @code{stmt},
3744 it might discard the previous semantic context @code{$<context>5} without
3745 restoring it.
3746 Thus, @code{$<context>5} needs a destructor (@pxref{Destructor Decl, , Freeing
3747 Discarded Symbols}).
3748 However, Bison currently provides no means to declare a destructor specific to
3749 a particular mid-rule action's semantic value.
3750
3751 One solution is to bury the mid-rule action inside a nonterminal symbol and to
3752 declare a destructor for that symbol:
3753
3754 @example
3755 @group
3756 %type <context> let
3757 %destructor @{ pop_context ($$); @} let
3758
3759 %%
3760
3761 stmt: let stmt
3762 @{ $$ = $2;
3763 pop_context ($1); @}
3764 ;
3765
3766 let: LET '(' var ')'
3767 @{ $$ = push_context ();
3768 declare_variable ($3); @}
3769 ;
3770
3771 @end group
3772 @end example
3773
3774 @noindent
3775 Note that the action is now at the end of its rule.
3776 Any mid-rule action can be converted to an end-of-rule action in this way, and
3777 this is what Bison actually does to implement mid-rule actions.
3778
3779 Taking action before a rule is completely recognized often leads to
3780 conflicts since the parser must commit to a parse in order to execute the
3781 action. For example, the following two rules, without mid-rule actions,
3782 can coexist in a working parser because the parser can shift the open-brace
3783 token and look at what follows before deciding whether there is a
3784 declaration or not:
3785
3786 @example
3787 @group
3788 compound: '@{' declarations statements '@}'
3789 | '@{' statements '@}'
3790 ;
3791 @end group
3792 @end example
3793
3794 @noindent
3795 But when we add a mid-rule action as follows, the rules become nonfunctional:
3796
3797 @example
3798 @group
3799 compound: @{ prepare_for_local_variables (); @}
3800 '@{' declarations statements '@}'
3801 @end group
3802 @group
3803 | '@{' statements '@}'
3804 ;
3805 @end group
3806 @end example
3807
3808 @noindent
3809 Now the parser is forced to decide whether to run the mid-rule action
3810 when it has read no farther than the open-brace. In other words, it
3811 must commit to using one rule or the other, without sufficient
3812 information to do it correctly. (The open-brace token is what is called
3813 the @dfn{lookahead} token at this time, since the parser is still
3814 deciding what to do about it. @xref{Lookahead, ,Lookahead Tokens}.)
3815
3816 You might think that you could correct the problem by putting identical
3817 actions into the two rules, like this:
3818
3819 @example
3820 @group
3821 compound: @{ prepare_for_local_variables (); @}
3822 '@{' declarations statements '@}'
3823 | @{ prepare_for_local_variables (); @}
3824 '@{' statements '@}'
3825 ;
3826 @end group
3827 @end example
3828
3829 @noindent
3830 But this does not help, because Bison does not realize that the two actions
3831 are identical. (Bison never tries to understand the C code in an action.)
3832
3833 If the grammar is such that a declaration can be distinguished from a
3834 statement by the first token (which is true in C), then one solution which
3835 does work is to put the action after the open-brace, like this:
3836
3837 @example
3838 @group
3839 compound: '@{' @{ prepare_for_local_variables (); @}
3840 declarations statements '@}'
3841 | '@{' statements '@}'
3842 ;
3843 @end group
3844 @end example
3845
3846 @noindent
3847 Now the first token of the following declaration or statement,
3848 which would in any case tell Bison which rule to use, can still do so.
3849
3850 Another solution is to bury the action inside a nonterminal symbol which
3851 serves as a subroutine:
3852
3853 @example
3854 @group
3855 subroutine: /* empty */
3856 @{ prepare_for_local_variables (); @}
3857 ;
3858
3859 @end group
3860
3861 @group
3862 compound: subroutine
3863 '@{' declarations statements '@}'
3864 | subroutine
3865 '@{' statements '@}'
3866 ;
3867 @end group
3868 @end example
3869
3870 @noindent
3871 Now Bison can execute the action in the rule for @code{subroutine} without
3872 deciding which rule for @code{compound} it will eventually use.
3873
3874 @node Named References
3875 @subsection Using Named References
3876 @cindex named references
3877
3878 While every semantic value can be accessed with positional references
3879 @code{$@var{n}} and @code{$$}, it's often much more convenient to refer to
3880 them by name. First of all, original symbol names may be used as named
3881 references. For example:
3882
3883 @example
3884 @group
3885 invocation: op '(' args ')'
3886 @{ $invocation = new_invocation ($op, $args, @@invocation); @}
3887 @end group
3888 @end example
3889
3890 @noindent
3891 The positional @code{$$}, @code{@@$}, @code{$n}, and @code{@@n} can be
3892 mixed with @code{$name} and @code{@@name} arbitrarily. For example:
3893
3894 @example
3895 @group
3896 invocation: op '(' args ')'
3897 @{ $$ = new_invocation ($op, $args, @@$); @}
3898 @end group
3899 @end example
3900
3901 @noindent
3902 However, sometimes regular symbol names are not sufficient due to
3903 ambiguities:
3904
3905 @example
3906 @group
3907 exp: exp '/' exp
3908 @{ $exp = $exp / $exp; @} // $exp is ambiguous.
3909
3910 exp: exp '/' exp
3911 @{ $$ = $1 / $exp; @} // One usage is ambiguous.
3912
3913 exp: exp '/' exp
3914 @{ $$ = $1 / $3; @} // No error.
3915 @end group
3916 @end example
3917
3918 @noindent
3919 When ambiguity occurs, explicitly declared names may be used for values and
3920 locations. Explicit names are declared as a bracketed name after a symbol
3921 appearance in rule definitions. For example:
3922 @example
3923 @group
3924 exp[result]: exp[left] '/' exp[right]
3925 @{ $result = $left / $right; @}
3926 @end group
3927 @end example
3928
3929 @noindent
3930 Explicit names may be declared for RHS and for LHS symbols as well. In order
3931 to access a semantic value generated by a mid-rule action, an explicit name
3932 may also be declared by putting a bracketed name after the closing brace of
3933 the mid-rule action code:
3934 @example
3935 @group
3936 exp[res]: exp[x] '+' @{$left = $x;@}[left] exp[right]
3937 @{ $res = $left + $right; @}
3938 @end group
3939 @end example
3940
3941 @noindent
3942
3943 In references, in order to specify names containing dots and dashes, an explicit
3944 bracketed syntax @code{$[name]} and @code{@@[name]} must be used:
3945 @example
3946 @group
3947 if-stmt: IF '(' expr ')' THEN then.stmt ';'
3948 @{ $[if-stmt] = new_if_stmt ($expr, $[then.stmt]); @}
3949 @end group
3950 @end example
3951
3952 It often happens that named references are followed by a dot, dash or other
3953 C punctuation marks and operators. By default, Bison will read
3954 @code{$name.suffix} as a reference to symbol value @code{$name} followed by
3955 @samp{.suffix}, i.e., an access to the @samp{suffix} field of the semantic
3956 value. In order to force Bison to recognize @code{name.suffix} in its entirety
3957 as the name of a semantic value, bracketed syntax @code{$[name.suffix]}
3958 must be used.
3959
3960
3961 @node Locations
3962 @section Tracking Locations
3963 @cindex location
3964 @cindex textual location
3965 @cindex location, textual
3966
3967 Though grammar rules and semantic actions are enough to write a fully
3968 functional parser, it can be useful to process some additional information,
3969 especially symbol locations.
3970
3971 The way locations are handled is defined by providing a data type, and
3972 actions to take when rules are matched.
3973
3974 @menu
3975 * Location Type:: Specifying a data type for locations.
3976 * Actions and Locations:: Using locations in actions.
3977 * Location Default Action:: Defining a general way to compute locations.
3978 @end menu
3979
3980 @node Location Type
3981 @subsection Data Type of Locations
3982 @cindex data type of locations
3983 @cindex default location type
3984
3985 Defining a data type for locations is much simpler than for semantic values,
3986 since all tokens and groupings always use the same type.
3987
3988 You can specify the type of locations by defining a macro called
3989 @code{YYLTYPE}, just as you can specify the semantic value type by
3990 defining a @code{YYSTYPE} macro (@pxref{Value Type}).
3991 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3992 four members:
3993
3994 @example
3995 typedef struct YYLTYPE
3996 @{
3997 int first_line;
3998 int first_column;
3999 int last_line;
4000 int last_column;
4001 @} YYLTYPE;
4002 @end example
4003
4004 When @code{YYLTYPE} is not defined, at the beginning of the parsing, Bison
4005 initializes all these fields to 1 for @code{yylloc}. To initialize
4006 @code{yylloc} with a custom location type (or to chose a different
4007 initialization), use the @code{%initial-action} directive. @xref{Initial
4008 Action Decl, , Performing Actions before Parsing}.
4009
4010 @node Actions and Locations
4011 @subsection Actions and Locations
4012 @cindex location actions
4013 @cindex actions, location
4014 @vindex @@$
4015 @vindex @@@var{n}
4016 @vindex @@@var{name}
4017 @vindex @@[@var{name}]
4018
4019 Actions are not only useful for defining language semantics, but also for
4020 describing the behavior of the output parser with locations.
4021
4022 The most obvious way for building locations of syntactic groupings is very
4023 similar to the way semantic values are computed. In a given rule, several
4024 constructs can be used to access the locations of the elements being matched.
4025 The location of the @var{n}th component of the right hand side is
4026 @code{@@@var{n}}, while the location of the left hand side grouping is
4027 @code{@@$}.
4028
4029 In addition, the named references construct @code{@@@var{name}} and
4030 @code{@@[@var{name}]} may also be used to address the symbol locations.
4031 @xref{Named References,,Using Named References}, for more information
4032 about using the named references construct.
4033
4034 Here is a basic example using the default data type for locations:
4035
4036 @example
4037 @group
4038 exp: @dots{}
4039 | exp '/' exp
4040 @{
4041 @@$.first_column = @@1.first_column;
4042 @@$.first_line = @@1.first_line;
4043 @@$.last_column = @@3.last_column;
4044 @@$.last_line = @@3.last_line;
4045 if ($3)
4046 $$ = $1 / $3;
4047 else
4048 @{
4049 $$ = 1;
4050 fprintf (stderr,
4051 "Division by zero, l%d,c%d-l%d,c%d",
4052 @@3.first_line, @@3.first_column,
4053 @@3.last_line, @@3.last_column);
4054 @}
4055 @}
4056 @end group
4057 @end example
4058
4059 As for semantic values, there is a default action for locations that is
4060 run each time a rule is matched. It sets the beginning of @code{@@$} to the
4061 beginning of the first symbol, and the end of @code{@@$} to the end of the
4062 last symbol.
4063
4064 With this default action, the location tracking can be fully automatic. The
4065 example above simply rewrites this way:
4066
4067 @example
4068 @group
4069 exp: @dots{}
4070 | exp '/' exp
4071 @{
4072 if ($3)
4073 $$ = $1 / $3;
4074 else
4075 @{
4076 $$ = 1;
4077 fprintf (stderr,
4078 "Division by zero, l%d,c%d-l%d,c%d",
4079 @@3.first_line, @@3.first_column,
4080 @@3.last_line, @@3.last_column);
4081 @}
4082 @}
4083 @end group
4084 @end example
4085
4086 @vindex yylloc
4087 It is also possible to access the location of the lookahead token, if any,
4088 from a semantic action.
4089 This location is stored in @code{yylloc}.
4090 @xref{Action Features, ,Special Features for Use in Actions}.
4091
4092 @node Location Default Action
4093 @subsection Default Action for Locations
4094 @vindex YYLLOC_DEFAULT
4095 @cindex GLR parsers and @code{YYLLOC_DEFAULT}
4096
4097 Actually, actions are not the best place to compute locations. Since
4098 locations are much more general than semantic values, there is room in
4099 the output parser to redefine the default action to take for each
4100 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
4101 matched, before the associated action is run. It is also invoked
4102 while processing a syntax error, to compute the error's location.
4103 Before reporting an unresolvable syntactic ambiguity, a GLR
4104 parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
4105 of that ambiguity.
4106
4107 Most of the time, this macro is general enough to suppress location
4108 dedicated code from semantic actions.
4109
4110 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
4111 the location of the grouping (the result of the computation). When a
4112 rule is matched, the second parameter identifies locations of
4113 all right hand side elements of the rule being matched, and the third
4114 parameter is the size of the rule's right hand side.
4115 When a GLR parser reports an ambiguity, which of multiple candidate
4116 right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
4117 When processing a syntax error, the second parameter identifies locations
4118 of the symbols that were discarded during error processing, and the third
4119 parameter is the number of discarded symbols.
4120
4121 By default, @code{YYLLOC_DEFAULT} is defined this way:
4122
4123 @smallexample
4124 @group
4125 # define YYLLOC_DEFAULT(Current, Rhs, N) \
4126 do \
4127 if (N) \
4128 @{ \
4129 (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
4130 (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
4131 (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
4132 (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
4133 @} \
4134 else \
4135 @{ \
4136 (Current).first_line = (Current).last_line = \
4137 YYRHSLOC(Rhs, 0).last_line; \
4138 (Current).first_column = (Current).last_column = \
4139 YYRHSLOC(Rhs, 0).last_column; \
4140 @} \
4141 while (0)
4142 @end group
4143 @end smallexample
4144
4145 where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
4146 in @var{rhs} when @var{k} is positive, and the location of the symbol
4147 just before the reduction when @var{k} and @var{n} are both zero.
4148
4149 When defining @code{YYLLOC_DEFAULT}, you should consider that:
4150
4151 @itemize @bullet
4152 @item
4153 All arguments are free of side-effects. However, only the first one (the
4154 result) should be modified by @code{YYLLOC_DEFAULT}.
4155
4156 @item
4157 For consistency with semantic actions, valid indexes within the
4158 right hand side range from 1 to @var{n}. When @var{n} is zero, only 0 is a
4159 valid index, and it refers to the symbol just before the reduction.
4160 During error processing @var{n} is always positive.
4161
4162 @item
4163 Your macro should parenthesize its arguments, if need be, since the
4164 actual arguments may not be surrounded by parentheses. Also, your
4165 macro should expand to something that can be used as a single
4166 statement when it is followed by a semicolon.
4167 @end itemize
4168
4169 @node Declarations
4170 @section Bison Declarations
4171 @cindex declarations, Bison
4172 @cindex Bison declarations
4173
4174 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
4175 used in formulating the grammar and the data types of semantic values.
4176 @xref{Symbols}.
4177
4178 All token type names (but not single-character literal tokens such as
4179 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
4180 declared if you need to specify which data type to use for the semantic
4181 value (@pxref{Multiple Types, ,More Than One Value Type}).
4182
4183 The first rule in the grammar file also specifies the start symbol, by
4184 default. If you want some other symbol to be the start symbol, you
4185 must declare it explicitly (@pxref{Language and Grammar, ,Languages
4186 and Context-Free Grammars}).
4187
4188 @menu
4189 * Require Decl:: Requiring a Bison version.
4190 * Token Decl:: Declaring terminal symbols.
4191 * Precedence Decl:: Declaring terminals with precedence and associativity.
4192 * Union Decl:: Declaring the set of all semantic value types.
4193 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
4194 * Initial Action Decl:: Code run before parsing starts.
4195 * Destructor Decl:: Declaring how symbols are freed.
4196 * Expect Decl:: Suppressing warnings about parsing conflicts.
4197 * Start Decl:: Specifying the start symbol.
4198 * Pure Decl:: Requesting a reentrant parser.
4199 * Push Decl:: Requesting a push parser.
4200 * Decl Summary:: Table of all Bison declarations.
4201 @end menu
4202
4203 @node Require Decl
4204 @subsection Require a Version of Bison
4205 @cindex version requirement
4206 @cindex requiring a version of Bison
4207 @findex %require
4208
4209 You may require the minimum version of Bison to process the grammar. If
4210 the requirement is not met, @command{bison} exits with an error (exit
4211 status 63).
4212
4213 @example
4214 %require "@var{version}"
4215 @end example
4216
4217 @node Token Decl
4218 @subsection Token Type Names
4219 @cindex declaring token type names
4220 @cindex token type names, declaring
4221 @cindex declaring literal string tokens
4222 @findex %token
4223
4224 The basic way to declare a token type name (terminal symbol) is as follows:
4225
4226 @example
4227 %token @var{name}
4228 @end example
4229
4230 Bison will convert this into a @code{#define} directive in
4231 the parser, so that the function @code{yylex} (if it is in this file)
4232 can use the name @var{name} to stand for this token type's code.
4233
4234 Alternatively, you can use @code{%left}, @code{%right},
4235 @code{%precedence}, or
4236 @code{%nonassoc} instead of @code{%token}, if you wish to specify
4237 associativity and precedence. @xref{Precedence Decl, ,Operator
4238 Precedence}.
4239
4240 You can explicitly specify the numeric code for a token type by appending
4241 a nonnegative decimal or hexadecimal integer value in the field immediately
4242 following the token name:
4243
4244 @example
4245 %token NUM 300
4246 %token XNUM 0x12d // a GNU extension
4247 @end example
4248
4249 @noindent
4250 It is generally best, however, to let Bison choose the numeric codes for
4251 all token types. Bison will automatically select codes that don't conflict
4252 with each other or with normal characters.
4253
4254 In the event that the stack type is a union, you must augment the
4255 @code{%token} or other token declaration to include the data type
4256 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
4257 Than One Value Type}).
4258
4259 For example:
4260
4261 @example
4262 @group
4263 %union @{ /* define stack type */
4264 double val;
4265 symrec *tptr;
4266 @}
4267 %token <val> NUM /* define token NUM and its type */
4268 @end group
4269 @end example
4270
4271 You can associate a literal string token with a token type name by
4272 writing the literal string at the end of a @code{%token}
4273 declaration which declares the name. For example:
4274
4275 @example
4276 %token arrow "=>"
4277 @end example
4278
4279 @noindent
4280 For example, a grammar for the C language might specify these names with
4281 equivalent literal string tokens:
4282
4283 @example
4284 %token <operator> OR "||"
4285 %token <operator> LE 134 "<="
4286 %left OR "<="
4287 @end example
4288
4289 @noindent
4290 Once you equate the literal string and the token name, you can use them
4291 interchangeably in further declarations or the grammar rules. The
4292 @code{yylex} function can use the token name or the literal string to
4293 obtain the token type code number (@pxref{Calling Convention}).
4294 Syntax error messages passed to @code{yyerror} from the parser will reference
4295 the literal string instead of the token name.
4296
4297 The token numbered as 0 corresponds to end of file; the following line
4298 allows for nicer error messages referring to ``end of file'' instead
4299 of ``$end'':
4300
4301 @example
4302 %token END 0 "end of file"
4303 @end example
4304
4305 @node Precedence Decl
4306 @subsection Operator Precedence
4307 @cindex precedence declarations
4308 @cindex declaring operator precedence
4309 @cindex operator precedence, declaring
4310
4311 Use the @code{%left}, @code{%right}, @code{%nonassoc}, or
4312 @code{%precedence} declaration to
4313 declare a token and specify its precedence and associativity, all at
4314 once. These are called @dfn{precedence declarations}.
4315 @xref{Precedence, ,Operator Precedence}, for general information on
4316 operator precedence.
4317
4318 The syntax of a precedence declaration is nearly the same as that of
4319 @code{%token}: either
4320
4321 @example
4322 %left @var{symbols}@dots{}
4323 @end example
4324
4325 @noindent
4326 or
4327
4328 @example
4329 %left <@var{type}> @var{symbols}@dots{}
4330 @end example
4331
4332 And indeed any of these declarations serves the purposes of @code{%token}.
4333 But in addition, they specify the associativity and relative precedence for
4334 all the @var{symbols}:
4335
4336 @itemize @bullet
4337 @item
4338 The associativity of an operator @var{op} determines how repeated uses
4339 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
4340 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
4341 grouping @var{y} with @var{z} first. @code{%left} specifies
4342 left-associativity (grouping @var{x} with @var{y} first) and
4343 @code{%right} specifies right-associativity (grouping @var{y} with
4344 @var{z} first). @code{%nonassoc} specifies no associativity, which
4345 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
4346 considered a syntax error.
4347
4348 @code{%precedence} gives only precedence to the @var{symbols}, and
4349 defines no associativity at all. Use this to define precedence only,
4350 and leave any potential conflict due to associativity enabled.
4351
4352 @item
4353 The precedence of an operator determines how it nests with other operators.
4354 All the tokens declared in a single precedence declaration have equal
4355 precedence and nest together according to their associativity.
4356 When two tokens declared in different precedence declarations associate,
4357 the one declared later has the higher precedence and is grouped first.
4358 @end itemize
4359
4360 For backward compatibility, there is a confusing difference between the
4361 argument lists of @code{%token} and precedence declarations.
4362 Only a @code{%token} can associate a literal string with a token type name.
4363 A precedence declaration always interprets a literal string as a reference to a
4364 separate token.
4365 For example:
4366
4367 @example
4368 %left OR "<=" // Does not declare an alias.
4369 %left OR 134 "<=" 135 // Declares 134 for OR and 135 for "<=".
4370 @end example
4371
4372 @node Union Decl
4373 @subsection The Collection of Value Types
4374 @cindex declaring value types
4375 @cindex value types, declaring
4376 @findex %union
4377
4378 The @code{%union} declaration specifies the entire collection of
4379 possible data types for semantic values. The keyword @code{%union} is
4380 followed by braced code containing the same thing that goes inside a
4381 @code{union} in C@.
4382
4383 For example:
4384
4385 @example
4386 @group
4387 %union @{
4388 double val;
4389 symrec *tptr;
4390 @}
4391 @end group
4392 @end example
4393
4394 @noindent
4395 This says that the two alternative types are @code{double} and @code{symrec
4396 *}. They are given names @code{val} and @code{tptr}; these names are used
4397 in the @code{%token} and @code{%type} declarations to pick one of the types
4398 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
4399
4400 As an extension to POSIX, a tag is allowed after the
4401 @code{union}. For example:
4402
4403 @example
4404 @group
4405 %union value @{
4406 double val;
4407 symrec *tptr;
4408 @}
4409 @end group
4410 @end example
4411
4412 @noindent
4413 specifies the union tag @code{value}, so the corresponding C type is
4414 @code{union value}. If you do not specify a tag, it defaults to
4415 @code{YYSTYPE}.
4416
4417 As another extension to POSIX, you may specify multiple
4418 @code{%union} declarations; their contents are concatenated. However,
4419 only the first @code{%union} declaration can specify a tag.
4420
4421 Note that, unlike making a @code{union} declaration in C, you need not write
4422 a semicolon after the closing brace.
4423
4424 Instead of @code{%union}, you can define and use your own union type
4425 @code{YYSTYPE} if your grammar contains at least one
4426 @samp{<@var{type}>} tag. For example, you can put the following into
4427 a header file @file{parser.h}:
4428
4429 @example
4430 @group
4431 union YYSTYPE @{
4432 double val;
4433 symrec *tptr;
4434 @};
4435 typedef union YYSTYPE YYSTYPE;
4436 @end group
4437 @end example
4438
4439 @noindent
4440 and then your grammar can use the following
4441 instead of @code{%union}:
4442
4443 @example
4444 @group
4445 %@{
4446 #include "parser.h"
4447 %@}
4448 %type <val> expr
4449 %token <tptr> ID
4450 @end group
4451 @end example
4452
4453 @node Type Decl
4454 @subsection Nonterminal Symbols
4455 @cindex declaring value types, nonterminals
4456 @cindex value types, nonterminals, declaring
4457 @findex %type
4458
4459 @noindent
4460 When you use @code{%union} to specify multiple value types, you must
4461 declare the value type of each nonterminal symbol for which values are
4462 used. This is done with a @code{%type} declaration, like this:
4463
4464 @example
4465 %type <@var{type}> @var{nonterminal}@dots{}
4466 @end example
4467
4468 @noindent
4469 Here @var{nonterminal} is the name of a nonterminal symbol, and
4470 @var{type} is the name given in the @code{%union} to the alternative
4471 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
4472 can give any number of nonterminal symbols in the same @code{%type}
4473 declaration, if they have the same value type. Use spaces to separate
4474 the symbol names.
4475
4476 You can also declare the value type of a terminal symbol. To do this,
4477 use the same @code{<@var{type}>} construction in a declaration for the
4478 terminal symbol. All kinds of token declarations allow
4479 @code{<@var{type}>}.
4480
4481 @node Initial Action Decl
4482 @subsection Performing Actions before Parsing
4483 @findex %initial-action
4484
4485 Sometimes your parser needs to perform some initializations before
4486 parsing. The @code{%initial-action} directive allows for such arbitrary
4487 code.
4488
4489 @deffn {Directive} %initial-action @{ @var{code} @}
4490 @findex %initial-action
4491 Declare that the braced @var{code} must be invoked before parsing each time
4492 @code{yyparse} is called. The @var{code} may use @code{$$} and
4493 @code{@@$} --- initial value and location of the lookahead --- and the
4494 @code{%parse-param}.
4495 @end deffn
4496
4497 For instance, if your locations use a file name, you may use
4498
4499 @example
4500 %parse-param @{ char const *file_name @};
4501 %initial-action
4502 @{
4503 @@$.initialize (file_name);
4504 @};
4505 @end example
4506
4507
4508 @node Destructor Decl
4509 @subsection Freeing Discarded Symbols
4510 @cindex freeing discarded symbols
4511 @findex %destructor
4512 @findex <*>
4513 @findex <>
4514 During error recovery (@pxref{Error Recovery}), symbols already pushed
4515 on the stack and tokens coming from the rest of the file are discarded
4516 until the parser falls on its feet. If the parser runs out of memory,
4517 or if it returns via @code{YYABORT} or @code{YYACCEPT}, all the
4518 symbols on the stack must be discarded. Even if the parser succeeds, it
4519 must discard the start symbol.
4520
4521 When discarded symbols convey heap based information, this memory is
4522 lost. While this behavior can be tolerable for batch parsers, such as
4523 in traditional compilers, it is unacceptable for programs like shells or
4524 protocol implementations that may parse and execute indefinitely.
4525
4526 The @code{%destructor} directive defines code that is called when a
4527 symbol is automatically discarded.
4528
4529 @deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
4530 @findex %destructor
4531 Invoke the braced @var{code} whenever the parser discards one of the
4532 @var{symbols}.
4533 Within @var{code}, @code{$$} designates the semantic value associated
4534 with the discarded symbol, and @code{@@$} designates its location.
4535 The additional parser parameters are also available (@pxref{Parser Function, ,
4536 The Parser Function @code{yyparse}}).
4537
4538 When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
4539 per-symbol @code{%destructor}.
4540 You may also define a per-type @code{%destructor} by listing a semantic type
4541 tag among @var{symbols}.
4542 In that case, the parser will invoke this @var{code} whenever it discards any
4543 grammar symbol that has that semantic type tag unless that symbol has its own
4544 per-symbol @code{%destructor}.
4545
4546 Finally, you can define two different kinds of default @code{%destructor}s.
4547 (These default forms are experimental.
4548 More user feedback will help to determine whether they should become permanent
4549 features.)
4550 You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
4551 exactly one @code{%destructor} declaration in your grammar file.
4552 The parser will invoke the @var{code} associated with one of these whenever it
4553 discards any user-defined grammar symbol that has no per-symbol and no per-type
4554 @code{%destructor}.
4555 The parser uses the @var{code} for @code{<*>} in the case of such a grammar
4556 symbol for which you have formally declared a semantic type tag (@code{%type}
4557 counts as such a declaration, but @code{$<tag>$} does not).
4558 The parser uses the @var{code} for @code{<>} in the case of such a grammar
4559 symbol that has no declared semantic type tag.
4560 @end deffn
4561
4562 @noindent
4563 For example:
4564
4565 @smallexample
4566 %union @{ char *string; @}
4567 %token <string> STRING1
4568 %token <string> STRING2
4569 %type <string> string1
4570 %type <string> string2
4571 %union @{ char character; @}
4572 %token <character> CHR
4573 %type <character> chr
4574 %token TAGLESS
4575
4576 %destructor @{ @} <character>
4577 %destructor @{ free ($$); @} <*>
4578 %destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
4579 %destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
4580 @end smallexample
4581
4582 @noindent
4583 guarantees that, when the parser discards any user-defined symbol that has a
4584 semantic type tag other than @code{<character>}, it passes its semantic value
4585 to @code{free} by default.
4586 However, when the parser discards a @code{STRING1} or a @code{string1}, it also
4587 prints its line number to @code{stdout}.
4588 It performs only the second @code{%destructor} in this case, so it invokes
4589 @code{free} only once.
4590 Finally, the parser merely prints a message whenever it discards any symbol,
4591 such as @code{TAGLESS}, that has no semantic type tag.
4592
4593 A Bison-generated parser invokes the default @code{%destructor}s only for
4594 user-defined as opposed to Bison-defined symbols.
4595 For example, the parser will not invoke either kind of default
4596 @code{%destructor} for the special Bison-defined symbols @code{$accept},
4597 @code{$undefined}, or @code{$end} (@pxref{Table of Symbols, ,Bison Symbols}),
4598 none of which you can reference in your grammar.
4599 It also will not invoke either for the @code{error} token (@pxref{Table of
4600 Symbols, ,error}), which is always defined by Bison regardless of whether you
4601 reference it in your grammar.
4602 However, it may invoke one of them for the end token (token 0) if you
4603 redefine it from @code{$end} to, for example, @code{END}:
4604
4605 @smallexample
4606 %token END 0
4607 @end smallexample
4608
4609 @cindex actions in mid-rule
4610 @cindex mid-rule actions
4611 Finally, Bison will never invoke a @code{%destructor} for an unreferenced
4612 mid-rule semantic value (@pxref{Mid-Rule Actions,,Actions in Mid-Rule}).
4613 That is, Bison does not consider a mid-rule to have a semantic value if you do
4614 not reference @code{$$} in the mid-rule's action or @code{$@var{n}} (where
4615 @var{n} is the RHS symbol position of the mid-rule) in any later action in that
4616 rule.
4617 However, if you do reference either, the Bison-generated parser will invoke the
4618 @code{<>} @code{%destructor} whenever it discards the mid-rule symbol.
4619
4620 @ignore
4621 @noindent
4622 In the future, it may be possible to redefine the @code{error} token as a
4623 nonterminal that captures the discarded symbols.
4624 In that case, the parser will invoke the default destructor for it as well.
4625 @end ignore
4626
4627 @sp 1
4628
4629 @cindex discarded symbols
4630 @dfn{Discarded symbols} are the following:
4631
4632 @itemize
4633 @item
4634 stacked symbols popped during the first phase of error recovery,
4635 @item
4636 incoming terminals during the second phase of error recovery,
4637 @item
4638 the current lookahead and the entire stack (except the current
4639 right-hand side symbols) when the parser returns immediately, and
4640 @item
4641 the start symbol, when the parser succeeds.
4642 @end itemize
4643
4644 The parser can @dfn{return immediately} because of an explicit call to
4645 @code{YYABORT} or @code{YYACCEPT}, or failed error recovery, or memory
4646 exhaustion.
4647
4648 Right-hand side symbols of a rule that explicitly triggers a syntax
4649 error via @code{YYERROR} are not discarded automatically. As a rule
4650 of thumb, destructors are invoked only when user actions cannot manage
4651 the memory.
4652
4653 @node Expect Decl
4654 @subsection Suppressing Conflict Warnings
4655 @cindex suppressing conflict warnings
4656 @cindex preventing warnings about conflicts
4657 @cindex warnings, preventing
4658 @cindex conflicts, suppressing warnings of
4659 @findex %expect
4660 @findex %expect-rr
4661
4662 Bison normally warns if there are any conflicts in the grammar
4663 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
4664 have harmless shift/reduce conflicts which are resolved in a predictable
4665 way and would be difficult to eliminate. It is desirable to suppress
4666 the warning about these conflicts unless the number of conflicts
4667 changes. You can do this with the @code{%expect} declaration.
4668
4669 The declaration looks like this:
4670
4671 @example
4672 %expect @var{n}
4673 @end example
4674
4675 Here @var{n} is a decimal integer. The declaration says there should
4676 be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
4677 Bison reports an error if the number of shift/reduce conflicts differs
4678 from @var{n}, or if there are any reduce/reduce conflicts.
4679
4680 For deterministic parsers, reduce/reduce conflicts are more
4681 serious, and should be eliminated entirely. Bison will always report
4682 reduce/reduce conflicts for these parsers. With GLR
4683 parsers, however, both kinds of conflicts are routine; otherwise,
4684 there would be no need to use GLR parsing. Therefore, it is
4685 also possible to specify an expected number of reduce/reduce conflicts
4686 in GLR parsers, using the declaration:
4687
4688 @example
4689 %expect-rr @var{n}
4690 @end example
4691
4692 In general, using @code{%expect} involves these steps:
4693
4694 @itemize @bullet
4695 @item
4696 Compile your grammar without @code{%expect}. Use the @samp{-v} option
4697 to get a verbose list of where the conflicts occur. Bison will also
4698 print the number of conflicts.
4699
4700 @item
4701 Check each of the conflicts to make sure that Bison's default
4702 resolution is what you really want. If not, rewrite the grammar and
4703 go back to the beginning.
4704
4705 @item
4706 Add an @code{%expect} declaration, copying the number @var{n} from the
4707 number which Bison printed. With GLR parsers, add an
4708 @code{%expect-rr} declaration as well.
4709 @end itemize
4710
4711 Now Bison will report an error if you introduce an unexpected conflict,
4712 but will keep silent otherwise.
4713
4714 @node Start Decl
4715 @subsection The Start-Symbol
4716 @cindex declaring the start symbol
4717 @cindex start symbol, declaring
4718 @cindex default start symbol
4719 @findex %start
4720
4721 Bison assumes by default that the start symbol for the grammar is the first
4722 nonterminal specified in the grammar specification section. The programmer
4723 may override this restriction with the @code{%start} declaration as follows:
4724
4725 @example
4726 %start @var{symbol}
4727 @end example
4728
4729 @node Pure Decl
4730 @subsection A Pure (Reentrant) Parser
4731 @cindex reentrant parser
4732 @cindex pure parser
4733 @findex %define api.pure
4734
4735 A @dfn{reentrant} program is one which does not alter in the course of
4736 execution; in other words, it consists entirely of @dfn{pure} (read-only)
4737 code. Reentrancy is important whenever asynchronous execution is possible;
4738 for example, a nonreentrant program may not be safe to call from a signal
4739 handler. In systems with multiple threads of control, a nonreentrant
4740 program must be called only within interlocks.
4741
4742 Normally, Bison generates a parser which is not reentrant. This is
4743 suitable for most uses, and it permits compatibility with Yacc. (The
4744 standard Yacc interfaces are inherently nonreentrant, because they use
4745 statically allocated variables for communication with @code{yylex},
4746 including @code{yylval} and @code{yylloc}.)
4747
4748 Alternatively, you can generate a pure, reentrant parser. The Bison
4749 declaration @samp{%define api.pure} says that you want the parser to be
4750 reentrant. It looks like this:
4751
4752 @example
4753 %define api.pure
4754 @end example
4755
4756 The result is that the communication variables @code{yylval} and
4757 @code{yylloc} become local variables in @code{yyparse}, and a different
4758 calling convention is used for the lexical analyzer function
4759 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
4760 Parsers}, for the details of this. The variable @code{yynerrs}
4761 becomes local in @code{yyparse} in pull mode but it becomes a member
4762 of yypstate in push mode. (@pxref{Error Reporting, ,The Error
4763 Reporting Function @code{yyerror}}). The convention for calling
4764 @code{yyparse} itself is unchanged.
4765
4766 Whether the parser is pure has nothing to do with the grammar rules.
4767 You can generate either a pure parser or a nonreentrant parser from any
4768 valid grammar.
4769
4770 @node Push Decl
4771 @subsection A Push Parser
4772 @cindex push parser
4773 @cindex push parser
4774 @findex %define api.push-pull
4775
4776 (The current push parsing interface is experimental and may evolve.
4777 More user feedback will help to stabilize it.)
4778
4779 A pull parser is called once and it takes control until all its input
4780 is completely parsed. A push parser, on the other hand, is called
4781 each time a new token is made available.
4782
4783 A push parser is typically useful when the parser is part of a
4784 main event loop in the client's application. This is typically
4785 a requirement of a GUI, when the main event loop needs to be triggered
4786 within a certain time period.
4787
4788 Normally, Bison generates a pull parser.
4789 The following Bison declaration says that you want the parser to be a push
4790 parser (@pxref{Decl Summary,,%define api.push-pull}):
4791
4792 @example
4793 %define api.push-pull push
4794 @end example
4795
4796 In almost all cases, you want to ensure that your push parser is also
4797 a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}). The only
4798 time you should create an impure push parser is to have backwards
4799 compatibility with the impure Yacc pull mode interface. Unless you know
4800 what you are doing, your declarations should look like this:
4801
4802 @example
4803 %define api.pure
4804 %define api.push-pull push
4805 @end example
4806
4807 There is a major notable functional difference between the pure push parser
4808 and the impure push parser. It is acceptable for a pure push parser to have
4809 many parser instances, of the same type of parser, in memory at the same time.
4810 An impure push parser should only use one parser at a time.
4811
4812 When a push parser is selected, Bison will generate some new symbols in
4813 the generated parser. @code{yypstate} is a structure that the generated
4814 parser uses to store the parser's state. @code{yypstate_new} is the
4815 function that will create a new parser instance. @code{yypstate_delete}
4816 will free the resources associated with the corresponding parser instance.
4817 Finally, @code{yypush_parse} is the function that should be called whenever a
4818 token is available to provide the parser. A trivial example
4819 of using a pure push parser would look like this:
4820
4821 @example
4822 int status;
4823 yypstate *ps = yypstate_new ();
4824 do @{
4825 status = yypush_parse (ps, yylex (), NULL);
4826 @} while (status == YYPUSH_MORE);
4827 yypstate_delete (ps);
4828 @end example
4829
4830 If the user decided to use an impure push parser, a few things about
4831 the generated parser will change. The @code{yychar} variable becomes
4832 a global variable instead of a variable in the @code{yypush_parse} function.
4833 For this reason, the signature of the @code{yypush_parse} function is
4834 changed to remove the token as a parameter. A nonreentrant push parser
4835 example would thus look like this:
4836
4837 @example
4838 extern int yychar;
4839 int status;
4840 yypstate *ps = yypstate_new ();
4841 do @{
4842 yychar = yylex ();
4843 status = yypush_parse (ps);
4844 @} while (status == YYPUSH_MORE);
4845 yypstate_delete (ps);
4846 @end example
4847
4848 That's it. Notice the next token is put into the global variable @code{yychar}
4849 for use by the next invocation of the @code{yypush_parse} function.
4850
4851 Bison also supports both the push parser interface along with the pull parser
4852 interface in the same generated parser. In order to get this functionality,
4853 you should replace the @samp{%define api.push-pull push} declaration with the
4854 @samp{%define api.push-pull both} declaration. Doing this will create all of
4855 the symbols mentioned earlier along with the two extra symbols, @code{yyparse}
4856 and @code{yypull_parse}. @code{yyparse} can be used exactly as it normally
4857 would be used. However, the user should note that it is implemented in the
4858 generated parser by calling @code{yypull_parse}.
4859 This makes the @code{yyparse} function that is generated with the
4860 @samp{%define api.push-pull both} declaration slower than the normal
4861 @code{yyparse} function. If the user
4862 calls the @code{yypull_parse} function it will parse the rest of the input
4863 stream. It is possible to @code{yypush_parse} tokens to select a subgrammar
4864 and then @code{yypull_parse} the rest of the input stream. If you would like
4865 to switch back and forth between between parsing styles, you would have to
4866 write your own @code{yypull_parse} function that knows when to quit looking
4867 for input. An example of using the @code{yypull_parse} function would look
4868 like this:
4869
4870 @example
4871 yypstate *ps = yypstate_new ();
4872 yypull_parse (ps); /* Will call the lexer */
4873 yypstate_delete (ps);
4874 @end example
4875
4876 Adding the @samp{%define api.pure} declaration does exactly the same thing to
4877 the generated parser with @samp{%define api.push-pull both} as it did for
4878 @samp{%define api.push-pull push}.
4879
4880 @node Decl Summary
4881 @subsection Bison Declaration Summary
4882 @cindex Bison declaration summary
4883 @cindex declaration summary
4884 @cindex summary, Bison declaration
4885
4886 Here is a summary of the declarations used to define a grammar:
4887
4888 @deffn {Directive} %union
4889 Declare the collection of data types that semantic values may have
4890 (@pxref{Union Decl, ,The Collection of Value Types}).
4891 @end deffn
4892
4893 @deffn {Directive} %token
4894 Declare a terminal symbol (token type name) with no precedence
4895 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
4896 @end deffn
4897
4898 @deffn {Directive} %right
4899 Declare a terminal symbol (token type name) that is right-associative
4900 (@pxref{Precedence Decl, ,Operator Precedence}).
4901 @end deffn
4902
4903 @deffn {Directive} %left
4904 Declare a terminal symbol (token type name) that is left-associative
4905 (@pxref{Precedence Decl, ,Operator Precedence}).
4906 @end deffn
4907
4908 @deffn {Directive} %nonassoc
4909 Declare a terminal symbol (token type name) that is nonassociative
4910 (@pxref{Precedence Decl, ,Operator Precedence}).
4911 Using it in a way that would be associative is a syntax error.
4912 @end deffn
4913
4914 @ifset defaultprec
4915 @deffn {Directive} %default-prec
4916 Assign a precedence to rules lacking an explicit @code{%prec} modifier
4917 (@pxref{Contextual Precedence, ,Context-Dependent Precedence}).
4918 @end deffn
4919 @end ifset
4920
4921 @deffn {Directive} %type
4922 Declare the type of semantic values for a nonterminal symbol
4923 (@pxref{Type Decl, ,Nonterminal Symbols}).
4924 @end deffn
4925
4926 @deffn {Directive} %start
4927 Specify the grammar's start symbol (@pxref{Start Decl, ,The
4928 Start-Symbol}).
4929 @end deffn
4930
4931 @deffn {Directive} %expect
4932 Declare the expected number of shift-reduce conflicts
4933 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
4934 @end deffn
4935
4936
4937 @sp 1
4938 @noindent
4939 In order to change the behavior of @command{bison}, use the following
4940 directives:
4941
4942 @deffn {Directive} %code @{@var{code}@}
4943 @findex %code
4944 This is the unqualified form of the @code{%code} directive.
4945 It inserts @var{code} verbatim at a language-dependent default location in the
4946 output@footnote{The default location is actually skeleton-dependent;
4947 writers of non-standard skeletons however should choose the default location
4948 consistently with the behavior of the standard Bison skeletons.}.
4949
4950 @cindex Prologue
4951 For C/C++, the default location is the parser implementation file
4952 after the usual contents of the parser header file. Thus,
4953 @code{%code} replaces the traditional Yacc prologue,
4954 @code{%@{@var{code}%@}}, for most purposes. For a detailed
4955 discussion, see @ref{Prologue Alternatives}.
4956
4957 For Java, the default location is inside the parser class.
4958 @end deffn
4959
4960 @deffn {Directive} %code @var{qualifier} @{@var{code}@}
4961 This is the qualified form of the @code{%code} directive.
4962 If you need to specify location-sensitive verbatim @var{code} that does not
4963 belong at the default location selected by the unqualified @code{%code} form,
4964 use this form instead.
4965
4966 @var{qualifier} identifies the purpose of @var{code} and thus the location(s)
4967 where Bison should generate it.
4968 Not all @var{qualifier}s are accepted for all target languages.
4969 Unaccepted @var{qualifier}s produce an error.
4970 Some of the accepted @var{qualifier}s are:
4971
4972 @itemize @bullet
4973 @item requires
4974 @findex %code requires
4975
4976 @itemize @bullet
4977 @item Language(s): C, C++
4978
4979 @item Purpose: This is the best place to write dependency code required for
4980 @code{YYSTYPE} and @code{YYLTYPE}.
4981 In other words, it's the best place to define types referenced in @code{%union}
4982 directives, and it's the best place to override Bison's default @code{YYSTYPE}
4983 and @code{YYLTYPE} definitions.
4984
4985 @item Location(s): The parser header file and the parser implementation file
4986 before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
4987 definitions.
4988 @end itemize
4989
4990 @item provides
4991 @findex %code provides
4992
4993 @itemize @bullet
4994 @item Language(s): C, C++
4995
4996 @item Purpose: This is the best place to write additional definitions and
4997 declarations that should be provided to other modules.
4998
4999 @item Location(s): The parser header file and the parser implementation
5000 file after the Bison-generated @code{YYSTYPE}, @code{YYLTYPE}, and
5001 token definitions.
5002 @end itemize
5003
5004 @item top
5005 @findex %code top
5006
5007 @itemize @bullet
5008 @item Language(s): C, C++
5009
5010 @item Purpose: The unqualified @code{%code} or @code{%code requires}
5011 should usually be more appropriate than @code{%code top}. However,
5012 occasionally it is necessary to insert code much nearer the top of the
5013 parser implementation file. For example:
5014
5015 @smallexample
5016 %code top @{
5017 #define _GNU_SOURCE
5018 #include <stdio.h>
5019 @}
5020 @end smallexample
5021
5022 @item Location(s): Near the top of the parser implementation file.
5023 @end itemize
5024
5025 @item imports
5026 @findex %code imports
5027
5028 @itemize @bullet
5029 @item Language(s): Java
5030
5031 @item Purpose: This is the best place to write Java import directives.
5032
5033 @item Location(s): The parser Java file after any Java package directive and
5034 before any class definitions.
5035 @end itemize
5036 @end itemize
5037
5038 @cindex Prologue
5039 For a detailed discussion of how to use @code{%code} in place of the
5040 traditional Yacc prologue for C/C++, see @ref{Prologue Alternatives}.
5041 @end deffn
5042
5043 @deffn {Directive} %debug
5044 Instrument the output parser for traces. Obsoleted by @samp{%define
5045 parse.trace}.
5046 @xref{Tracing, ,Tracing Your Parser}.
5047 @end deffn
5048
5049 @deffn {Directive} %define @var{variable}
5050 @deffnx {Directive} %define @var{variable} @var{value}
5051 @deffnx {Directive} %define @var{variable} "@var{value}"
5052 Define a variable to adjust Bison's behavior.
5053
5054 It is an error if a @var{variable} is defined by @code{%define} multiple
5055 times, but see @ref{Bison Options,,-D @var{name}[=@var{value}]}.
5056
5057 @var{value} must be placed in quotation marks if it contains any character
5058 other than a letter, underscore, period, or non-initial dash or digit.
5059
5060 Omitting @code{"@var{value}"} entirely is always equivalent to specifying
5061 @code{""}.
5062
5063 Some @var{variable}s take Boolean values.
5064 In this case, Bison will complain if the variable definition does not meet one
5065 of the following four conditions:
5066
5067 @enumerate
5068 @item @code{@var{value}} is @code{true}
5069
5070 @item @code{@var{value}} is omitted (or @code{""} is specified).
5071 This is equivalent to @code{true}.
5072
5073 @item @code{@var{value}} is @code{false}.
5074
5075 @item @var{variable} is never defined.
5076 In this case, Bison selects a default value.
5077 @end enumerate
5078
5079 What @var{variable}s are accepted, as well as their meanings and default
5080 values, depend on the selected target language and/or the parser
5081 skeleton (@pxref{Decl Summary,,%language}, @pxref{Decl
5082 Summary,,%skeleton}).
5083 Unaccepted @var{variable}s produce an error.
5084 Some of the accepted @var{variable}s are:
5085
5086 @table @code
5087 @c ================================================== api.namespace
5088 @item api.namespace
5089 @findex %define api.namespace
5090 @itemize
5091 @item Languages(s): C++
5092
5093 @item Purpose: Specify the namespace for the parser class.
5094 For example, if you specify:
5095
5096 @smallexample
5097 %define api.namespace "foo::bar"
5098 @end smallexample
5099
5100 Bison uses @code{foo::bar} verbatim in references such as:
5101
5102 @smallexample
5103 foo::bar::parser::semantic_type
5104 @end smallexample
5105
5106 However, to open a namespace, Bison removes any leading @code{::} and then
5107 splits on any remaining occurrences:
5108
5109 @smallexample
5110 namespace foo @{ namespace bar @{
5111 class position;
5112 class location;
5113 @} @}
5114 @end smallexample
5115
5116 @item Accepted Values:
5117 Any absolute or relative C++ namespace reference without a trailing
5118 @code{"::"}. For example, @code{"foo"} or @code{"::foo::bar"}.
5119
5120 @item Default Value:
5121 The value specified by @code{%name-prefix}, which defaults to @code{yy}.
5122 This usage of @code{%name-prefix} is for backward compatibility and can
5123 be confusing since @code{%name-prefix} also specifies the textual prefix
5124 for the lexical analyzer function. Thus, if you specify
5125 @code{%name-prefix}, it is best to also specify @samp{%define
5126 api.namespace} so that @code{%name-prefix} @emph{only} affects the
5127 lexical analyzer function. For example, if you specify:
5128
5129 @smallexample
5130 %define api.namespace "foo"
5131 %name-prefix "bar::"
5132 @end smallexample
5133
5134 The parser namespace is @code{foo} and @code{yylex} is referenced as
5135 @code{bar::lex}.
5136 @end itemize
5137 @c namespace
5138
5139
5140
5141 @c ================================================== api.pure
5142 @item api.pure
5143 @findex %define api.pure
5144
5145 @itemize @bullet
5146 @item Language(s): C
5147
5148 @item Purpose: Request a pure (reentrant) parser program.
5149 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
5150
5151 @item Accepted Values: Boolean
5152
5153 @item Default Value: @code{false}
5154 @end itemize
5155 @c api.pure
5156
5157
5158
5159 @c ================================================== api.push-pull
5160 @item api.push-pull
5161 @findex %define api.push-pull
5162
5163 @itemize @bullet
5164 @item Language(s): C (deterministic parsers only)
5165
5166 @item Purpose: Request a pull parser, a push parser, or both.
5167 @xref{Push Decl, ,A Push Parser}.
5168 (The current push parsing interface is experimental and may evolve.
5169 More user feedback will help to stabilize it.)
5170
5171 @item Accepted Values: @code{pull}, @code{push}, @code{both}
5172
5173 @item Default Value: @code{pull}
5174 @end itemize
5175 @c api.push-pull
5176
5177
5178
5179 @c ================================================== api.tokens.prefix
5180 @item api.tokens.prefix
5181 @findex %define api.tokens.prefix
5182
5183 @itemize
5184 @item Languages(s): all
5185
5186 @item Purpose:
5187 Add a prefix to the token names when generating their definition in the
5188 target language. For instance
5189
5190 @example
5191 %token FILE for ERROR
5192 %define api.tokens.prefix "TOK_"
5193 %%
5194 start: FILE for ERROR;
5195 @end example
5196
5197 @noindent
5198 generates the definition of the symbols @code{TOK_FILE}, @code{TOK_for},
5199 and @code{TOK_ERROR} in the generated source files. In particular, the
5200 scanner must use these prefixed token names, while the grammar itself
5201 may still use the short names (as in the sample rule given above). The
5202 generated informational files (@file{*.output}, @file{*.xml},
5203 @file{*.dot}) are not modified by this prefix. See @ref{Calc++ Parser}
5204 and @ref{Calc++ Scanner}, for a complete example.
5205
5206 @item Accepted Values:
5207 Any string. Should be a valid identifier prefix in the target language,
5208 in other words, it should typically be an identifier itself (sequence of
5209 letters, underscores, and ---not at the beginning--- digits).
5210
5211 @item Default Value:
5212 empty
5213 @end itemize
5214 @c api.tokens.prefix
5215
5216
5217 @c ================================================== lex_symbol
5218 @item variant
5219 @findex %define lex_symbol
5220
5221 @itemize @bullet
5222 @item Language(s):
5223 C++
5224
5225 @item Purpose:
5226 When variant-based semantic values are enabled (@pxref{C++ Variants}),
5227 request that symbols be handled as a whole (type, value, and possibly
5228 location) in the scanner. @xref{Complete Symbols}, for details.
5229
5230 @item Accepted Values:
5231 Boolean.
5232
5233 @item Default Value:
5234 @code{false}
5235 @end itemize
5236 @c lex_symbol
5237
5238
5239 @c ================================================== lr.default-reductions
5240
5241 @item lr.default-reductions
5242 @cindex default reductions
5243 @findex %define lr.default-reductions
5244 @cindex delayed syntax errors
5245 @cindex syntax errors delayed
5246 @cindex LAC
5247 @findex %nonassoc
5248
5249 @itemize @bullet
5250 @item Language(s): all
5251
5252 @item Purpose: Specify the kind of states that are permitted to
5253 contain default reductions.
5254 That is, in such a state, Bison selects the reduction with the largest
5255 lookahead set to be the default parser action and then removes that
5256 lookahead set.
5257 (The ability to specify where default reductions should be used is
5258 experimental.
5259 More user feedback will help to stabilize it.)
5260
5261 @item Accepted Values:
5262 @itemize
5263 @item @code{all}.
5264 This is the traditional Bison behavior.
5265 The main advantage is a significant decrease in the size of the parser
5266 tables.
5267 The disadvantage is that, when the generated parser encounters a
5268 syntactically unacceptable token, the parser might then perform
5269 unnecessary default reductions before it can detect the syntax error.
5270 Such delayed syntax error detection is usually inherent in
5271 LALR and IELR parser tables anyway due to
5272 LR state merging (@pxref{Decl Summary,,lr.type}).
5273 Furthermore, the use of @code{%nonassoc} can contribute to delayed
5274 syntax error detection even in the case of canonical LR.
5275 As an experimental feature, delayed syntax error detection can be
5276 overcome in all cases by enabling LAC (@pxref{Decl
5277 Summary,,parse.lac}, for details, including a discussion of the effects
5278 of delayed syntax error detection).
5279
5280 @item @code{consistent}.
5281 @cindex consistent states
5282 A consistent state is a state that has only one possible action.
5283 If that action is a reduction, then the parser does not need to request
5284 a lookahead token from the scanner before performing that action.
5285 However, the parser recognizes the ability to ignore the lookahead token
5286 in this way only when such a reduction is encoded as a default
5287 reduction.
5288 Thus, if default reductions are permitted only in consistent states,
5289 then a canonical LR parser that does not employ
5290 @code{%nonassoc} detects a syntax error as soon as it @emph{needs} the
5291 syntactically unacceptable token from the scanner.
5292
5293 @item @code{accepting}.
5294 @cindex accepting state
5295 In the accepting state, the default reduction is actually the accept
5296 action.
5297 In this case, a canonical LR parser that does not employ
5298 @code{%nonassoc} detects a syntax error as soon as it @emph{reaches} the
5299 syntactically unacceptable token in the input.
5300 That is, it does not perform any extra reductions.
5301 @end itemize
5302
5303 @item Default Value:
5304 @itemize
5305 @item @code{accepting} if @code{lr.type} is @code{canonical-lr}.
5306 @item @code{all} otherwise.
5307 @end itemize
5308 @end itemize
5309
5310 @c ============================================ lr.keep-unreachable-states
5311
5312 @item lr.keep-unreachable-states
5313 @findex %define lr.keep-unreachable-states
5314
5315 @itemize @bullet
5316 @item Language(s): all
5317
5318 @item Purpose: Request that Bison allow unreachable parser states to
5319 remain in the parser tables.
5320 Bison considers a state to be unreachable if there exists no sequence of
5321 transitions from the start state to that state.
5322 A state can become unreachable during conflict resolution if Bison disables a
5323 shift action leading to it from a predecessor state.
5324 Keeping unreachable states is sometimes useful for analysis purposes, but they
5325 are useless in the generated parser.
5326
5327 @item Accepted Values: Boolean
5328
5329 @item Default Value: @code{false}
5330
5331 @item Caveats:
5332
5333 @itemize @bullet
5334
5335 @item Unreachable states may contain conflicts and may use rules not used in
5336 any other state.
5337 Thus, keeping unreachable states may induce warnings that are irrelevant to
5338 your parser's behavior, and it may eliminate warnings that are relevant.
5339 Of course, the change in warnings may actually be relevant to a parser table
5340 analysis that wants to keep unreachable states, so this behavior will likely
5341 remain in future Bison releases.
5342
5343 @item While Bison is able to remove unreachable states, it is not guaranteed to
5344 remove other kinds of useless states.
5345 Specifically, when Bison disables reduce actions during conflict resolution,
5346 some goto actions may become useless, and thus some additional states may
5347 become useless.
5348 If Bison were to compute which goto actions were useless and then disable those
5349 actions, it could identify such states as unreachable and then remove those
5350 states.
5351 However, Bison does not compute which goto actions are useless.
5352 @end itemize
5353 @end itemize
5354 @c lr.keep-unreachable-states
5355
5356 @c ================================================== lr.type
5357
5358 @item lr.type
5359 @findex %define lr.type
5360 @cindex LALR
5361 @cindex IELR
5362 @cindex LR
5363
5364 @itemize @bullet
5365 @item Language(s): all
5366
5367 @item Purpose: Specify the type of parser tables within the
5368 LR(1) family.
5369 (This feature is experimental.
5370 More user feedback will help to stabilize it.)
5371
5372 @item Accepted Values:
5373 @itemize
5374 @item @code{lalr}.
5375 While Bison generates LALR parser tables by default for
5376 historical reasons, IELR or canonical LR is almost
5377 always preferable for deterministic parsers.
5378 The trouble is that LALR parser tables can suffer from
5379 mysterious conflicts and thus may not accept the full set of sentences
5380 that IELR and canonical LR accept.
5381 @xref{Mystery Conflicts}, for details.
5382 However, there are at least two scenarios where LALR may be
5383 worthwhile:
5384 @itemize
5385 @cindex GLR with LALR
5386 @item When employing GLR parsers (@pxref{GLR Parsers}), if you
5387 do not resolve any conflicts statically (for example, with @code{%left}
5388 or @code{%prec}), then the parser explores all potential parses of any
5389 given input.
5390 In this case, the use of LALR parser tables is guaranteed not
5391 to alter the language accepted by the parser.
5392 LALR parser tables are the smallest parser tables Bison can
5393 currently generate, so they may be preferable.
5394 Nevertheless, once you begin to resolve conflicts statically,
5395 GLR begins to behave more like a deterministic parser, and so
5396 IELR and canonical LR can be helpful to avoid
5397 LALR's mysterious behavior.
5398
5399 @item Occasionally during development, an especially malformed grammar
5400 with a major recurring flaw may severely impede the IELR or
5401 canonical LR parser table generation algorithm.
5402 LALR can be a quick way to generate parser tables in order to
5403 investigate such problems while ignoring the more subtle differences
5404 from IELR and canonical LR.
5405 @end itemize
5406
5407 @item @code{ielr}.
5408 IELR is a minimal LR algorithm.
5409 That is, given any grammar (LR or non-LR),
5410 IELR and canonical LR always accept exactly the same
5411 set of sentences.
5412 However, as for LALR, the number of parser states is often an
5413 order of magnitude less for IELR than for canonical
5414 LR.
5415 More importantly, because canonical LR's extra parser states
5416 may contain duplicate conflicts in the case of non-LR
5417 grammars, the number of conflicts for IELR is often an order
5418 of magnitude less as well.
5419 This can significantly reduce the complexity of developing of a grammar.
5420
5421 @item @code{canonical-lr}.
5422 @cindex delayed syntax errors
5423 @cindex syntax errors delayed
5424 @cindex LAC
5425 @findex %nonassoc
5426 While inefficient, canonical LR parser tables can be an
5427 interesting means to explore a grammar because they have a property that
5428 IELR and LALR tables do not.
5429 That is, if @code{%nonassoc} is not used and default reductions are left
5430 disabled (@pxref{Decl Summary,,lr.default-reductions}), then, for every
5431 left context of every canonical LR state, the set of tokens
5432 accepted by that state is guaranteed to be the exact set of tokens that
5433 is syntactically acceptable in that left context.
5434 It might then seem that an advantage of canonical LR parsers
5435 in production is that, under the above constraints, they are guaranteed
5436 to detect a syntax error as soon as possible without performing any
5437 unnecessary reductions.
5438 However, IELR parsers using LAC (@pxref{Decl
5439 Summary,,parse.lac}) are also able to achieve this behavior without
5440 sacrificing @code{%nonassoc} or default reductions.
5441 @end itemize
5442
5443 @item Default Value: @code{lalr}
5444 @end itemize
5445
5446
5447 @c ================================================== namespace
5448 @item namespace
5449 @findex %define namespace
5450 Obsoleted by @code{api.namespace}
5451 @c namespace
5452
5453
5454 @c ================================================== parse.assert
5455 @item parse.assert
5456 @findex %define parse.assert
5457
5458 @itemize
5459 @item Languages(s): C++
5460
5461 @item Purpose: Issue runtime assertions to catch invalid uses.
5462 In C++, when variants are used (@pxref{C++ Variants}), symbols must be
5463 constructed and
5464 destroyed properly. This option checks these constraints.
5465
5466 @item Accepted Values: Boolean
5467
5468 @item Default Value: @code{false}
5469 @end itemize
5470 @c parse.assert
5471
5472
5473 @c ================================================== parse.error
5474 @item parse.error
5475 @findex %define parse.error
5476 @itemize
5477 @item Languages(s):
5478 all
5479 @item Purpose:
5480 Control the kind of error messages passed to the error reporting
5481 function. @xref{Error Reporting, ,The Error Reporting Function
5482 @code{yyerror}}.
5483 @item Accepted Values:
5484 @itemize
5485 @item @code{simple}
5486 Error messages passed to @code{yyerror} are simply @w{@code{"syntax
5487 error"}}.
5488 @item @code{verbose}
5489 Error messages report the unexpected token, and possibly the expected
5490 ones.
5491 @end itemize
5492
5493 @item Default Value:
5494 @code{simple}
5495 @end itemize
5496 @c parse.error
5497
5498
5499 @c ================================================== parse.lac
5500 @item parse.lac
5501 @findex %define parse.lac
5502 @cindex LAC
5503 @cindex lookahead correction
5504
5505 @itemize
5506 @item Languages(s): C
5507
5508 @item Purpose: Enable LAC (lookahead correction) to improve
5509 syntax error handling.
5510
5511 Canonical LR, IELR, and LALR can suffer
5512 from a couple of problems upon encountering a syntax error. First, the
5513 parser might perform additional parser stack reductions before
5514 discovering the syntax error. Such reductions perform user semantic
5515 actions that are unexpected because they are based on an invalid token,
5516 and they cause error recovery to begin in a different syntactic context
5517 than the one in which the invalid token was encountered. Second, when
5518 verbose error messages are enabled (with @code{%error-verbose} or
5519 @code{#define YYERROR_VERBOSE}), the expected token list in the syntax
5520 error message can both contain invalid tokens and omit valid tokens.
5521
5522 The culprits for the above problems are @code{%nonassoc}, default
5523 reductions in inconsistent states, and parser state merging. Thus,
5524 IELR and LALR suffer the most. Canonical
5525 LR can suffer only if @code{%nonassoc} is used or if default
5526 reductions are enabled for inconsistent states.
5527
5528 LAC is a new mechanism within the parsing algorithm that
5529 completely solves these problems for canonical LR,
5530 IELR, and LALR without sacrificing @code{%nonassoc},
5531 default reductions, or state mering. Conceptually, the mechanism is
5532 straight-forward. Whenever the parser fetches a new token from the
5533 scanner so that it can determine the next parser action, it immediately
5534 suspends normal parsing and performs an exploratory parse using a
5535 temporary copy of the normal parser state stack. During this
5536 exploratory parse, the parser does not perform user semantic actions.
5537 If the exploratory parse reaches a shift action, normal parsing then
5538 resumes on the normal parser stacks. If the exploratory parse reaches
5539 an error instead, the parser reports a syntax error. If verbose syntax
5540 error messages are enabled, the parser must then discover the list of
5541 expected tokens, so it performs a separate exploratory parse for each
5542 token in the grammar.
5543
5544 There is one subtlety about the use of LAC. That is, when in
5545 a consistent parser state with a default reduction, the parser will not
5546 attempt to fetch a token from the scanner because no lookahead is needed
5547 to determine the next parser action. Thus, whether default reductions
5548 are enabled in consistent states (@pxref{Decl
5549 Summary,,lr.default-reductions}) affects how soon the parser detects a
5550 syntax error: when it @emph{reaches} an erroneous token or when it
5551 eventually @emph{needs} that token as a lookahead. The latter behavior
5552 is probably more intuitive, so Bison currently provides no way to
5553 achieve the former behavior while default reductions are fully enabled.
5554
5555 Thus, when LAC is in use, for some fixed decision of whether
5556 to enable default reductions in consistent states, canonical
5557 LR and IELR behave exactly the same for both
5558 syntactically acceptable and syntactically unacceptable input. While
5559 LALR still does not support the full language-recognition
5560 power of canonical LR and IELR, LAC at
5561 least enables LALR's syntax error handling to correctly
5562 reflect LALR's language-recognition power.
5563
5564 Because LAC requires many parse actions to be performed twice,
5565 it can have a performance penalty. However, not all parse actions must
5566 be performed twice. Specifically, during a series of default reductions
5567 in consistent states and shift actions, the parser never has to initiate
5568 an exploratory parse. Moreover, the most time-consuming tasks in a
5569 parse are often the file I/O, the lexical analysis performed by the
5570 scanner, and the user's semantic actions, but none of these are
5571 performed during the exploratory parse. Finally, the base of the
5572 temporary stack used during an exploratory parse is a pointer into the
5573 normal parser state stack so that the stack is never physically copied.
5574 In our experience, the performance penalty of LAC has proven
5575 insignificant for practical grammars.
5576
5577 @item Accepted Values: @code{none}, @code{full}
5578
5579 @item Default Value: @code{none}
5580 @end itemize
5581 @c parse.lac
5582
5583 @c ================================================== parse.trace
5584 @item parse.trace
5585 @findex %define parse.trace
5586
5587 @itemize
5588 @item Languages(s): C, C++
5589
5590 @item Purpose: Require parser instrumentation for tracing.
5591 In C/C++, define the macro @code{YYDEBUG} to 1 in the parser implementation
5592 file if it is not already defined, so that the debugging facilities are
5593 compiled. @xref{Tracing, ,Tracing Your Parser}.
5594
5595 @item Accepted Values: Boolean
5596
5597 @item Default Value: @code{false}
5598 @end itemize
5599 @c parse.trace
5600
5601 @c ================================================== variant
5602 @item variant
5603 @findex %define variant
5604
5605 @itemize @bullet
5606 @item Language(s):
5607 C++
5608
5609 @item Purpose:
5610 Request variant-based semantic values.
5611 @xref{C++ Variants}.
5612
5613 @item Accepted Values:
5614 Boolean.
5615
5616 @item Default Value:
5617 @code{false}
5618 @end itemize
5619 @c variant
5620
5621
5622 @end table
5623 @end deffn
5624 @c ---------------------------------------------------------- %define
5625
5626 @deffn {Directive} %defines
5627 Write a parser header file containing macro definitions for the token
5628 type names defined in the grammar as well as a few other declarations.
5629 If the parser implementation file is named @file{@var{name}.c} then
5630 the parser header file is named @file{@var{name}.h}.
5631
5632 For C parsers, the parser header file declares @code{YYSTYPE} unless
5633 @code{YYSTYPE} is already defined as a macro or you have used a
5634 @code{<@var{type}>} tag without using @code{%union}. Therefore, if
5635 you are using a @code{%union} (@pxref{Multiple Types, ,More Than One
5636 Value Type}) with components that require other definitions, or if you
5637 have defined a @code{YYSTYPE} macro or type definition (@pxref{Value
5638 Type, ,Data Types of Semantic Values}), you need to arrange for these
5639 definitions to be propagated to all modules, e.g., by putting them in
5640 a prerequisite header that is included both by your parser and by any
5641 other module that needs @code{YYSTYPE}.
5642
5643 Unless your parser is pure, the parser header file declares
5644 @code{yylval} as an external variable. @xref{Pure Decl, ,A Pure
5645 (Reentrant) Parser}.
5646
5647 If you have also used locations, the parser header file declares
5648 @code{YYLTYPE} and @code{yylloc} using a protocol similar to that of
5649 the @code{YYSTYPE} macro and @code{yylval}. @xref{Locations,
5650 ,Tracking Locations}.
5651
5652 This parser header file is normally essential if you wish to put the
5653 definition of @code{yylex} in a separate source file, because
5654 @code{yylex} typically needs to be able to refer to the
5655 above-mentioned declarations and to the token type codes. @xref{Token
5656 Values, ,Semantic Values of Tokens}.
5657
5658 @findex %code requires
5659 @findex %code provides
5660 If you have declared @code{%code requires} or @code{%code provides}, the output
5661 header also contains their code.
5662 @xref{Decl Summary, ,%code}.
5663 @end deffn
5664
5665 @deffn {Directive} %defines @var{defines-file}
5666 Same as above, but save in the file @var{defines-file}.
5667 @end deffn
5668
5669 @deffn {Directive} %destructor
5670 Specify how the parser should reclaim the memory associated to
5671 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
5672 @end deffn
5673
5674 @deffn {Directive} %file-prefix "@var{prefix}"
5675 Specify a prefix to use for all Bison output file names. The names
5676 are chosen as if the grammar file were named @file{@var{prefix}.y}.
5677 @end deffn
5678
5679 @deffn {Directive} %language "@var{language}"
5680 Specify the programming language for the generated parser. Currently
5681 supported languages include C, C++, and Java.
5682 @var{language} is case-insensitive.
5683
5684 This directive is experimental and its effect may be modified in future
5685 releases.
5686 @end deffn
5687
5688 @deffn {Directive} %locations
5689 Generate the code processing the locations (@pxref{Action Features,
5690 ,Special Features for Use in Actions}). This mode is enabled as soon as
5691 the grammar uses the special @samp{@@@var{n}} tokens, but if your
5692 grammar does not use it, using @samp{%locations} allows for more
5693 accurate syntax error messages.
5694 @end deffn
5695
5696 @deffn {Directive} %name-prefix "@var{prefix}"
5697 Rename the external symbols used in the parser so that they start with
5698 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
5699 in C parsers
5700 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
5701 @code{yylval}, @code{yychar}, @code{yydebug}, and
5702 (if locations are used) @code{yylloc}. If you use a push parser,
5703 @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5704 @code{yypstate_new} and @code{yypstate_delete} will
5705 also be renamed. For example, if you use @samp{%name-prefix "c_"}, the
5706 names become @code{c_parse}, @code{c_lex}, and so on.
5707 For C++ parsers, see the @samp{%define api.namespace} documentation in this
5708 section.
5709 @xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
5710 @end deffn
5711
5712 @ifset defaultprec
5713 @deffn {Directive} %no-default-prec
5714 Do not assign a precedence to rules lacking an explicit @code{%prec}
5715 modifier (@pxref{Contextual Precedence, ,Context-Dependent
5716 Precedence}).
5717 @end deffn
5718 @end ifset
5719
5720 @deffn {Directive} %no-lines
5721 Don't generate any @code{#line} preprocessor commands in the parser
5722 implementation file. Ordinarily Bison writes these commands in the
5723 parser implementation file so that the C compiler and debuggers will
5724 associate errors and object code with your source file (the grammar
5725 file). This directive causes them to associate errors with the parser
5726 implementation file, treating it as an independent source file in its
5727 own right.
5728 @end deffn
5729
5730 @deffn {Directive} %output "@var{file}"
5731 Specify @var{file} for the parser implementation file.
5732 @end deffn
5733
5734 @deffn {Directive} %pure-parser
5735 Deprecated version of @samp{%define api.pure} (@pxref{Decl Summary, ,%define}),
5736 for which Bison is more careful to warn about unreasonable usage.
5737 @end deffn
5738
5739 @deffn {Directive} %require "@var{version}"
5740 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
5741 Require a Version of Bison}.
5742 @end deffn
5743
5744 @deffn {Directive} %skeleton "@var{file}"
5745 Specify the skeleton to use.
5746
5747 @c You probably don't need this option unless you are developing Bison.
5748 @c You should use @code{%language} if you want to specify the skeleton for a
5749 @c different language, because it is clearer and because it will always choose the
5750 @c correct skeleton for non-deterministic or push parsers.
5751
5752 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
5753 file in the Bison installation directory.
5754 If it does, @var{file} is an absolute file name or a file name relative to the
5755 directory of the grammar file.
5756 This is similar to how most shells resolve commands.
5757 @end deffn
5758
5759 @deffn {Directive} %token-table
5760 Generate an array of token names in the parser implementation file.
5761 The name of the array is @code{yytname}; @code{yytname[@var{i}]} is
5762 the name of the token whose internal Bison token code number is
5763 @var{i}. The first three elements of @code{yytname} correspond to the
5764 predefined tokens @code{"$end"}, @code{"error"}, and
5765 @code{"$undefined"}; after these come the symbols defined in the
5766 grammar file.
5767
5768 The name in the table includes all the characters needed to represent
5769 the token in Bison. For single-character literals and literal
5770 strings, this includes the surrounding quoting characters and any
5771 escape sequences. For example, the Bison single-character literal
5772 @code{'+'} corresponds to a three-character name, represented in C as
5773 @code{"'+'"}; and the Bison two-character literal string @code{"\\/"}
5774 corresponds to a five-character name, represented in C as
5775 @code{"\"\\\\/\""}.
5776
5777 When you specify @code{%token-table}, Bison also generates macro
5778 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
5779 @code{YYNRULES}, and @code{YYNSTATES}:
5780
5781 @table @code
5782 @item YYNTOKENS
5783 The highest token number, plus one.
5784 @item YYNNTS
5785 The number of nonterminal symbols.
5786 @item YYNRULES
5787 The number of grammar rules,
5788 @item YYNSTATES
5789 The number of parser states (@pxref{Parser States}).
5790 @end table
5791 @end deffn
5792
5793 @deffn {Directive} %verbose
5794 Write an extra output file containing verbose descriptions of the
5795 parser states and what is done for each type of lookahead token in
5796 that state. @xref{Understanding, , Understanding Your Parser}, for more
5797 information.
5798 @end deffn
5799
5800 @deffn {Directive} %yacc
5801 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
5802 including its naming conventions. @xref{Bison Options}, for more.
5803 @end deffn
5804
5805
5806 @node Multiple Parsers
5807 @section Multiple Parsers in the Same Program
5808
5809 Most programs that use Bison parse only one language and therefore contain
5810 only one Bison parser. But what if you want to parse more than one
5811 language with the same program? Then you need to avoid a name conflict
5812 between different definitions of @code{yyparse}, @code{yylval}, and so on.
5813
5814 The easy way to do this is to use the option @samp{-p @var{prefix}}
5815 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
5816 functions and variables of the Bison parser to start with @var{prefix}
5817 instead of @samp{yy}. You can use this to give each parser distinct
5818 names that do not conflict.
5819
5820 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
5821 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
5822 @code{yychar} and @code{yydebug}. If you use a push parser,
5823 @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5824 @code{yypstate_new} and @code{yypstate_delete} will also be renamed.
5825 For example, if you use @samp{-p c}, the names become @code{cparse},
5826 @code{clex}, and so on.
5827
5828 @strong{All the other variables and macros associated with Bison are not
5829 renamed.} These others are not global; there is no conflict if the same
5830 name is used in different parsers. For example, @code{YYSTYPE} is not
5831 renamed, but defining this in different ways in different parsers causes
5832 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
5833
5834 The @samp{-p} option works by adding macro definitions to the
5835 beginning of the parser implementation file, defining @code{yyparse}
5836 as @code{@var{prefix}parse}, and so on. This effectively substitutes
5837 one name for the other in the entire parser implementation file.
5838
5839 @node Interface
5840 @chapter Parser C-Language Interface
5841 @cindex C-language interface
5842 @cindex interface
5843
5844 The Bison parser is actually a C function named @code{yyparse}. Here we
5845 describe the interface conventions of @code{yyparse} and the other
5846 functions that it needs to use.
5847
5848 Keep in mind that the parser uses many C identifiers starting with
5849 @samp{yy} and @samp{YY} for internal purposes. If you use such an
5850 identifier (aside from those in this manual) in an action or in epilogue
5851 in the grammar file, you are likely to run into trouble.
5852
5853 @menu
5854 * Parser Function:: How to call @code{yyparse} and what it returns.
5855 * Push Parser Function:: How to call @code{yypush_parse} and what it returns.
5856 * Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
5857 * Parser Create Function:: How to call @code{yypstate_new} and what it returns.
5858 * Parser Delete Function:: How to call @code{yypstate_delete} and what it returns.
5859 * Lexical:: You must supply a function @code{yylex}
5860 which reads tokens.
5861 * Error Reporting:: You must supply a function @code{yyerror}.
5862 * Action Features:: Special features for use in actions.
5863 * Internationalization:: How to let the parser speak in the user's
5864 native language.
5865 @end menu
5866
5867 @node Parser Function
5868 @section The Parser Function @code{yyparse}
5869 @findex yyparse
5870
5871 You call the function @code{yyparse} to cause parsing to occur. This
5872 function reads tokens, executes actions, and ultimately returns when it
5873 encounters end-of-input or an unrecoverable syntax error. You can also
5874 write an action which directs @code{yyparse} to return immediately
5875 without reading further.
5876
5877
5878 @deftypefun int yyparse (void)
5879 The value returned by @code{yyparse} is 0 if parsing was successful (return
5880 is due to end-of-input).
5881
5882 The value is 1 if parsing failed because of invalid input, i.e., input
5883 that contains a syntax error or that causes @code{YYABORT} to be
5884 invoked.
5885
5886 The value is 2 if parsing failed due to memory exhaustion.
5887 @end deftypefun
5888
5889 In an action, you can cause immediate return from @code{yyparse} by using
5890 these macros:
5891
5892 @defmac YYACCEPT
5893 @findex YYACCEPT
5894 Return immediately with value 0 (to report success).
5895 @end defmac
5896
5897 @defmac YYABORT
5898 @findex YYABORT
5899 Return immediately with value 1 (to report failure).
5900 @end defmac
5901
5902 If you use a reentrant parser, you can optionally pass additional
5903 parameter information to it in a reentrant way. To do so, use the
5904 declaration @code{%parse-param}:
5905
5906 @deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
5907 @findex %parse-param
5908 Declare that one or more
5909 @var{argument-declaration} are additional @code{yyparse} arguments.
5910 The @var{argument-declaration} is used when declaring
5911 functions or prototypes. The last identifier in
5912 @var{argument-declaration} must be the argument name.
5913 @end deffn
5914
5915 Here's an example. Write this in the parser:
5916
5917 @example
5918 %parse-param @{int *nastiness@} @{int *randomness@}
5919 @end example
5920
5921 @noindent
5922 Then call the parser like this:
5923
5924 @example
5925 @{
5926 int nastiness, randomness;
5927 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
5928 value = yyparse (&nastiness, &randomness);
5929 @dots{}
5930 @}
5931 @end example
5932
5933 @noindent
5934 In the grammar actions, use expressions like this to refer to the data:
5935
5936 @example
5937 exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
5938 @end example
5939
5940 @node Push Parser Function
5941 @section The Push Parser Function @code{yypush_parse}
5942 @findex yypush_parse
5943
5944 (The current push parsing interface is experimental and may evolve.
5945 More user feedback will help to stabilize it.)
5946
5947 You call the function @code{yypush_parse} to parse a single token. This
5948 function is available if either the @samp{%define api.push-pull push} or
5949 @samp{%define api.push-pull both} declaration is used.
5950 @xref{Push Decl, ,A Push Parser}.
5951
5952 @deftypefun int yypush_parse (yypstate *yyps)
5953 The value returned by @code{yypush_parse} is the same as for yyparse with the
5954 following exception. @code{yypush_parse} will return YYPUSH_MORE if more input
5955 is required to finish parsing the grammar.
5956 @end deftypefun
5957
5958 @node Pull Parser Function
5959 @section The Pull Parser Function @code{yypull_parse}
5960 @findex yypull_parse
5961
5962 (The current push parsing interface is experimental and may evolve.
5963 More user feedback will help to stabilize it.)
5964
5965 You call the function @code{yypull_parse} to parse the rest of the input
5966 stream. This function is available if the @samp{%define api.push-pull both}
5967 declaration is used.
5968 @xref{Push Decl, ,A Push Parser}.
5969
5970 @deftypefun int yypull_parse (yypstate *yyps)
5971 The value returned by @code{yypull_parse} is the same as for @code{yyparse}.
5972 @end deftypefun
5973
5974 @node Parser Create Function
5975 @section The Parser Create Function @code{yystate_new}
5976 @findex yypstate_new
5977
5978 (The current push parsing interface is experimental and may evolve.
5979 More user feedback will help to stabilize it.)
5980
5981 You call the function @code{yypstate_new} to create a new parser instance.
5982 This function is available if either the @samp{%define api.push-pull push} or
5983 @samp{%define api.push-pull both} declaration is used.
5984 @xref{Push Decl, ,A Push Parser}.
5985
5986 @deftypefun yypstate *yypstate_new (void)
5987 The function will return a valid parser instance if there was memory available
5988 or 0 if no memory was available.
5989 In impure mode, it will also return 0 if a parser instance is currently
5990 allocated.
5991 @end deftypefun
5992
5993 @node Parser Delete Function
5994 @section The Parser Delete Function @code{yystate_delete}
5995 @findex yypstate_delete
5996
5997 (The current push parsing interface is experimental and may evolve.
5998 More user feedback will help to stabilize it.)
5999
6000 You call the function @code{yypstate_delete} to delete a parser instance.
6001 function is available if either the @samp{%define api.push-pull push} or
6002 @samp{%define api.push-pull both} declaration is used.
6003 @xref{Push Decl, ,A Push Parser}.
6004
6005 @deftypefun void yypstate_delete (yypstate *yyps)
6006 This function will reclaim the memory associated with a parser instance.
6007 After this call, you should no longer attempt to use the parser instance.
6008 @end deftypefun
6009
6010 @node Lexical
6011 @section The Lexical Analyzer Function @code{yylex}
6012 @findex yylex
6013 @cindex lexical analyzer
6014
6015 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
6016 the input stream and returns them to the parser. Bison does not create
6017 this function automatically; you must write it so that @code{yyparse} can
6018 call it. The function is sometimes referred to as a lexical scanner.
6019
6020 In simple programs, @code{yylex} is often defined at the end of the
6021 Bison grammar file. If @code{yylex} is defined in a separate source
6022 file, you need to arrange for the token-type macro definitions to be
6023 available there. To do this, use the @samp{-d} option when you run
6024 Bison, so that it will write these macro definitions into the separate
6025 parser header file, @file{@var{name}.tab.h}, which you can include in
6026 the other source files that need it. @xref{Invocation, ,Invoking
6027 Bison}.
6028
6029 @menu
6030 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
6031 * Token Values:: How @code{yylex} must return the semantic value
6032 of the token it has read.
6033 * Token Locations:: How @code{yylex} must return the text location
6034 (line number, etc.) of the token, if the
6035 actions want that.
6036 * Pure Calling:: How the calling convention differs in a pure parser
6037 (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
6038 @end menu
6039
6040 @node Calling Convention
6041 @subsection Calling Convention for @code{yylex}
6042
6043 The value that @code{yylex} returns must be the positive numeric code
6044 for the type of token it has just found; a zero or negative value
6045 signifies end-of-input.
6046
6047 When a token is referred to in the grammar rules by a name, that name
6048 in the parser implementation file becomes a C macro whose definition
6049 is the proper numeric code for that token type. So @code{yylex} can
6050 use the name to indicate that type. @xref{Symbols}.
6051
6052 When a token is referred to in the grammar rules by a character literal,
6053 the numeric code for that character is also the code for the token type.
6054 So @code{yylex} can simply return that character code, possibly converted
6055 to @code{unsigned char} to avoid sign-extension. The null character
6056 must not be used this way, because its code is zero and that
6057 signifies end-of-input.
6058
6059 Here is an example showing these things:
6060
6061 @example
6062 int
6063 yylex (void)
6064 @{
6065 @dots{}
6066 if (c == EOF) /* Detect end-of-input. */
6067 return 0;
6068 @dots{}
6069 if (c == '+' || c == '-')
6070 return c; /* Assume token type for `+' is '+'. */
6071 @dots{}
6072 return INT; /* Return the type of the token. */
6073 @dots{}
6074 @}
6075 @end example
6076
6077 @noindent
6078 This interface has been designed so that the output from the @code{lex}
6079 utility can be used without change as the definition of @code{yylex}.
6080
6081 If the grammar uses literal string tokens, there are two ways that
6082 @code{yylex} can determine the token type codes for them:
6083
6084 @itemize @bullet
6085 @item
6086 If the grammar defines symbolic token names as aliases for the
6087 literal string tokens, @code{yylex} can use these symbolic names like
6088 all others. In this case, the use of the literal string tokens in
6089 the grammar file has no effect on @code{yylex}.
6090
6091 @item
6092 @code{yylex} can find the multicharacter token in the @code{yytname}
6093 table. The index of the token in the table is the token type's code.
6094 The name of a multicharacter token is recorded in @code{yytname} with a
6095 double-quote, the token's characters, and another double-quote. The
6096 token's characters are escaped as necessary to be suitable as input
6097 to Bison.
6098
6099 Here's code for looking up a multicharacter token in @code{yytname},
6100 assuming that the characters of the token are stored in
6101 @code{token_buffer}, and assuming that the token does not contain any
6102 characters like @samp{"} that require escaping.
6103
6104 @smallexample
6105 for (i = 0; i < YYNTOKENS; i++)
6106 @{
6107 if (yytname[i] != 0
6108 && yytname[i][0] == '"'
6109 && ! strncmp (yytname[i] + 1, token_buffer,
6110 strlen (token_buffer))
6111 && yytname[i][strlen (token_buffer) + 1] == '"'
6112 && yytname[i][strlen (token_buffer) + 2] == 0)
6113 break;
6114 @}
6115 @end smallexample
6116
6117 The @code{yytname} table is generated only if you use the
6118 @code{%token-table} declaration. @xref{Decl Summary}.
6119 @end itemize
6120
6121 @node Token Values
6122 @subsection Semantic Values of Tokens
6123
6124 @vindex yylval
6125 In an ordinary (nonreentrant) parser, the semantic value of the token must
6126 be stored into the global variable @code{yylval}. When you are using
6127 just one data type for semantic values, @code{yylval} has that type.
6128 Thus, if the type is @code{int} (the default), you might write this in
6129 @code{yylex}:
6130
6131 @example
6132 @group
6133 @dots{}
6134 yylval = value; /* Put value onto Bison stack. */
6135 return INT; /* Return the type of the token. */
6136 @dots{}
6137 @end group
6138 @end example
6139
6140 When you are using multiple data types, @code{yylval}'s type is a union
6141 made from the @code{%union} declaration (@pxref{Union Decl, ,The
6142 Collection of Value Types}). So when you store a token's value, you
6143 must use the proper member of the union. If the @code{%union}
6144 declaration looks like this:
6145
6146 @example
6147 @group
6148 %union @{
6149 int intval;
6150 double val;
6151 symrec *tptr;
6152 @}
6153 @end group
6154 @end example
6155
6156 @noindent
6157 then the code in @code{yylex} might look like this:
6158
6159 @example
6160 @group
6161 @dots{}
6162 yylval.intval = value; /* Put value onto Bison stack. */
6163 return INT; /* Return the type of the token. */
6164 @dots{}
6165 @end group
6166 @end example
6167
6168 @node Token Locations
6169 @subsection Textual Locations of Tokens
6170
6171 @vindex yylloc
6172 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
6173 Tracking Locations}) in actions to keep track of the textual locations
6174 of tokens and groupings, then you must provide this information in
6175 @code{yylex}. The function @code{yyparse} expects to find the textual
6176 location of a token just parsed in the global variable @code{yylloc}.
6177 So @code{yylex} must store the proper data in that variable.
6178
6179 By default, the value of @code{yylloc} is a structure and you need only
6180 initialize the members that are going to be used by the actions. The
6181 four members are called @code{first_line}, @code{first_column},
6182 @code{last_line} and @code{last_column}. Note that the use of this
6183 feature makes the parser noticeably slower.
6184
6185 @tindex YYLTYPE
6186 The data type of @code{yylloc} has the name @code{YYLTYPE}.
6187
6188 @node Pure Calling
6189 @subsection Calling Conventions for Pure Parsers
6190
6191 When you use the Bison declaration @samp{%define api.pure} to request a
6192 pure, reentrant parser, the global communication variables @code{yylval}
6193 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
6194 Parser}.) In such parsers the two global variables are replaced by
6195 pointers passed as arguments to @code{yylex}. You must declare them as
6196 shown here, and pass the information back by storing it through those
6197 pointers.
6198
6199 @example
6200 int
6201 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
6202 @{
6203 @dots{}
6204 *lvalp = value; /* Put value onto Bison stack. */
6205 return INT; /* Return the type of the token. */
6206 @dots{}
6207 @}
6208 @end example
6209
6210 If the grammar file does not use the @samp{@@} constructs to refer to
6211 textual locations, then the type @code{YYLTYPE} will not be defined. In
6212 this case, omit the second argument; @code{yylex} will be called with
6213 only one argument.
6214
6215 If you wish to pass additional arguments to @code{yylex}, use
6216 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
6217 Function}). To pass additional arguments to both @code{yylex} and
6218 @code{yyparse}, use @code{%param}.
6219
6220 @deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
6221 @findex %lex-param
6222 Specify that @var{argument-declaration} are additional @code{yylex} argument
6223 declarations. You may pass one or more such declarations, which is
6224 equivalent to repeating @code{%lex-param}.
6225 @end deffn
6226
6227 @deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
6228 @findex %param
6229 Specify that @var{argument-declaration} are additional
6230 @code{yylex}/@code{yyparse} argument declaration. This is equivalent to
6231 @samp{%lex-param @{@var{argument-declaration}@} @dots{} %parse-param
6232 @{@var{argument-declaration}@} @dots{}}. You may pass one or more
6233 declarations, which is equivalent to repeating @code{%param}.
6234 @end deffn
6235
6236 For instance:
6237
6238 @example
6239 %lex-param @{scanner_mode *mode@}
6240 %parse-param @{parser_mode *mode@}
6241 %param @{environment_type *env@}
6242 @end example
6243
6244 @noindent
6245 results in the following signature:
6246
6247 @example
6248 int yylex (scanner_mode *mode, environment_type *env);
6249 int yyparse (parser_mode *mode, environment_type *env);
6250 @end example
6251
6252 If @samp{%define api.pure} is added:
6253
6254 @example
6255 int yylex (YYSTYPE *lvalp, scanner_mode *mode, environment_type *env);
6256 int yyparse (parser_mode *mode, environment_type *env);
6257 @end example
6258
6259 @noindent
6260 and finally, if both @samp{%define api.pure} and @code{%locations} are used:
6261
6262 @example
6263 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp,
6264 scanner_mode *mode, environment_type *env);
6265 int yyparse (parser_mode *mode, environment_type *env);
6266 @end example
6267
6268 @node Error Reporting
6269 @section The Error Reporting Function @code{yyerror}
6270 @cindex error reporting function
6271 @findex yyerror
6272 @cindex parse error
6273 @cindex syntax error
6274
6275 The Bison parser detects a @dfn{syntax error} (or @dfn{parse error})
6276 whenever it reads a token which cannot satisfy any syntax rule. An
6277 action in the grammar can also explicitly proclaim an error, using the
6278 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
6279 in Actions}).
6280
6281 The Bison parser expects to report the error by calling an error
6282 reporting function named @code{yyerror}, which you must supply. It is
6283 called by @code{yyparse} whenever a syntax error is found, and it
6284 receives one argument. For a syntax error, the string is normally
6285 @w{@code{"syntax error"}}.
6286
6287 @findex %define parse.error
6288 If you invoke @samp{%define parse.error verbose} in the Bison
6289 declarations section (@pxref{Bison Declarations, ,The Bison Declarations
6290 Section}), then Bison provides a more verbose and specific error message
6291 string instead of just plain @w{@code{"syntax error"}}.
6292
6293 The parser can detect one other kind of error: memory exhaustion. This
6294 can happen when the input contains constructions that are very deeply
6295 nested. It isn't likely you will encounter this, since the Bison
6296 parser normally extends its stack automatically up to a very large limit. But
6297 if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
6298 fashion, except that the argument string is @w{@code{"memory exhausted"}}.
6299
6300 In some cases diagnostics like @w{@code{"syntax error"}} are
6301 translated automatically from English to some other language before
6302 they are passed to @code{yyerror}. @xref{Internationalization}.
6303
6304 The following definition suffices in simple programs:
6305
6306 @example
6307 @group
6308 void
6309 yyerror (char const *s)
6310 @{
6311 @end group
6312 @group
6313 fprintf (stderr, "%s\n", s);
6314 @}
6315 @end group
6316 @end example
6317
6318 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
6319 error recovery if you have written suitable error recovery grammar rules
6320 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
6321 immediately return 1.
6322
6323 Obviously, in location tracking pure parsers, @code{yyerror} should have
6324 an access to the current location.
6325 This is indeed the case for the GLR
6326 parsers, but not for the Yacc parser, for historical reasons. I.e., if
6327 @samp{%locations %define api.pure} is passed then the prototypes for
6328 @code{yyerror} are:
6329
6330 @example
6331 void yyerror (char const *msg); /* Yacc parsers. */
6332 void yyerror (YYLTYPE *locp, char const *msg); /* GLR parsers. */
6333 @end example
6334
6335 If @samp{%parse-param @{int *nastiness@}} is used, then:
6336
6337 @example
6338 void yyerror (int *nastiness, char const *msg); /* Yacc parsers. */
6339 void yyerror (int *nastiness, char const *msg); /* GLR parsers. */
6340 @end example
6341
6342 Finally, GLR and Yacc parsers share the same @code{yyerror} calling
6343 convention for absolutely pure parsers, i.e., when the calling
6344 convention of @code{yylex} @emph{and} the calling convention of
6345 @samp{%define api.pure} are pure.
6346 I.e.:
6347
6348 @example
6349 /* Location tracking. */
6350 %locations
6351 /* Pure yylex. */
6352 %define api.pure
6353 %lex-param @{int *nastiness@}
6354 /* Pure yyparse. */
6355 %parse-param @{int *nastiness@}
6356 %parse-param @{int *randomness@}
6357 @end example
6358
6359 @noindent
6360 results in the following signatures for all the parser kinds:
6361
6362 @example
6363 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
6364 int yyparse (int *nastiness, int *randomness);
6365 void yyerror (YYLTYPE *locp,
6366 int *nastiness, int *randomness,
6367 char const *msg);
6368 @end example
6369
6370 @noindent
6371 The prototypes are only indications of how the code produced by Bison
6372 uses @code{yyerror}. Bison-generated code always ignores the returned
6373 value, so @code{yyerror} can return any type, including @code{void}.
6374 Also, @code{yyerror} can be a variadic function; that is why the
6375 message is always passed last.
6376
6377 Traditionally @code{yyerror} returns an @code{int} that is always
6378 ignored, but this is purely for historical reasons, and @code{void} is
6379 preferable since it more accurately describes the return type for
6380 @code{yyerror}.
6381
6382 @vindex yynerrs
6383 The variable @code{yynerrs} contains the number of syntax errors
6384 reported so far. Normally this variable is global; but if you
6385 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
6386 then it is a local variable which only the actions can access.
6387
6388 @node Action Features
6389 @section Special Features for Use in Actions
6390 @cindex summary, action features
6391 @cindex action features summary
6392
6393 Here is a table of Bison constructs, variables and macros that
6394 are useful in actions.
6395
6396 @deffn {Variable} $$
6397 Acts like a variable that contains the semantic value for the
6398 grouping made by the current rule. @xref{Actions}.
6399 @end deffn
6400
6401 @deffn {Variable} $@var{n}
6402 Acts like a variable that contains the semantic value for the
6403 @var{n}th component of the current rule. @xref{Actions}.
6404 @end deffn
6405
6406 @deffn {Variable} $<@var{typealt}>$
6407 Like @code{$$} but specifies alternative @var{typealt} in the union
6408 specified by the @code{%union} declaration. @xref{Action Types, ,Data
6409 Types of Values in Actions}.
6410 @end deffn
6411
6412 @deffn {Variable} $<@var{typealt}>@var{n}
6413 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
6414 union specified by the @code{%union} declaration.
6415 @xref{Action Types, ,Data Types of Values in Actions}.
6416 @end deffn
6417
6418 @deffn {Macro} YYABORT;
6419 Return immediately from @code{yyparse}, indicating failure.
6420 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6421 @end deffn
6422
6423 @deffn {Macro} YYACCEPT;
6424 Return immediately from @code{yyparse}, indicating success.
6425 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6426 @end deffn
6427
6428 @deffn {Macro} YYBACKUP (@var{token}, @var{value});
6429 @findex YYBACKUP
6430 Unshift a token. This macro is allowed only for rules that reduce
6431 a single value, and only when there is no lookahead token.
6432 It is also disallowed in GLR parsers.
6433 It installs a lookahead token with token type @var{token} and
6434 semantic value @var{value}; then it discards the value that was
6435 going to be reduced by this rule.
6436
6437 If the macro is used when it is not valid, such as when there is
6438 a lookahead token already, then it reports a syntax error with
6439 a message @samp{cannot back up} and performs ordinary error
6440 recovery.
6441
6442 In either case, the rest of the action is not executed.
6443 @end deffn
6444
6445 @deffn {Macro} YYEMPTY
6446 @vindex YYEMPTY
6447 Value stored in @code{yychar} when there is no lookahead token.
6448 @end deffn
6449
6450 @deffn {Macro} YYEOF
6451 @vindex YYEOF
6452 Value stored in @code{yychar} when the lookahead is the end of the input
6453 stream.
6454 @end deffn
6455
6456 @deffn {Macro} YYERROR;
6457 @findex YYERROR
6458 Cause an immediate syntax error. This statement initiates error
6459 recovery just as if the parser itself had detected an error; however, it
6460 does not call @code{yyerror}, and does not print any message. If you
6461 want to print an error message, call @code{yyerror} explicitly before
6462 the @samp{YYERROR;} statement. @xref{Error Recovery}.
6463 @end deffn
6464
6465 @deffn {Macro} YYRECOVERING
6466 @findex YYRECOVERING
6467 The expression @code{YYRECOVERING ()} yields 1 when the parser
6468 is recovering from a syntax error, and 0 otherwise.
6469 @xref{Error Recovery}.
6470 @end deffn
6471
6472 @deffn {Variable} yychar
6473 Variable containing either the lookahead token, or @code{YYEOF} when the
6474 lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
6475 has been performed so the next token is not yet known.
6476 Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
6477 Actions}).
6478 @xref{Lookahead, ,Lookahead Tokens}.
6479 @end deffn
6480
6481 @deffn {Macro} yyclearin;
6482 Discard the current lookahead token. This is useful primarily in
6483 error rules.
6484 Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
6485 Semantic Actions}).
6486 @xref{Error Recovery}.
6487 @end deffn
6488
6489 @deffn {Macro} yyerrok;
6490 Resume generating error messages immediately for subsequent syntax
6491 errors. This is useful primarily in error rules.
6492 @xref{Error Recovery}.
6493 @end deffn
6494
6495 @deffn {Variable} yylloc
6496 Variable containing the lookahead token location when @code{yychar} is not set
6497 to @code{YYEMPTY} or @code{YYEOF}.
6498 Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
6499 Actions}).
6500 @xref{Actions and Locations, ,Actions and Locations}.
6501 @end deffn
6502
6503 @deffn {Variable} yylval
6504 Variable containing the lookahead token semantic value when @code{yychar} is
6505 not set to @code{YYEMPTY} or @code{YYEOF}.
6506 Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
6507 Actions}).
6508 @xref{Actions, ,Actions}.
6509 @end deffn
6510
6511 @deffn {Value} @@$
6512 @findex @@$
6513 Acts like a structure variable containing information on the textual location
6514 of the grouping made by the current rule. @xref{Locations, ,
6515 Tracking Locations}.
6516
6517 @c Check if those paragraphs are still useful or not.
6518
6519 @c @example
6520 @c struct @{
6521 @c int first_line, last_line;
6522 @c int first_column, last_column;
6523 @c @};
6524 @c @end example
6525
6526 @c Thus, to get the starting line number of the third component, you would
6527 @c use @samp{@@3.first_line}.
6528
6529 @c In order for the members of this structure to contain valid information,
6530 @c you must make @code{yylex} supply this information about each token.
6531 @c If you need only certain members, then @code{yylex} need only fill in
6532 @c those members.
6533
6534 @c The use of this feature makes the parser noticeably slower.
6535 @end deffn
6536
6537 @deffn {Value} @@@var{n}
6538 @findex @@@var{n}
6539 Acts like a structure variable containing information on the textual location
6540 of the @var{n}th component of the current rule. @xref{Locations, ,
6541 Tracking Locations}.
6542 @end deffn
6543
6544 @node Internationalization
6545 @section Parser Internationalization
6546 @cindex internationalization
6547 @cindex i18n
6548 @cindex NLS
6549 @cindex gettext
6550 @cindex bison-po
6551
6552 A Bison-generated parser can print diagnostics, including error and
6553 tracing messages. By default, they appear in English. However, Bison
6554 also supports outputting diagnostics in the user's native language. To
6555 make this work, the user should set the usual environment variables.
6556 @xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
6557 For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
6558 set the user's locale to French Canadian using the UTF-8
6559 encoding. The exact set of available locales depends on the user's
6560 installation.
6561
6562 The maintainer of a package that uses a Bison-generated parser enables
6563 the internationalization of the parser's output through the following
6564 steps. Here we assume a package that uses GNU Autoconf and
6565 GNU Automake.
6566
6567 @enumerate
6568 @item
6569 @cindex bison-i18n.m4
6570 Into the directory containing the GNU Autoconf macros used
6571 by the package---often called @file{m4}---copy the
6572 @file{bison-i18n.m4} file installed by Bison under
6573 @samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
6574 For example:
6575
6576 @example
6577 cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
6578 @end example
6579
6580 @item
6581 @findex BISON_I18N
6582 @vindex BISON_LOCALEDIR
6583 @vindex YYENABLE_NLS
6584 In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
6585 invocation, add an invocation of @code{BISON_I18N}. This macro is
6586 defined in the file @file{bison-i18n.m4} that you copied earlier. It
6587 causes @samp{configure} to find the value of the
6588 @code{BISON_LOCALEDIR} variable, and it defines the source-language
6589 symbol @code{YYENABLE_NLS} to enable translations in the
6590 Bison-generated parser.
6591
6592 @item
6593 In the @code{main} function of your program, designate the directory
6594 containing Bison's runtime message catalog, through a call to
6595 @samp{bindtextdomain} with domain name @samp{bison-runtime}.
6596 For example:
6597
6598 @example
6599 bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
6600 @end example
6601
6602 Typically this appears after any other call @code{bindtextdomain
6603 (PACKAGE, LOCALEDIR)} that your package already has. Here we rely on
6604 @samp{BISON_LOCALEDIR} to be defined as a string through the
6605 @file{Makefile}.
6606
6607 @item
6608 In the @file{Makefile.am} that controls the compilation of the @code{main}
6609 function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
6610 either in @samp{DEFS} or in @samp{AM_CPPFLAGS}. For example:
6611
6612 @example
6613 DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6614 @end example
6615
6616 or:
6617
6618 @example
6619 AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6620 @end example
6621
6622 @item
6623 Finally, invoke the command @command{autoreconf} to generate the build
6624 infrastructure.
6625 @end enumerate
6626
6627
6628 @node Algorithm
6629 @chapter The Bison Parser Algorithm
6630 @cindex Bison parser algorithm
6631 @cindex algorithm of parser
6632 @cindex shifting
6633 @cindex reduction
6634 @cindex parser stack
6635 @cindex stack, parser
6636
6637 As Bison reads tokens, it pushes them onto a stack along with their
6638 semantic values. The stack is called the @dfn{parser stack}. Pushing a
6639 token is traditionally called @dfn{shifting}.
6640
6641 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
6642 @samp{3} to come. The stack will have four elements, one for each token
6643 that was shifted.
6644
6645 But the stack does not always have an element for each token read. When
6646 the last @var{n} tokens and groupings shifted match the components of a
6647 grammar rule, they can be combined according to that rule. This is called
6648 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
6649 single grouping whose symbol is the result (left hand side) of that rule.
6650 Running the rule's action is part of the process of reduction, because this
6651 is what computes the semantic value of the resulting grouping.
6652
6653 For example, if the infix calculator's parser stack contains this:
6654
6655 @example
6656 1 + 5 * 3
6657 @end example
6658
6659 @noindent
6660 and the next input token is a newline character, then the last three
6661 elements can be reduced to 15 via the rule:
6662
6663 @example
6664 expr: expr '*' expr;
6665 @end example
6666
6667 @noindent
6668 Then the stack contains just these three elements:
6669
6670 @example
6671 1 + 15
6672 @end example
6673
6674 @noindent
6675 At this point, another reduction can be made, resulting in the single value
6676 16. Then the newline token can be shifted.
6677
6678 The parser tries, by shifts and reductions, to reduce the entire input down
6679 to a single grouping whose symbol is the grammar's start-symbol
6680 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
6681
6682 This kind of parser is known in the literature as a bottom-up parser.
6683
6684 @menu
6685 * Lookahead:: Parser looks one token ahead when deciding what to do.
6686 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
6687 * Precedence:: Operator precedence works by resolving conflicts.
6688 * Contextual Precedence:: When an operator's precedence depends on context.
6689 * Parser States:: The parser is a finite-state-machine with stack.
6690 * Reduce/Reduce:: When two rules are applicable in the same situation.
6691 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
6692 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
6693 * Memory Management:: What happens when memory is exhausted. How to avoid it.
6694 @end menu
6695
6696 @node Lookahead
6697 @section Lookahead Tokens
6698 @cindex lookahead token
6699
6700 The Bison parser does @emph{not} always reduce immediately as soon as the
6701 last @var{n} tokens and groupings match a rule. This is because such a
6702 simple strategy is inadequate to handle most languages. Instead, when a
6703 reduction is possible, the parser sometimes ``looks ahead'' at the next
6704 token in order to decide what to do.
6705
6706 When a token is read, it is not immediately shifted; first it becomes the
6707 @dfn{lookahead token}, which is not on the stack. Now the parser can
6708 perform one or more reductions of tokens and groupings on the stack, while
6709 the lookahead token remains off to the side. When no more reductions
6710 should take place, the lookahead token is shifted onto the stack. This
6711 does not mean that all possible reductions have been done; depending on the
6712 token type of the lookahead token, some rules may choose to delay their
6713 application.
6714
6715 Here is a simple case where lookahead is needed. These three rules define
6716 expressions which contain binary addition operators and postfix unary
6717 factorial operators (@samp{!}), and allow parentheses for grouping.
6718
6719 @example
6720 @group
6721 expr: term '+' expr
6722 | term
6723 ;
6724 @end group
6725
6726 @group
6727 term: '(' expr ')'
6728 | term '!'
6729 | NUMBER
6730 ;
6731 @end group
6732 @end example
6733
6734 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
6735 should be done? If the following token is @samp{)}, then the first three
6736 tokens must be reduced to form an @code{expr}. This is the only valid
6737 course, because shifting the @samp{)} would produce a sequence of symbols
6738 @w{@code{term ')'}}, and no rule allows this.
6739
6740 If the following token is @samp{!}, then it must be shifted immediately so
6741 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
6742 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
6743 @code{expr}. It would then be impossible to shift the @samp{!} because
6744 doing so would produce on the stack the sequence of symbols @code{expr
6745 '!'}. No rule allows that sequence.
6746
6747 @vindex yychar
6748 @vindex yylval
6749 @vindex yylloc
6750 The lookahead token is stored in the variable @code{yychar}.
6751 Its semantic value and location, if any, are stored in the variables
6752 @code{yylval} and @code{yylloc}.
6753 @xref{Action Features, ,Special Features for Use in Actions}.
6754
6755 @node Shift/Reduce
6756 @section Shift/Reduce Conflicts
6757 @cindex conflicts
6758 @cindex shift/reduce conflicts
6759 @cindex dangling @code{else}
6760 @cindex @code{else}, dangling
6761
6762 Suppose we are parsing a language which has if-then and if-then-else
6763 statements, with a pair of rules like this:
6764
6765 @example
6766 @group
6767 if_stmt:
6768 IF expr THEN stmt
6769 | IF expr THEN stmt ELSE stmt
6770 ;
6771 @end group
6772 @end example
6773
6774 @noindent
6775 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
6776 terminal symbols for specific keyword tokens.
6777
6778 When the @code{ELSE} token is read and becomes the lookahead token, the
6779 contents of the stack (assuming the input is valid) are just right for
6780 reduction by the first rule. But it is also legitimate to shift the
6781 @code{ELSE}, because that would lead to eventual reduction by the second
6782 rule.
6783
6784 This situation, where either a shift or a reduction would be valid, is
6785 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
6786 these conflicts by choosing to shift, unless otherwise directed by
6787 operator precedence declarations. To see the reason for this, let's
6788 contrast it with the other alternative.
6789
6790 Since the parser prefers to shift the @code{ELSE}, the result is to attach
6791 the else-clause to the innermost if-statement, making these two inputs
6792 equivalent:
6793
6794 @example
6795 if x then if y then win (); else lose;
6796
6797 if x then do; if y then win (); else lose; end;
6798 @end example
6799
6800 But if the parser chose to reduce when possible rather than shift, the
6801 result would be to attach the else-clause to the outermost if-statement,
6802 making these two inputs equivalent:
6803
6804 @example
6805 if x then if y then win (); else lose;
6806
6807 if x then do; if y then win (); end; else lose;
6808 @end example
6809
6810 The conflict exists because the grammar as written is ambiguous: either
6811 parsing of the simple nested if-statement is legitimate. The established
6812 convention is that these ambiguities are resolved by attaching the
6813 else-clause to the innermost if-statement; this is what Bison accomplishes
6814 by choosing to shift rather than reduce. (It would ideally be cleaner to
6815 write an unambiguous grammar, but that is very hard to do in this case.)
6816 This particular ambiguity was first encountered in the specifications of
6817 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
6818
6819 To avoid warnings from Bison about predictable, legitimate shift/reduce
6820 conflicts, use the @code{%expect @var{n}} declaration.
6821 There will be no warning as long as the number of shift/reduce conflicts
6822 is exactly @var{n}, and Bison will report an error if there is a
6823 different number.
6824 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
6825
6826 The definition of @code{if_stmt} above is solely to blame for the
6827 conflict, but the conflict does not actually appear without additional
6828 rules. Here is a complete Bison grammar file that actually manifests
6829 the conflict:
6830
6831 @example
6832 @group
6833 %token IF THEN ELSE variable
6834 %%
6835 @end group
6836 @group
6837 stmt: expr
6838 | if_stmt
6839 ;
6840 @end group
6841
6842 @group
6843 if_stmt:
6844 IF expr THEN stmt
6845 | IF expr THEN stmt ELSE stmt
6846 ;
6847 @end group
6848
6849 expr: variable
6850 ;
6851 @end example
6852
6853 @node Precedence
6854 @section Operator Precedence
6855 @cindex operator precedence
6856 @cindex precedence of operators
6857
6858 Another situation where shift/reduce conflicts appear is in arithmetic
6859 expressions. Here shifting is not always the preferred resolution; the
6860 Bison declarations for operator precedence allow you to specify when to
6861 shift and when to reduce.
6862
6863 @menu
6864 * Why Precedence:: An example showing why precedence is needed.
6865 * Using Precedence:: How to specify precedence and associativity.
6866 * Precedence Only:: How to specify precedence only.
6867 * Precedence Examples:: How these features are used in the previous example.
6868 * How Precedence:: How they work.
6869 @end menu
6870
6871 @node Why Precedence
6872 @subsection When Precedence is Needed
6873
6874 Consider the following ambiguous grammar fragment (ambiguous because the
6875 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
6876
6877 @example
6878 @group
6879 expr: expr '-' expr
6880 | expr '*' expr
6881 | expr '<' expr
6882 | '(' expr ')'
6883 @dots{}
6884 ;
6885 @end group
6886 @end example
6887
6888 @noindent
6889 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
6890 should it reduce them via the rule for the subtraction operator? It
6891 depends on the next token. Of course, if the next token is @samp{)}, we
6892 must reduce; shifting is invalid because no single rule can reduce the
6893 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
6894 the next token is @samp{*} or @samp{<}, we have a choice: either
6895 shifting or reduction would allow the parse to complete, but with
6896 different results.
6897
6898 To decide which one Bison should do, we must consider the results. If
6899 the next operator token @var{op} is shifted, then it must be reduced
6900 first in order to permit another opportunity to reduce the difference.
6901 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
6902 hand, if the subtraction is reduced before shifting @var{op}, the result
6903 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
6904 reduce should depend on the relative precedence of the operators
6905 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
6906 @samp{<}.
6907
6908 @cindex associativity
6909 What about input such as @w{@samp{1 - 2 - 5}}; should this be
6910 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
6911 operators we prefer the former, which is called @dfn{left association}.
6912 The latter alternative, @dfn{right association}, is desirable for
6913 assignment operators. The choice of left or right association is a
6914 matter of whether the parser chooses to shift or reduce when the stack
6915 contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
6916 makes right-associativity.
6917
6918 @node Using Precedence
6919 @subsection Specifying Operator Precedence
6920 @findex %left
6921 @findex %nonassoc
6922 @findex %precedence
6923 @findex %right
6924
6925 Bison allows you to specify these choices with the operator precedence
6926 declarations @code{%left} and @code{%right}. Each such declaration
6927 contains a list of tokens, which are operators whose precedence and
6928 associativity is being declared. The @code{%left} declaration makes all
6929 those operators left-associative and the @code{%right} declaration makes
6930 them right-associative. A third alternative is @code{%nonassoc}, which
6931 declares that it is a syntax error to find the same operator twice ``in a
6932 row''.
6933 The last alternative, @code{%precedence}, allows to define only
6934 precedence and no associativity at all. As a result, any
6935 associativity-related conflict that remains will be reported as an
6936 compile-time error. The directive @code{%nonassoc} creates run-time
6937 error: using the operator in a associative way is a syntax error. The
6938 directive @code{%precedence} creates compile-time errors: an operator
6939 @emph{can} be involved in an associativity-related conflict, contrary to
6940 what expected the grammar author.
6941
6942 The relative precedence of different operators is controlled by the
6943 order in which they are declared. The first precedence/associativity
6944 declaration in the file declares the operators whose
6945 precedence is lowest, the next such declaration declares the operators
6946 whose precedence is a little higher, and so on.
6947
6948 @node Precedence Only
6949 @subsection Specifying Precedence Only
6950 @findex %precedence
6951
6952 Since POSIX Yacc defines only @code{%left}, @code{%right}, and
6953 @code{%nonassoc}, which all defines precedence and associativity, little
6954 attention is paid to the fact that precedence cannot be defined without
6955 defining associativity. Yet, sometimes, when trying to solve a
6956 conflict, precedence suffices. In such a case, using @code{%left},
6957 @code{%right}, or @code{%nonassoc} might hide future (associativity
6958 related) conflicts that would remain hidden.
6959
6960 The dangling @code{else} ambiguity (@pxref{Shift/Reduce, , Shift/Reduce
6961 Conflicts}) can be solved explicitly. This shift/reduce conflicts occurs
6962 in the following situation, where the period denotes the current parsing
6963 state:
6964
6965 @example
6966 if @var{e1} then if @var{e2} then @var{s1} . else @var{s2}
6967 @end example
6968
6969 The conflict involves the reduction of the rule @samp{IF expr THEN
6970 stmt}, which precedence is by default that of its last token
6971 (@code{THEN}), and the shifting of the token @code{ELSE}. The usual
6972 disambiguation (attach the @code{else} to the closest @code{if}),
6973 shifting must be preferred, i.e., the precedence of @code{ELSE} must be
6974 higher than that of @code{THEN}. But neither is expected to be involved
6975 in an associativity related conflict, which can be specified as follows.
6976
6977 @example
6978 %precedence THEN
6979 %precedence ELSE
6980 @end example
6981
6982 The unary-minus is another typical example where associativity is
6983 usually over-specified, see @ref{Infix Calc, , Infix Notation
6984 Calculator: @code{calc}}. The @code{%left} directive is traditionally
6985 used to declare the precedence of @code{NEG}, which is more than needed
6986 since it also defines its associativity. While this is harmless in the
6987 traditional example, who knows how @code{NEG} might be used in future
6988 evolutions of the grammar@dots{}
6989
6990 @node Precedence Examples
6991 @subsection Precedence Examples
6992
6993 In our example, we would want the following declarations:
6994
6995 @example
6996 %left '<'
6997 %left '-'
6998 %left '*'
6999 @end example
7000
7001 In a more complete example, which supports other operators as well, we
7002 would declare them in groups of equal precedence. For example, @code{'+'} is
7003 declared with @code{'-'}:
7004
7005 @example
7006 %left '<' '>' '=' NE LE GE
7007 %left '+' '-'
7008 %left '*' '/'
7009 @end example
7010
7011 @noindent
7012 (Here @code{NE} and so on stand for the operators for ``not equal''
7013 and so on. We assume that these tokens are more than one character long
7014 and therefore are represented by names, not character literals.)
7015
7016 @node How Precedence
7017 @subsection How Precedence Works
7018
7019 The first effect of the precedence declarations is to assign precedence
7020 levels to the terminal symbols declared. The second effect is to assign
7021 precedence levels to certain rules: each rule gets its precedence from
7022 the last terminal symbol mentioned in the components. (You can also
7023 specify explicitly the precedence of a rule. @xref{Contextual
7024 Precedence, ,Context-Dependent Precedence}.)
7025
7026 Finally, the resolution of conflicts works by comparing the precedence
7027 of the rule being considered with that of the lookahead token. If the
7028 token's precedence is higher, the choice is to shift. If the rule's
7029 precedence is higher, the choice is to reduce. If they have equal
7030 precedence, the choice is made based on the associativity of that
7031 precedence level. The verbose output file made by @samp{-v}
7032 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
7033 resolved.
7034
7035 Not all rules and not all tokens have precedence. If either the rule or
7036 the lookahead token has no precedence, then the default is to shift.
7037
7038 @node Contextual Precedence
7039 @section Context-Dependent Precedence
7040 @cindex context-dependent precedence
7041 @cindex unary operator precedence
7042 @cindex precedence, context-dependent
7043 @cindex precedence, unary operator
7044 @findex %prec
7045
7046 Often the precedence of an operator depends on the context. This sounds
7047 outlandish at first, but it is really very common. For example, a minus
7048 sign typically has a very high precedence as a unary operator, and a
7049 somewhat lower precedence (lower than multiplication) as a binary operator.
7050
7051 The Bison precedence declarations
7052 can only be used once for a given token; so a token has
7053 only one precedence declared in this way. For context-dependent
7054 precedence, you need to use an additional mechanism: the @code{%prec}
7055 modifier for rules.
7056
7057 The @code{%prec} modifier declares the precedence of a particular rule by
7058 specifying a terminal symbol whose precedence should be used for that rule.
7059 It's not necessary for that symbol to appear otherwise in the rule. The
7060 modifier's syntax is:
7061
7062 @example
7063 %prec @var{terminal-symbol}
7064 @end example
7065
7066 @noindent
7067 and it is written after the components of the rule. Its effect is to
7068 assign the rule the precedence of @var{terminal-symbol}, overriding
7069 the precedence that would be deduced for it in the ordinary way. The
7070 altered rule precedence then affects how conflicts involving that rule
7071 are resolved (@pxref{Precedence, ,Operator Precedence}).
7072
7073 Here is how @code{%prec} solves the problem of unary minus. First, declare
7074 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
7075 are no tokens of this type, but the symbol serves to stand for its
7076 precedence:
7077
7078 @example
7079 @dots{}
7080 %left '+' '-'
7081 %left '*'
7082 %left UMINUS
7083 @end example
7084
7085 Now the precedence of @code{UMINUS} can be used in specific rules:
7086
7087 @example
7088 @group
7089 exp: @dots{}
7090 | exp '-' exp
7091 @dots{}
7092 | '-' exp %prec UMINUS
7093 @end group
7094 @end example
7095
7096 @ifset defaultprec
7097 If you forget to append @code{%prec UMINUS} to the rule for unary
7098 minus, Bison silently assumes that minus has its usual precedence.
7099 This kind of problem can be tricky to debug, since one typically
7100 discovers the mistake only by testing the code.
7101
7102 The @code{%no-default-prec;} declaration makes it easier to discover
7103 this kind of problem systematically. It causes rules that lack a
7104 @code{%prec} modifier to have no precedence, even if the last terminal
7105 symbol mentioned in their components has a declared precedence.
7106
7107 If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
7108 for all rules that participate in precedence conflict resolution.
7109 Then you will see any shift/reduce conflict until you tell Bison how
7110 to resolve it, either by changing your grammar or by adding an
7111 explicit precedence. This will probably add declarations to the
7112 grammar, but it helps to protect against incorrect rule precedences.
7113
7114 The effect of @code{%no-default-prec;} can be reversed by giving
7115 @code{%default-prec;}, which is the default.
7116 @end ifset
7117
7118 @node Parser States
7119 @section Parser States
7120 @cindex finite-state machine
7121 @cindex parser state
7122 @cindex state (of parser)
7123
7124 The function @code{yyparse} is implemented using a finite-state machine.
7125 The values pushed on the parser stack are not simply token type codes; they
7126 represent the entire sequence of terminal and nonterminal symbols at or
7127 near the top of the stack. The current state collects all the information
7128 about previous input which is relevant to deciding what to do next.
7129
7130 Each time a lookahead token is read, the current parser state together
7131 with the type of lookahead token are looked up in a table. This table
7132 entry can say, ``Shift the lookahead token.'' In this case, it also
7133 specifies the new parser state, which is pushed onto the top of the
7134 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
7135 This means that a certain number of tokens or groupings are taken off
7136 the top of the stack, and replaced by one grouping. In other words,
7137 that number of states are popped from the stack, and one new state is
7138 pushed.
7139
7140 There is one other alternative: the table can say that the lookahead token
7141 is erroneous in the current state. This causes error processing to begin
7142 (@pxref{Error Recovery}).
7143
7144 @node Reduce/Reduce
7145 @section Reduce/Reduce Conflicts
7146 @cindex reduce/reduce conflict
7147 @cindex conflicts, reduce/reduce
7148
7149 A reduce/reduce conflict occurs if there are two or more rules that apply
7150 to the same sequence of input. This usually indicates a serious error
7151 in the grammar.
7152
7153 For example, here is an erroneous attempt to define a sequence
7154 of zero or more @code{word} groupings.
7155
7156 @example
7157 sequence: /* empty */
7158 @{ printf ("empty sequence\n"); @}
7159 | maybeword
7160 | sequence word
7161 @{ printf ("added word %s\n", $2); @}
7162 ;
7163
7164 maybeword: /* empty */
7165 @{ printf ("empty maybeword\n"); @}
7166 | word
7167 @{ printf ("single word %s\n", $1); @}
7168 ;
7169 @end example
7170
7171 @noindent
7172 The error is an ambiguity: there is more than one way to parse a single
7173 @code{word} into a @code{sequence}. It could be reduced to a
7174 @code{maybeword} and then into a @code{sequence} via the second rule.
7175 Alternatively, nothing-at-all could be reduced into a @code{sequence}
7176 via the first rule, and this could be combined with the @code{word}
7177 using the third rule for @code{sequence}.
7178
7179 There is also more than one way to reduce nothing-at-all into a
7180 @code{sequence}. This can be done directly via the first rule,
7181 or indirectly via @code{maybeword} and then the second rule.
7182
7183 You might think that this is a distinction without a difference, because it
7184 does not change whether any particular input is valid or not. But it does
7185 affect which actions are run. One parsing order runs the second rule's
7186 action; the other runs the first rule's action and the third rule's action.
7187 In this example, the output of the program changes.
7188
7189 Bison resolves a reduce/reduce conflict by choosing to use the rule that
7190 appears first in the grammar, but it is very risky to rely on this. Every
7191 reduce/reduce conflict must be studied and usually eliminated. Here is the
7192 proper way to define @code{sequence}:
7193
7194 @example
7195 sequence: /* empty */
7196 @{ printf ("empty sequence\n"); @}
7197 | sequence word
7198 @{ printf ("added word %s\n", $2); @}
7199 ;
7200 @end example
7201
7202 Here is another common error that yields a reduce/reduce conflict:
7203
7204 @example
7205 sequence: /* empty */
7206 | sequence words
7207 | sequence redirects
7208 ;
7209
7210 words: /* empty */
7211 | words word
7212 ;
7213
7214 redirects:/* empty */
7215 | redirects redirect
7216 ;
7217 @end example
7218
7219 @noindent
7220 The intention here is to define a sequence which can contain either
7221 @code{word} or @code{redirect} groupings. The individual definitions of
7222 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
7223 three together make a subtle ambiguity: even an empty input can be parsed
7224 in infinitely many ways!
7225
7226 Consider: nothing-at-all could be a @code{words}. Or it could be two
7227 @code{words} in a row, or three, or any number. It could equally well be a
7228 @code{redirects}, or two, or any number. Or it could be a @code{words}
7229 followed by three @code{redirects} and another @code{words}. And so on.
7230
7231 Here are two ways to correct these rules. First, to make it a single level
7232 of sequence:
7233
7234 @example
7235 sequence: /* empty */
7236 | sequence word
7237 | sequence redirect
7238 ;
7239 @end example
7240
7241 Second, to prevent either a @code{words} or a @code{redirects}
7242 from being empty:
7243
7244 @example
7245 sequence: /* empty */
7246 | sequence words
7247 | sequence redirects
7248 ;
7249
7250 words: word
7251 | words word
7252 ;
7253
7254 redirects:redirect
7255 | redirects redirect
7256 ;
7257 @end example
7258
7259 @node Mystery Conflicts
7260 @section Mysterious Reduce/Reduce Conflicts
7261
7262 Sometimes reduce/reduce conflicts can occur that don't look warranted.
7263 Here is an example:
7264
7265 @example
7266 @group
7267 %token ID
7268
7269 %%
7270 def: param_spec return_spec ','
7271 ;
7272 param_spec:
7273 type
7274 | name_list ':' type
7275 ;
7276 @end group
7277 @group
7278 return_spec:
7279 type
7280 | name ':' type
7281 ;
7282 @end group
7283 @group
7284 type: ID
7285 ;
7286 @end group
7287 @group
7288 name: ID
7289 ;
7290 name_list:
7291 name
7292 | name ',' name_list
7293 ;
7294 @end group
7295 @end example
7296
7297 It would seem that this grammar can be parsed with only a single token
7298 of lookahead: when a @code{param_spec} is being read, an @code{ID} is
7299 a @code{name} if a comma or colon follows, or a @code{type} if another
7300 @code{ID} follows. In other words, this grammar is LR(1).
7301
7302 @cindex LR(1)
7303 @cindex LALR(1)
7304 However, for historical reasons, Bison cannot by default handle all
7305 LR(1) grammars.
7306 In this grammar, two contexts, that after an @code{ID} at the beginning
7307 of a @code{param_spec} and likewise at the beginning of a
7308 @code{return_spec}, are similar enough that Bison assumes they are the
7309 same.
7310 They appear similar because the same set of rules would be
7311 active---the rule for reducing to a @code{name} and that for reducing to
7312 a @code{type}. Bison is unable to determine at that stage of processing
7313 that the rules would require different lookahead tokens in the two
7314 contexts, so it makes a single parser state for them both. Combining
7315 the two contexts causes a conflict later. In parser terminology, this
7316 occurrence means that the grammar is not LALR(1).
7317
7318 For many practical grammars (specifically those that fall into the
7319 non-LR(1) class), the limitations of LALR(1) result in
7320 difficulties beyond just mysterious reduce/reduce conflicts.
7321 The best way to fix all these problems is to select a different parser
7322 table generation algorithm.
7323 Either IELR(1) or canonical LR(1) would suffice, but
7324 the former is more efficient and easier to debug during development.
7325 @xref{Decl Summary,,lr.type}, for details.
7326 (Bison's IELR(1) and canonical LR(1) implementations
7327 are experimental.
7328 More user feedback will help to stabilize them.)
7329
7330 If you instead wish to work around LALR(1)'s limitations, you
7331 can often fix a mysterious conflict by identifying the two parser states
7332 that are being confused, and adding something to make them look
7333 distinct. In the above example, adding one rule to
7334 @code{return_spec} as follows makes the problem go away:
7335
7336 @example
7337 @group
7338 %token BOGUS
7339 @dots{}
7340 %%
7341 @dots{}
7342 return_spec:
7343 type
7344 | name ':' type
7345 /* This rule is never used. */
7346 | ID BOGUS
7347 ;
7348 @end group
7349 @end example
7350
7351 This corrects the problem because it introduces the possibility of an
7352 additional active rule in the context after the @code{ID} at the beginning of
7353 @code{return_spec}. This rule is not active in the corresponding context
7354 in a @code{param_spec}, so the two contexts receive distinct parser states.
7355 As long as the token @code{BOGUS} is never generated by @code{yylex},
7356 the added rule cannot alter the way actual input is parsed.
7357
7358 In this particular example, there is another way to solve the problem:
7359 rewrite the rule for @code{return_spec} to use @code{ID} directly
7360 instead of via @code{name}. This also causes the two confusing
7361 contexts to have different sets of active rules, because the one for
7362 @code{return_spec} activates the altered rule for @code{return_spec}
7363 rather than the one for @code{name}.
7364
7365 @example
7366 param_spec:
7367 type
7368 | name_list ':' type
7369 ;
7370 return_spec:
7371 type
7372 | ID ':' type
7373 ;
7374 @end example
7375
7376 For a more detailed exposition of LALR(1) parsers and parser
7377 generators, please see:
7378 Frank DeRemer and Thomas Pennello, Efficient Computation of
7379 LALR(1) Look-Ahead Sets, @cite{ACM Transactions on
7380 Programming Languages and Systems}, Vol.@: 4, No.@: 4 (October 1982),
7381 pp.@: 615--649 @uref{http://doi.acm.org/10.1145/69622.357187}.
7382
7383 @node Generalized LR Parsing
7384 @section Generalized LR (GLR) Parsing
7385 @cindex GLR parsing
7386 @cindex generalized LR (GLR) parsing
7387 @cindex ambiguous grammars
7388 @cindex nondeterministic parsing
7389
7390 Bison produces @emph{deterministic} parsers that choose uniquely
7391 when to reduce and which reduction to apply
7392 based on a summary of the preceding input and on one extra token of lookahead.
7393 As a result, normal Bison handles a proper subset of the family of
7394 context-free languages.
7395 Ambiguous grammars, since they have strings with more than one possible
7396 sequence of reductions cannot have deterministic parsers in this sense.
7397 The same is true of languages that require more than one symbol of
7398 lookahead, since the parser lacks the information necessary to make a
7399 decision at the point it must be made in a shift-reduce parser.
7400 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
7401 there are languages where Bison's default choice of how to
7402 summarize the input seen so far loses necessary information.
7403
7404 When you use the @samp{%glr-parser} declaration in your grammar file,
7405 Bison generates a parser that uses a different algorithm, called
7406 Generalized LR (or GLR). A Bison GLR
7407 parser uses the same basic
7408 algorithm for parsing as an ordinary Bison parser, but behaves
7409 differently in cases where there is a shift-reduce conflict that has not
7410 been resolved by precedence rules (@pxref{Precedence}) or a
7411 reduce-reduce conflict. When a GLR parser encounters such a
7412 situation, it
7413 effectively @emph{splits} into a several parsers, one for each possible
7414 shift or reduction. These parsers then proceed as usual, consuming
7415 tokens in lock-step. Some of the stacks may encounter other conflicts
7416 and split further, with the result that instead of a sequence of states,
7417 a Bison GLR parsing stack is what is in effect a tree of states.
7418
7419 In effect, each stack represents a guess as to what the proper parse
7420 is. Additional input may indicate that a guess was wrong, in which case
7421 the appropriate stack silently disappears. Otherwise, the semantics
7422 actions generated in each stack are saved, rather than being executed
7423 immediately. When a stack disappears, its saved semantic actions never
7424 get executed. When a reduction causes two stacks to become equivalent,
7425 their sets of semantic actions are both saved with the state that
7426 results from the reduction. We say that two stacks are equivalent
7427 when they both represent the same sequence of states,
7428 and each pair of corresponding states represents a
7429 grammar symbol that produces the same segment of the input token
7430 stream.
7431
7432 Whenever the parser makes a transition from having multiple
7433 states to having one, it reverts to the normal deterministic parsing
7434 algorithm, after resolving and executing the saved-up actions.
7435 At this transition, some of the states on the stack will have semantic
7436 values that are sets (actually multisets) of possible actions. The
7437 parser tries to pick one of the actions by first finding one whose rule
7438 has the highest dynamic precedence, as set by the @samp{%dprec}
7439 declaration. Otherwise, if the alternative actions are not ordered by
7440 precedence, but there the same merging function is declared for both
7441 rules by the @samp{%merge} declaration,
7442 Bison resolves and evaluates both and then calls the merge function on
7443 the result. Otherwise, it reports an ambiguity.
7444
7445 It is possible to use a data structure for the GLR parsing tree that
7446 permits the processing of any LR(1) grammar in linear time (in the
7447 size of the input), any unambiguous (not necessarily
7448 LR(1)) grammar in
7449 quadratic worst-case time, and any general (possibly ambiguous)
7450 context-free grammar in cubic worst-case time. However, Bison currently
7451 uses a simpler data structure that requires time proportional to the
7452 length of the input times the maximum number of stacks required for any
7453 prefix of the input. Thus, really ambiguous or nondeterministic
7454 grammars can require exponential time and space to process. Such badly
7455 behaving examples, however, are not generally of practical interest.
7456 Usually, nondeterminism in a grammar is local---the parser is ``in
7457 doubt'' only for a few tokens at a time. Therefore, the current data
7458 structure should generally be adequate. On LR(1) portions of a
7459 grammar, in particular, it is only slightly slower than with the
7460 deterministic LR(1) Bison parser.
7461
7462 For a more detailed exposition of GLR parsers, please see: Elizabeth
7463 Scott, Adrian Johnstone and Shamsa Sadaf Hussain, Tomita-Style
7464 Generalised LR Parsers, Royal Holloway, University of
7465 London, Department of Computer Science, TR-00-12,
7466 @uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps},
7467 (2000-12-24).
7468
7469 @node Memory Management
7470 @section Memory Management, and How to Avoid Memory Exhaustion
7471 @cindex memory exhaustion
7472 @cindex memory management
7473 @cindex stack overflow
7474 @cindex parser stack overflow
7475 @cindex overflow of parser stack
7476
7477 The Bison parser stack can run out of memory if too many tokens are shifted and
7478 not reduced. When this happens, the parser function @code{yyparse}
7479 calls @code{yyerror} and then returns 2.
7480
7481 Because Bison parsers have growing stacks, hitting the upper limit
7482 usually results from using a right recursion instead of a left
7483 recursion, @xref{Recursion, ,Recursive Rules}.
7484
7485 @vindex YYMAXDEPTH
7486 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
7487 parser stack can become before memory is exhausted. Define the
7488 macro with a value that is an integer. This value is the maximum number
7489 of tokens that can be shifted (and not reduced) before overflow.
7490
7491 The stack space allowed is not necessarily allocated. If you specify a
7492 large value for @code{YYMAXDEPTH}, the parser normally allocates a small
7493 stack at first, and then makes it bigger by stages as needed. This
7494 increasing allocation happens automatically and silently. Therefore,
7495 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
7496 space for ordinary inputs that do not need much stack.
7497
7498 However, do not allow @code{YYMAXDEPTH} to be a value so large that
7499 arithmetic overflow could occur when calculating the size of the stack
7500 space. Also, do not allow @code{YYMAXDEPTH} to be less than
7501 @code{YYINITDEPTH}.
7502
7503 @cindex default stack limit
7504 The default value of @code{YYMAXDEPTH}, if you do not define it, is
7505 10000.
7506
7507 @vindex YYINITDEPTH
7508 You can control how much stack is allocated initially by defining the
7509 macro @code{YYINITDEPTH} to a positive integer. For the deterministic
7510 parser in C, this value must be a compile-time constant
7511 unless you are assuming C99 or some other target language or compiler
7512 that allows variable-length arrays. The default is 200.
7513
7514 Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
7515
7516 You can generate a deterministic parser containing C++ user code from
7517 the default (C) skeleton, as well as from the C++ skeleton
7518 (@pxref{C++ Parsers}). However, if you do use the default skeleton
7519 and want to allow the parsing stack to grow,
7520 be careful not to use semantic types or location types that require
7521 non-trivial copy constructors.
7522 The C skeleton bypasses these constructors when copying data to
7523 new, larger stacks.
7524
7525 @node Error Recovery
7526 @chapter Error Recovery
7527 @cindex error recovery
7528 @cindex recovery from errors
7529
7530 It is not usually acceptable to have a program terminate on a syntax
7531 error. For example, a compiler should recover sufficiently to parse the
7532 rest of the input file and check it for errors; a calculator should accept
7533 another expression.
7534
7535 In a simple interactive command parser where each input is one line, it may
7536 be sufficient to allow @code{yyparse} to return 1 on error and have the
7537 caller ignore the rest of the input line when that happens (and then call
7538 @code{yyparse} again). But this is inadequate for a compiler, because it
7539 forgets all the syntactic context leading up to the error. A syntax error
7540 deep within a function in the compiler input should not cause the compiler
7541 to treat the following line like the beginning of a source file.
7542
7543 @findex error
7544 You can define how to recover from a syntax error by writing rules to
7545 recognize the special token @code{error}. This is a terminal symbol that
7546 is always defined (you need not declare it) and reserved for error
7547 handling. The Bison parser generates an @code{error} token whenever a
7548 syntax error happens; if you have provided a rule to recognize this token
7549 in the current context, the parse can continue.
7550
7551 For example:
7552
7553 @example
7554 stmnts: /* empty string */
7555 | stmnts '\n'
7556 | stmnts exp '\n'
7557 | stmnts error '\n'
7558 @end example
7559
7560 The fourth rule in this example says that an error followed by a newline
7561 makes a valid addition to any @code{stmnts}.
7562
7563 What happens if a syntax error occurs in the middle of an @code{exp}? The
7564 error recovery rule, interpreted strictly, applies to the precise sequence
7565 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
7566 the middle of an @code{exp}, there will probably be some additional tokens
7567 and subexpressions on the stack after the last @code{stmnts}, and there
7568 will be tokens to read before the next newline. So the rule is not
7569 applicable in the ordinary way.
7570
7571 But Bison can force the situation to fit the rule, by discarding part of
7572 the semantic context and part of the input. First it discards states
7573 and objects from the stack until it gets back to a state in which the
7574 @code{error} token is acceptable. (This means that the subexpressions
7575 already parsed are discarded, back to the last complete @code{stmnts}.)
7576 At this point the @code{error} token can be shifted. Then, if the old
7577 lookahead token is not acceptable to be shifted next, the parser reads
7578 tokens and discards them until it finds a token which is acceptable. In
7579 this example, Bison reads and discards input until the next newline so
7580 that the fourth rule can apply. Note that discarded symbols are
7581 possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
7582 Discarded Symbols}, for a means to reclaim this memory.
7583
7584 The choice of error rules in the grammar is a choice of strategies for
7585 error recovery. A simple and useful strategy is simply to skip the rest of
7586 the current input line or current statement if an error is detected:
7587
7588 @example
7589 stmnt: error ';' /* On error, skip until ';' is read. */
7590 @end example
7591
7592 It is also useful to recover to the matching close-delimiter of an
7593 opening-delimiter that has already been parsed. Otherwise the
7594 close-delimiter will probably appear to be unmatched, and generate another,
7595 spurious error message:
7596
7597 @example
7598 primary: '(' expr ')'
7599 | '(' error ')'
7600 @dots{}
7601 ;
7602 @end example
7603
7604 Error recovery strategies are necessarily guesses. When they guess wrong,
7605 one syntax error often leads to another. In the above example, the error
7606 recovery rule guesses that an error is due to bad input within one
7607 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
7608 middle of a valid @code{stmnt}. After the error recovery rule recovers
7609 from the first error, another syntax error will be found straightaway,
7610 since the text following the spurious semicolon is also an invalid
7611 @code{stmnt}.
7612
7613 To prevent an outpouring of error messages, the parser will output no error
7614 message for another syntax error that happens shortly after the first; only
7615 after three consecutive input tokens have been successfully shifted will
7616 error messages resume.
7617
7618 Note that rules which accept the @code{error} token may have actions, just
7619 as any other rules can.
7620
7621 @findex yyerrok
7622 You can make error messages resume immediately by using the macro
7623 @code{yyerrok} in an action. If you do this in the error rule's action, no
7624 error messages will be suppressed. This macro requires no arguments;
7625 @samp{yyerrok;} is a valid C statement.
7626
7627 @findex yyclearin
7628 The previous lookahead token is reanalyzed immediately after an error. If
7629 this is unacceptable, then the macro @code{yyclearin} may be used to clear
7630 this token. Write the statement @samp{yyclearin;} in the error rule's
7631 action.
7632 @xref{Action Features, ,Special Features for Use in Actions}.
7633
7634 For example, suppose that on a syntax error, an error handling routine is
7635 called that advances the input stream to some point where parsing should
7636 once again commence. The next symbol returned by the lexical scanner is
7637 probably correct. The previous lookahead token ought to be discarded
7638 with @samp{yyclearin;}.
7639
7640 @vindex YYRECOVERING
7641 The expression @code{YYRECOVERING ()} yields 1 when the parser
7642 is recovering from a syntax error, and 0 otherwise.
7643 Syntax error diagnostics are suppressed while recovering from a syntax
7644 error.
7645
7646 @node Context Dependency
7647 @chapter Handling Context Dependencies
7648
7649 The Bison paradigm is to parse tokens first, then group them into larger
7650 syntactic units. In many languages, the meaning of a token is affected by
7651 its context. Although this violates the Bison paradigm, certain techniques
7652 (known as @dfn{kludges}) may enable you to write Bison parsers for such
7653 languages.
7654
7655 @menu
7656 * Semantic Tokens:: Token parsing can depend on the semantic context.
7657 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
7658 * Tie-in Recovery:: Lexical tie-ins have implications for how
7659 error recovery rules must be written.
7660 @end menu
7661
7662 (Actually, ``kludge'' means any technique that gets its job done but is
7663 neither clean nor robust.)
7664
7665 @node Semantic Tokens
7666 @section Semantic Info in Token Types
7667
7668 The C language has a context dependency: the way an identifier is used
7669 depends on what its current meaning is. For example, consider this:
7670
7671 @example
7672 foo (x);
7673 @end example
7674
7675 This looks like a function call statement, but if @code{foo} is a typedef
7676 name, then this is actually a declaration of @code{x}. How can a Bison
7677 parser for C decide how to parse this input?
7678
7679 The method used in GNU C is to have two different token types,
7680 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
7681 identifier, it looks up the current declaration of the identifier in order
7682 to decide which token type to return: @code{TYPENAME} if the identifier is
7683 declared as a typedef, @code{IDENTIFIER} otherwise.
7684
7685 The grammar rules can then express the context dependency by the choice of
7686 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
7687 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
7688 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
7689 is @emph{not} significant, such as in declarations that can shadow a
7690 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
7691 accepted---there is one rule for each of the two token types.
7692
7693 This technique is simple to use if the decision of which kinds of
7694 identifiers to allow is made at a place close to where the identifier is
7695 parsed. But in C this is not always so: C allows a declaration to
7696 redeclare a typedef name provided an explicit type has been specified
7697 earlier:
7698
7699 @example
7700 typedef int foo, bar;
7701 int baz (void)
7702 @{
7703 static bar (bar); /* @r{redeclare @code{bar} as static variable} */
7704 extern foo foo (foo); /* @r{redeclare @code{foo} as function} */
7705 return foo (bar);
7706 @}
7707 @end example
7708
7709 Unfortunately, the name being declared is separated from the declaration
7710 construct itself by a complicated syntactic structure---the ``declarator''.
7711
7712 As a result, part of the Bison parser for C needs to be duplicated, with
7713 all the nonterminal names changed: once for parsing a declaration in
7714 which a typedef name can be redefined, and once for parsing a
7715 declaration in which that can't be done. Here is a part of the
7716 duplication, with actions omitted for brevity:
7717
7718 @example
7719 initdcl:
7720 declarator maybeasm '='
7721 init
7722 | declarator maybeasm
7723 ;
7724
7725 notype_initdcl:
7726 notype_declarator maybeasm '='
7727 init
7728 | notype_declarator maybeasm
7729 ;
7730 @end example
7731
7732 @noindent
7733 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
7734 cannot. The distinction between @code{declarator} and
7735 @code{notype_declarator} is the same sort of thing.
7736
7737 There is some similarity between this technique and a lexical tie-in
7738 (described next), in that information which alters the lexical analysis is
7739 changed during parsing by other parts of the program. The difference is
7740 here the information is global, and is used for other purposes in the
7741 program. A true lexical tie-in has a special-purpose flag controlled by
7742 the syntactic context.
7743
7744 @node Lexical Tie-ins
7745 @section Lexical Tie-ins
7746 @cindex lexical tie-in
7747
7748 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
7749 which is set by Bison actions, whose purpose is to alter the way tokens are
7750 parsed.
7751
7752 For example, suppose we have a language vaguely like C, but with a special
7753 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
7754 an expression in parentheses in which all integers are hexadecimal. In
7755 particular, the token @samp{a1b} must be treated as an integer rather than
7756 as an identifier if it appears in that context. Here is how you can do it:
7757
7758 @example
7759 @group
7760 %@{
7761 int hexflag;
7762 int yylex (void);
7763 void yyerror (char const *);
7764 %@}
7765 %%
7766 @dots{}
7767 @end group
7768 @group
7769 expr: IDENTIFIER
7770 | constant
7771 | HEX '('
7772 @{ hexflag = 1; @}
7773 expr ')'
7774 @{ hexflag = 0;
7775 $$ = $4; @}
7776 | expr '+' expr
7777 @{ $$ = make_sum ($1, $3); @}
7778 @dots{}
7779 ;
7780 @end group
7781
7782 @group
7783 constant:
7784 INTEGER
7785 | STRING
7786 ;
7787 @end group
7788 @end example
7789
7790 @noindent
7791 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
7792 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
7793 with letters are parsed as integers if possible.
7794
7795 The declaration of @code{hexflag} shown in the prologue of the grammar
7796 file is needed to make it accessible to the actions (@pxref{Prologue,
7797 ,The Prologue}). You must also write the code in @code{yylex} to obey
7798 the flag.
7799
7800 @node Tie-in Recovery
7801 @section Lexical Tie-ins and Error Recovery
7802
7803 Lexical tie-ins make strict demands on any error recovery rules you have.
7804 @xref{Error Recovery}.
7805
7806 The reason for this is that the purpose of an error recovery rule is to
7807 abort the parsing of one construct and resume in some larger construct.
7808 For example, in C-like languages, a typical error recovery rule is to skip
7809 tokens until the next semicolon, and then start a new statement, like this:
7810
7811 @example
7812 stmt: expr ';'
7813 | IF '(' expr ')' stmt @{ @dots{} @}
7814 @dots{}
7815 error ';'
7816 @{ hexflag = 0; @}
7817 ;
7818 @end example
7819
7820 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
7821 construct, this error rule will apply, and then the action for the
7822 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
7823 remain set for the entire rest of the input, or until the next @code{hex}
7824 keyword, causing identifiers to be misinterpreted as integers.
7825
7826 To avoid this problem the error recovery rule itself clears @code{hexflag}.
7827
7828 There may also be an error recovery rule that works within expressions.
7829 For example, there could be a rule which applies within parentheses
7830 and skips to the close-parenthesis:
7831
7832 @example
7833 @group
7834 expr: @dots{}
7835 | '(' expr ')'
7836 @{ $$ = $2; @}
7837 | '(' error ')'
7838 @dots{}
7839 @end group
7840 @end example
7841
7842 If this rule acts within the @code{hex} construct, it is not going to abort
7843 that construct (since it applies to an inner level of parentheses within
7844 the construct). Therefore, it should not clear the flag: the rest of
7845 the @code{hex} construct should be parsed with the flag still in effect.
7846
7847 What if there is an error recovery rule which might abort out of the
7848 @code{hex} construct or might not, depending on circumstances? There is no
7849 way you can write the action to determine whether a @code{hex} construct is
7850 being aborted or not. So if you are using a lexical tie-in, you had better
7851 make sure your error recovery rules are not of this kind. Each rule must
7852 be such that you can be sure that it always will, or always won't, have to
7853 clear the flag.
7854
7855 @c ================================================== Debugging Your Parser
7856
7857 @node Debugging
7858 @chapter Debugging Your Parser
7859
7860 Developing a parser can be a challenge, especially if you don't
7861 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
7862 Algorithm}). Even so, sometimes a detailed description of the automaton
7863 can help (@pxref{Understanding, , Understanding Your Parser}), or
7864 tracing the execution of the parser can give some insight on why it
7865 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
7866
7867 @menu
7868 * Understanding:: Understanding the structure of your parser.
7869 * Tracing:: Tracing the execution of your parser.
7870 @end menu
7871
7872 @node Understanding
7873 @section Understanding Your Parser
7874
7875 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
7876 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
7877 frequent than one would hope), looking at this automaton is required to
7878 tune or simply fix a parser. Bison provides two different
7879 representation of it, either textually or graphically (as a DOT file).
7880
7881 The textual file is generated when the options @option{--report} or
7882 @option{--verbose} are specified, see @xref{Invocation, , Invoking
7883 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
7884 the parser implementation file name, and adding @samp{.output}
7885 instead. Therefore, if the grammar file is @file{foo.y}, then the
7886 parser implementation file is called @file{foo.tab.c} by default. As
7887 a consequence, the verbose output file is called @file{foo.output}.
7888
7889 The following grammar file, @file{calc.y}, will be used in the sequel:
7890
7891 @example
7892 %token NUM STR
7893 %left '+' '-'
7894 %left '*'
7895 %%
7896 exp: exp '+' exp
7897 | exp '-' exp
7898 | exp '*' exp
7899 | exp '/' exp
7900 | NUM
7901 ;
7902 useless: STR;
7903 %%
7904 @end example
7905
7906 @command{bison} reports:
7907
7908 @example
7909 calc.y: warning: 1 nonterminal useless in grammar
7910 calc.y: warning: 1 rule useless in grammar
7911 calc.y:11.1-7: warning: nonterminal useless in grammar: useless
7912 calc.y:11.10-12: warning: rule useless in grammar: useless: STR
7913 calc.y: conflicts: 7 shift/reduce
7914 @end example
7915
7916 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
7917 creates a file @file{calc.output} with contents detailed below. The
7918 order of the output and the exact presentation might vary, but the
7919 interpretation is the same.
7920
7921 The first section includes details on conflicts that were solved thanks
7922 to precedence and/or associativity:
7923
7924 @example
7925 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
7926 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
7927 Conflict in state 8 between rule 2 and token '*' resolved as shift.
7928 @exdent @dots{}
7929 @end example
7930
7931 @noindent
7932 The next section lists states that still have conflicts.
7933
7934 @example
7935 State 8 conflicts: 1 shift/reduce
7936 State 9 conflicts: 1 shift/reduce
7937 State 10 conflicts: 1 shift/reduce
7938 State 11 conflicts: 4 shift/reduce
7939 @end example
7940
7941 @noindent
7942 @cindex token, useless
7943 @cindex useless token
7944 @cindex nonterminal, useless
7945 @cindex useless nonterminal
7946 @cindex rule, useless
7947 @cindex useless rule
7948 The next section reports useless tokens, nonterminal and rules. Useless
7949 nonterminals and rules are removed in order to produce a smaller parser,
7950 but useless tokens are preserved, since they might be used by the
7951 scanner (note the difference between ``useless'' and ``unused''
7952 below):
7953
7954 @example
7955 Nonterminals useless in grammar:
7956 useless
7957
7958 Terminals unused in grammar:
7959 STR
7960
7961 Rules useless in grammar:
7962 #6 useless: STR;
7963 @end example
7964
7965 @noindent
7966 The next section reproduces the exact grammar that Bison used:
7967
7968 @example
7969 Grammar
7970
7971 Number, Line, Rule
7972 0 5 $accept -> exp $end
7973 1 5 exp -> exp '+' exp
7974 2 6 exp -> exp '-' exp
7975 3 7 exp -> exp '*' exp
7976 4 8 exp -> exp '/' exp
7977 5 9 exp -> NUM
7978 @end example
7979
7980 @noindent
7981 and reports the uses of the symbols:
7982
7983 @example
7984 Terminals, with rules where they appear
7985
7986 $end (0) 0
7987 '*' (42) 3
7988 '+' (43) 1
7989 '-' (45) 2
7990 '/' (47) 4
7991 error (256)
7992 NUM (258) 5
7993
7994 Nonterminals, with rules where they appear
7995
7996 $accept (8)
7997 on left: 0
7998 exp (9)
7999 on left: 1 2 3 4 5, on right: 0 1 2 3 4
8000 @end example
8001
8002 @noindent
8003 @cindex item
8004 @cindex pointed rule
8005 @cindex rule, pointed
8006 Bison then proceeds onto the automaton itself, describing each state
8007 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
8008 item is a production rule together with a point (marked by @samp{.})
8009 that the input cursor.
8010
8011 @example
8012 state 0
8013
8014 $accept -> . exp $ (rule 0)
8015
8016 NUM shift, and go to state 1
8017
8018 exp go to state 2
8019 @end example
8020
8021 This reads as follows: ``state 0 corresponds to being at the very
8022 beginning of the parsing, in the initial rule, right before the start
8023 symbol (here, @code{exp}). When the parser returns to this state right
8024 after having reduced a rule that produced an @code{exp}, the control
8025 flow jumps to state 2. If there is no such transition on a nonterminal
8026 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
8027 the parse stack, and the control flow jumps to state 1. Any other
8028 lookahead triggers a syntax error.''
8029
8030 @cindex core, item set
8031 @cindex item set core
8032 @cindex kernel, item set
8033 @cindex item set core
8034 Even though the only active rule in state 0 seems to be rule 0, the
8035 report lists @code{NUM} as a lookahead token because @code{NUM} can be
8036 at the beginning of any rule deriving an @code{exp}. By default Bison
8037 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
8038 you want to see more detail you can invoke @command{bison} with
8039 @option{--report=itemset} to list all the items, include those that can
8040 be derived:
8041
8042 @example
8043 state 0
8044
8045 $accept -> . exp $ (rule 0)
8046 exp -> . exp '+' exp (rule 1)
8047 exp -> . exp '-' exp (rule 2)
8048 exp -> . exp '*' exp (rule 3)
8049 exp -> . exp '/' exp (rule 4)
8050 exp -> . NUM (rule 5)
8051
8052 NUM shift, and go to state 1
8053
8054 exp go to state 2
8055 @end example
8056
8057 @noindent
8058 In the state 1...
8059
8060 @example
8061 state 1
8062
8063 exp -> NUM . (rule 5)
8064
8065 $default reduce using rule 5 (exp)
8066 @end example
8067
8068 @noindent
8069 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead token
8070 (@samp{$default}), the parser will reduce it. If it was coming from
8071 state 0, then, after this reduction it will return to state 0, and will
8072 jump to state 2 (@samp{exp: go to state 2}).
8073
8074 @example
8075 state 2
8076
8077 $accept -> exp . $ (rule 0)
8078 exp -> exp . '+' exp (rule 1)
8079 exp -> exp . '-' exp (rule 2)
8080 exp -> exp . '*' exp (rule 3)
8081 exp -> exp . '/' exp (rule 4)
8082
8083 $ shift, and go to state 3
8084 '+' shift, and go to state 4
8085 '-' shift, and go to state 5
8086 '*' shift, and go to state 6
8087 '/' shift, and go to state 7
8088 @end example
8089
8090 @noindent
8091 In state 2, the automaton can only shift a symbol. For instance,
8092 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
8093 @samp{+}, it will be shifted on the parse stack, and the automaton
8094 control will jump to state 4, corresponding to the item @samp{exp -> exp
8095 '+' . exp}. Since there is no default action, any other token than
8096 those listed above will trigger a syntax error.
8097
8098 @cindex accepting state
8099 The state 3 is named the @dfn{final state}, or the @dfn{accepting
8100 state}:
8101
8102 @example
8103 state 3
8104
8105 $accept -> exp $ . (rule 0)
8106
8107 $default accept
8108 @end example
8109
8110 @noindent
8111 the initial rule is completed (the start symbol and the end
8112 of input were read), the parsing exits successfully.
8113
8114 The interpretation of states 4 to 7 is straightforward, and is left to
8115 the reader.
8116
8117 @example
8118 state 4
8119
8120 exp -> exp '+' . exp (rule 1)
8121
8122 NUM shift, and go to state 1
8123
8124 exp go to state 8
8125
8126 state 5
8127
8128 exp -> exp '-' . exp (rule 2)
8129
8130 NUM shift, and go to state 1
8131
8132 exp go to state 9
8133
8134 state 6
8135
8136 exp -> exp '*' . exp (rule 3)
8137
8138 NUM shift, and go to state 1
8139
8140 exp go to state 10
8141
8142 state 7
8143
8144 exp -> exp '/' . exp (rule 4)
8145
8146 NUM shift, and go to state 1
8147
8148 exp go to state 11
8149 @end example
8150
8151 As was announced in beginning of the report, @samp{State 8 conflicts:
8152 1 shift/reduce}:
8153
8154 @example
8155 state 8
8156
8157 exp -> exp . '+' exp (rule 1)
8158 exp -> exp '+' exp . (rule 1)
8159 exp -> exp . '-' exp (rule 2)
8160 exp -> exp . '*' exp (rule 3)
8161 exp -> exp . '/' exp (rule 4)
8162
8163 '*' shift, and go to state 6
8164 '/' shift, and go to state 7
8165
8166 '/' [reduce using rule 1 (exp)]
8167 $default reduce using rule 1 (exp)
8168 @end example
8169
8170 Indeed, there are two actions associated to the lookahead @samp{/}:
8171 either shifting (and going to state 7), or reducing rule 1. The
8172 conflict means that either the grammar is ambiguous, or the parser lacks
8173 information to make the right decision. Indeed the grammar is
8174 ambiguous, as, since we did not specify the precedence of @samp{/}, the
8175 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
8176 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
8177 NUM}, which corresponds to reducing rule 1.
8178
8179 Because in deterministic parsing a single decision can be made, Bison
8180 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
8181 Shift/Reduce Conflicts}. Discarded actions are reported in between
8182 square brackets.
8183
8184 Note that all the previous states had a single possible action: either
8185 shifting the next token and going to the corresponding state, or
8186 reducing a single rule. In the other cases, i.e., when shifting
8187 @emph{and} reducing is possible or when @emph{several} reductions are
8188 possible, the lookahead is required to select the action. State 8 is
8189 one such state: if the lookahead is @samp{*} or @samp{/} then the action
8190 is shifting, otherwise the action is reducing rule 1. In other words,
8191 the first two items, corresponding to rule 1, are not eligible when the
8192 lookahead token is @samp{*}, since we specified that @samp{*} has higher
8193 precedence than @samp{+}. More generally, some items are eligible only
8194 with some set of possible lookahead tokens. When run with
8195 @option{--report=lookahead}, Bison specifies these lookahead tokens:
8196
8197 @example
8198 state 8
8199
8200 exp -> exp . '+' exp (rule 1)
8201 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
8202 exp -> exp . '-' exp (rule 2)
8203 exp -> exp . '*' exp (rule 3)
8204 exp -> exp . '/' exp (rule 4)
8205
8206 '*' shift, and go to state 6
8207 '/' shift, and go to state 7
8208
8209 '/' [reduce using rule 1 (exp)]
8210 $default reduce using rule 1 (exp)
8211 @end example
8212
8213 The remaining states are similar:
8214
8215 @example
8216 state 9
8217
8218 exp -> exp . '+' exp (rule 1)
8219 exp -> exp . '-' exp (rule 2)
8220 exp -> exp '-' exp . (rule 2)
8221 exp -> exp . '*' exp (rule 3)
8222 exp -> exp . '/' exp (rule 4)
8223
8224 '*' shift, and go to state 6
8225 '/' shift, and go to state 7
8226
8227 '/' [reduce using rule 2 (exp)]
8228 $default reduce using rule 2 (exp)
8229
8230 state 10
8231
8232 exp -> exp . '+' exp (rule 1)
8233 exp -> exp . '-' exp (rule 2)
8234 exp -> exp . '*' exp (rule 3)
8235 exp -> exp '*' exp . (rule 3)
8236 exp -> exp . '/' exp (rule 4)
8237
8238 '/' shift, and go to state 7
8239
8240 '/' [reduce using rule 3 (exp)]
8241 $default reduce using rule 3 (exp)
8242
8243 state 11
8244
8245 exp -> exp . '+' exp (rule 1)
8246 exp -> exp . '-' exp (rule 2)
8247 exp -> exp . '*' exp (rule 3)
8248 exp -> exp . '/' exp (rule 4)
8249 exp -> exp '/' exp . (rule 4)
8250
8251 '+' shift, and go to state 4
8252 '-' shift, and go to state 5
8253 '*' shift, and go to state 6
8254 '/' shift, and go to state 7
8255
8256 '+' [reduce using rule 4 (exp)]
8257 '-' [reduce using rule 4 (exp)]
8258 '*' [reduce using rule 4 (exp)]
8259 '/' [reduce using rule 4 (exp)]
8260 $default reduce using rule 4 (exp)
8261 @end example
8262
8263 @noindent
8264 Observe that state 11 contains conflicts not only due to the lack of
8265 precedence of @samp{/} with respect to @samp{+}, @samp{-}, and
8266 @samp{*}, but also because the
8267 associativity of @samp{/} is not specified.
8268
8269
8270 @node Tracing
8271 @section Tracing Your Parser
8272 @findex yydebug
8273 @cindex debugging
8274 @cindex tracing the parser
8275
8276 If a Bison grammar compiles properly but doesn't do what you want when it
8277 runs, the @code{yydebug} parser-trace feature can help you figure out why.
8278
8279 There are several means to enable compilation of trace facilities:
8280
8281 @table @asis
8282 @item the macro @code{YYDEBUG}
8283 @findex YYDEBUG
8284 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
8285 parser. This is compliant with POSIX Yacc. You could use
8286 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
8287 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
8288 Prologue}).
8289
8290 @item the option @option{-t}, @option{--debug}
8291 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
8292 ,Invoking Bison}). This is POSIX compliant too.
8293
8294 @item the directive @samp{%debug}
8295 @findex %debug
8296 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison Declaration
8297 Summary}). This Bison extension is maintained for backward
8298 compatibility with previous versions of Bison.
8299
8300 @item the variable @samp{parse.trace}
8301 @findex %define parse.trace
8302 Add the @samp{%define parse.trace} directive (@pxref{Decl Summary,
8303 ,Bison Declaration Summary}), or pass the @option{-Dparse.trace} option
8304 (@pxref{Bison Options}). This is a Bison extension, which is especially
8305 useful for languages that don't use a preprocessor. Unless
8306 POSIX and Yacc portability matter to you, this is the
8307 preferred solution.
8308 @end table
8309
8310 We suggest that you always enable the trace option so that debugging is
8311 always possible.
8312
8313 The trace facility outputs messages with macro calls of the form
8314 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
8315 @var{format} and @var{args} are the usual @code{printf} format and variadic
8316 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
8317 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
8318 and @code{YYFPRINTF} is defined to @code{fprintf}.
8319
8320 Once you have compiled the program with trace facilities, the way to
8321 request a trace is to store a nonzero value in the variable @code{yydebug}.
8322 You can do this by making the C code do it (in @code{main}, perhaps), or
8323 you can alter the value with a C debugger.
8324
8325 Each step taken by the parser when @code{yydebug} is nonzero produces a
8326 line or two of trace information, written on @code{stderr}. The trace
8327 messages tell you these things:
8328
8329 @itemize @bullet
8330 @item
8331 Each time the parser calls @code{yylex}, what kind of token was read.
8332
8333 @item
8334 Each time a token is shifted, the depth and complete contents of the
8335 state stack (@pxref{Parser States}).
8336
8337 @item
8338 Each time a rule is reduced, which rule it is, and the complete contents
8339 of the state stack afterward.
8340 @end itemize
8341
8342 To make sense of this information, it helps to refer to the listing file
8343 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
8344 Bison}). This file shows the meaning of each state in terms of
8345 positions in various rules, and also what each state will do with each
8346 possible input token. As you read the successive trace messages, you
8347 can see that the parser is functioning according to its specification in
8348 the listing file. Eventually you will arrive at the place where
8349 something undesirable happens, and you will see which parts of the
8350 grammar are to blame.
8351
8352 The parser implementation file is a C program and you can use C
8353 debuggers on it, but it's not easy to interpret what it is doing. The
8354 parser function is a finite-state machine interpreter, and aside from
8355 the actions it executes the same code over and over. Only the values
8356 of variables show where in the grammar it is working.
8357
8358 @findex YYPRINT
8359 The debugging information normally gives the token type of each token
8360 read, but not its semantic value. You can optionally define a macro
8361 named @code{YYPRINT} to provide a way to print the value. If you define
8362 @code{YYPRINT}, it should take three arguments. The parser will pass a
8363 standard I/O stream, the numeric code for the token type, and the token
8364 value (from @code{yylval}).
8365
8366 Here is an example of @code{YYPRINT} suitable for the multi-function
8367 calculator (@pxref{Mfcalc Declarations, ,Declarations for @code{mfcalc}}):
8368
8369 @smallexample
8370 %@{
8371 static void print_token_value (FILE *, int, YYSTYPE);
8372 #define YYPRINT(file, type, value) print_token_value (file, type, value)
8373 %@}
8374
8375 @dots{} %% @dots{} %% @dots{}
8376
8377 static void
8378 print_token_value (FILE *file, int type, YYSTYPE value)
8379 @{
8380 if (type == VAR)
8381 fprintf (file, "%s", value.tptr->name);
8382 else if (type == NUM)
8383 fprintf (file, "%d", value.val);
8384 @}
8385 @end smallexample
8386
8387 @c ================================================= Invoking Bison
8388
8389 @node Invocation
8390 @chapter Invoking Bison
8391 @cindex invoking Bison
8392 @cindex Bison invocation
8393 @cindex options for invoking Bison
8394
8395 The usual way to invoke Bison is as follows:
8396
8397 @example
8398 bison @var{infile}
8399 @end example
8400
8401 Here @var{infile} is the grammar file name, which usually ends in
8402 @samp{.y}. The parser implementation file's name is made by replacing
8403 the @samp{.y} with @samp{.tab.c} and removing any leading directory.
8404 Thus, the @samp{bison foo.y} file name yields @file{foo.tab.c}, and
8405 the @samp{bison hack/foo.y} file name yields @file{foo.tab.c}. It's
8406 also possible, in case you are writing C++ code instead of C in your
8407 grammar file, to name it @file{foo.ypp} or @file{foo.y++}. Then, the
8408 output files will take an extension like the given one as input
8409 (respectively @file{foo.tab.cpp} and @file{foo.tab.c++}). This
8410 feature takes effect with all options that manipulate file names like
8411 @samp{-o} or @samp{-d}.
8412
8413 For example :
8414
8415 @example
8416 bison -d @var{infile.yxx}
8417 @end example
8418 @noindent
8419 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
8420
8421 @example
8422 bison -d -o @var{output.c++} @var{infile.y}
8423 @end example
8424 @noindent
8425 will produce @file{output.c++} and @file{outfile.h++}.
8426
8427 For compatibility with POSIX, the standard Bison
8428 distribution also contains a shell script called @command{yacc} that
8429 invokes Bison with the @option{-y} option.
8430
8431 @menu
8432 * Bison Options:: All the options described in detail,
8433 in alphabetical order by short options.
8434 * Option Cross Key:: Alphabetical list of long options.
8435 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
8436 @end menu
8437
8438 @node Bison Options
8439 @section Bison Options
8440
8441 Bison supports both traditional single-letter options and mnemonic long
8442 option names. Long option names are indicated with @samp{--} instead of
8443 @samp{-}. Abbreviations for option names are allowed as long as they
8444 are unique. When a long option takes an argument, like
8445 @samp{--file-prefix}, connect the option name and the argument with
8446 @samp{=}.
8447
8448 Here is a list of options that can be used with Bison, alphabetized by
8449 short option. It is followed by a cross key alphabetized by long
8450 option.
8451
8452 @c Please, keep this ordered as in `bison --help'.
8453 @noindent
8454 Operations modes:
8455 @table @option
8456 @item -h
8457 @itemx --help
8458 Print a summary of the command-line options to Bison and exit.
8459
8460 @item -V
8461 @itemx --version
8462 Print the version number of Bison and exit.
8463
8464 @item --print-localedir
8465 Print the name of the directory containing locale-dependent data.
8466
8467 @item --print-datadir
8468 Print the name of the directory containing skeletons and XSLT.
8469
8470 @item -y
8471 @itemx --yacc
8472 Act more like the traditional Yacc command. This can cause different
8473 diagnostics to be generated, and may change behavior in other minor
8474 ways. Most importantly, imitate Yacc's output file name conventions,
8475 so that the parser implementation file is called @file{y.tab.c}, and
8476 the other outputs are called @file{y.output} and @file{y.tab.h}.
8477 Also, if generating a deterministic parser in C, generate
8478 @code{#define} statements in addition to an @code{enum} to associate
8479 token numbers with token names. Thus, the following shell script can
8480 substitute for Yacc, and the Bison distribution contains such a script
8481 for compatibility with POSIX:
8482
8483 @example
8484 #! /bin/sh
8485 bison -y "$@@"
8486 @end example
8487
8488 The @option{-y}/@option{--yacc} option is intended for use with
8489 traditional Yacc grammars. If your grammar uses a Bison extension
8490 like @samp{%glr-parser}, Bison might not be Yacc-compatible even if
8491 this option is specified.
8492
8493 @item -W [@var{category}]
8494 @itemx --warnings[=@var{category}]
8495 Output warnings falling in @var{category}. @var{category} can be one
8496 of:
8497 @table @code
8498 @item midrule-values
8499 Warn about mid-rule values that are set but not used within any of the actions
8500 of the parent rule.
8501 For example, warn about unused @code{$2} in:
8502
8503 @example
8504 exp: '1' @{ $$ = 1; @} '+' exp @{ $$ = $1 + $4; @};
8505 @end example
8506
8507 Also warn about mid-rule values that are used but not set.
8508 For example, warn about unset @code{$$} in the mid-rule action in:
8509
8510 @example
8511 exp: '1' @{ $1 = 1; @} '+' exp @{ $$ = $2 + $4; @};
8512 @end example
8513
8514 These warnings are not enabled by default since they sometimes prove to
8515 be false alarms in existing grammars employing the Yacc constructs
8516 @code{$0} or @code{$-@var{n}} (where @var{n} is some positive integer).
8517
8518
8519 @item yacc
8520 Incompatibilities with POSIX Yacc.
8521
8522 @item all
8523 All the warnings.
8524 @item none
8525 Turn off all the warnings.
8526 @item error
8527 Treat warnings as errors.
8528 @end table
8529
8530 A category can be turned off by prefixing its name with @samp{no-}. For
8531 instance, @option{-Wno-yacc} will hide the warnings about
8532 POSIX Yacc incompatibilities.
8533 @end table
8534
8535 @noindent
8536 Tuning the parser:
8537
8538 @table @option
8539 @item -t
8540 @itemx --debug
8541 In the parser implementation file, define the macro @code{YYDEBUG} to
8542 1 if it is not already defined, so that the debugging facilities are
8543 compiled. @xref{Tracing, ,Tracing Your Parser}.
8544
8545 @item -D @var{name}[=@var{value}]
8546 @itemx --define=@var{name}[=@var{value}]
8547 @itemx -F @var{name}[=@var{value}]
8548 @itemx --force-define=@var{name}[=@var{value}]
8549 Each of these is equivalent to @samp{%define @var{name} "@var{value}"}
8550 (@pxref{Decl Summary, ,%define}) except that Bison processes multiple
8551 definitions for the same @var{name} as follows:
8552
8553 @itemize
8554 @item
8555 Bison quietly ignores all command-line definitions for @var{name} except
8556 the last.
8557 @item
8558 If that command-line definition is specified by a @code{-D} or
8559 @code{--define}, Bison reports an error for any @code{%define}
8560 definition for @var{name}.
8561 @item
8562 If that command-line definition is specified by a @code{-F} or
8563 @code{--force-define} instead, Bison quietly ignores all @code{%define}
8564 definitions for @var{name}.
8565 @item
8566 Otherwise, Bison reports an error if there are multiple @code{%define}
8567 definitions for @var{name}.
8568 @end itemize
8569
8570 You should avoid using @code{-F} and @code{--force-define} in your
8571 make files unless you are confident that it is safe to quietly ignore
8572 any conflicting @code{%define} that may be added to the grammar file.
8573
8574 @item -L @var{language}
8575 @itemx --language=@var{language}
8576 Specify the programming language for the generated parser, as if
8577 @code{%language} was specified (@pxref{Decl Summary, , Bison Declaration
8578 Summary}). Currently supported languages include C, C++, and Java.
8579 @var{language} is case-insensitive.
8580
8581 This option is experimental and its effect may be modified in future
8582 releases.
8583
8584 @item --locations
8585 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
8586
8587 @item -p @var{prefix}
8588 @itemx --name-prefix=@var{prefix}
8589 Pretend that @code{%name-prefix "@var{prefix}"} was specified.
8590 @xref{Decl Summary}.
8591
8592 @item -l
8593 @itemx --no-lines
8594 Don't put any @code{#line} preprocessor commands in the parser
8595 implementation file. Ordinarily Bison puts them in the parser
8596 implementation file so that the C compiler and debuggers will
8597 associate errors with your source file, the grammar file. This option
8598 causes them to associate errors with the parser implementation file,
8599 treating it as an independent source file in its own right.
8600
8601 @item -S @var{file}
8602 @itemx --skeleton=@var{file}
8603 Specify the skeleton to use, similar to @code{%skeleton}
8604 (@pxref{Decl Summary, , Bison Declaration Summary}).
8605
8606 @c You probably don't need this option unless you are developing Bison.
8607 @c You should use @option{--language} if you want to specify the skeleton for a
8608 @c different language, because it is clearer and because it will always
8609 @c choose the correct skeleton for non-deterministic or push parsers.
8610
8611 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
8612 file in the Bison installation directory.
8613 If it does, @var{file} is an absolute file name or a file name relative to the
8614 current working directory.
8615 This is similar to how most shells resolve commands.
8616
8617 @item -k
8618 @itemx --token-table
8619 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
8620 @end table
8621
8622 @noindent
8623 Adjust the output:
8624
8625 @table @option
8626 @item --defines[=@var{file}]
8627 Pretend that @code{%defines} was specified, i.e., write an extra output
8628 file containing macro definitions for the token type names defined in
8629 the grammar, as well as a few other declarations. @xref{Decl Summary}.
8630
8631 @item -d
8632 This is the same as @code{--defines} except @code{-d} does not accept a
8633 @var{file} argument since POSIX Yacc requires that @code{-d} can be bundled
8634 with other short options.
8635
8636 @item -b @var{file-prefix}
8637 @itemx --file-prefix=@var{prefix}
8638 Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
8639 for all Bison output file names. @xref{Decl Summary}.
8640
8641 @item -r @var{things}
8642 @itemx --report=@var{things}
8643 Write an extra output file containing verbose description of the comma
8644 separated list of @var{things} among:
8645
8646 @table @code
8647 @item state
8648 Description of the grammar, conflicts (resolved and unresolved), and
8649 parser's automaton.
8650
8651 @item lookahead
8652 Implies @code{state} and augments the description of the automaton with
8653 each rule's lookahead set.
8654
8655 @item itemset
8656 Implies @code{state} and augments the description of the automaton with
8657 the full set of items for each state, instead of its core only.
8658 @end table
8659
8660 @item --report-file=@var{file}
8661 Specify the @var{file} for the verbose description.
8662
8663 @item -v
8664 @itemx --verbose
8665 Pretend that @code{%verbose} was specified, i.e., write an extra output
8666 file containing verbose descriptions of the grammar and
8667 parser. @xref{Decl Summary}.
8668
8669 @item -o @var{file}
8670 @itemx --output=@var{file}
8671 Specify the @var{file} for the parser implementation file.
8672
8673 The other output files' names are constructed from @var{file} as
8674 described under the @samp{-v} and @samp{-d} options.
8675
8676 @item -g [@var{file}]
8677 @itemx --graph[=@var{file}]
8678 Output a graphical representation of the parser's
8679 automaton computed by Bison, in @uref{http://www.graphviz.org/, Graphviz}
8680 @uref{http://www.graphviz.org/doc/info/lang.html, DOT} format.
8681 @code{@var{file}} is optional.
8682 If omitted and the grammar file is @file{foo.y}, the output file will be
8683 @file{foo.dot}.
8684
8685 @item -x [@var{file}]
8686 @itemx --xml[=@var{file}]
8687 Output an XML report of the parser's automaton computed by Bison.
8688 @code{@var{file}} is optional.
8689 If omitted and the grammar file is @file{foo.y}, the output file will be
8690 @file{foo.xml}.
8691 (The current XML schema is experimental and may evolve.
8692 More user feedback will help to stabilize it.)
8693 @end table
8694
8695 @node Option Cross Key
8696 @section Option Cross Key
8697
8698 Here is a list of options, alphabetized by long option, to help you find
8699 the corresponding short option and directive.
8700
8701 @multitable {@option{--force-define=@var{name}[=@var{value}]}} {@option{-F @var{name}[=@var{value}]}} {@code{%nondeterministic-parser}}
8702 @headitem Long Option @tab Short Option @tab Bison Directive
8703 @include cross-options.texi
8704 @end multitable
8705
8706 @node Yacc Library
8707 @section Yacc Library
8708
8709 The Yacc library contains default implementations of the
8710 @code{yyerror} and @code{main} functions. These default
8711 implementations are normally not useful, but POSIX requires
8712 them. To use the Yacc library, link your program with the
8713 @option{-ly} option. Note that Bison's implementation of the Yacc
8714 library is distributed under the terms of the GNU General
8715 Public License (@pxref{Copying}).
8716
8717 If you use the Yacc library's @code{yyerror} function, you should
8718 declare @code{yyerror} as follows:
8719
8720 @example
8721 int yyerror (char const *);
8722 @end example
8723
8724 Bison ignores the @code{int} value returned by this @code{yyerror}.
8725 If you use the Yacc library's @code{main} function, your
8726 @code{yyparse} function should have the following type signature:
8727
8728 @example
8729 int yyparse (void);
8730 @end example
8731
8732 @c ================================================= C++ Bison
8733
8734 @node Other Languages
8735 @chapter Parsers Written In Other Languages
8736
8737 @menu
8738 * C++ Parsers:: The interface to generate C++ parser classes
8739 * Java Parsers:: The interface to generate Java parser classes
8740 @end menu
8741
8742 @node C++ Parsers
8743 @section C++ Parsers
8744
8745 @menu
8746 * C++ Bison Interface:: Asking for C++ parser generation
8747 * C++ Semantic Values:: %union vs. C++
8748 * C++ Location Values:: The position and location classes
8749 * C++ Parser Interface:: Instantiating and running the parser
8750 * C++ Scanner Interface:: Exchanges between yylex and parse
8751 * A Complete C++ Example:: Demonstrating their use
8752 @end menu
8753
8754 @node C++ Bison Interface
8755 @subsection C++ Bison Interface
8756 @c - %skeleton "lalr1.cc"
8757 @c - Always pure
8758 @c - initial action
8759
8760 The C++ deterministic parser is selected using the skeleton directive,
8761 @samp{%skeleton "lalr1.cc"}, or the synonymous command-line option
8762 @option{--skeleton=lalr1.cc}.
8763 @xref{Decl Summary}.
8764
8765 When run, @command{bison} will create several entities in the @samp{yy}
8766 namespace.
8767 @findex %define api.namespace
8768 Use the @samp{%define api.namespace} directive to change the namespace
8769 name, see
8770 @ref{Decl Summary}.
8771 The various classes are generated in the following files:
8772
8773 @table @file
8774 @item position.hh
8775 @itemx location.hh
8776 The definition of the classes @code{position} and @code{location},
8777 used for location tracking when enabled. @xref{C++ Location Values}.
8778
8779 @item stack.hh
8780 An auxiliary class @code{stack} used by the parser.
8781
8782 @item @var{file}.hh
8783 @itemx @var{file}.cc
8784 (Assuming the extension of the grammar file was @samp{.yy}.) The
8785 declaration and implementation of the C++ parser class. The basename
8786 and extension of these two files follow the same rules as with regular C
8787 parsers (@pxref{Invocation}).
8788
8789 The header is @emph{mandatory}; you must either pass
8790 @option{-d}/@option{--defines} to @command{bison}, or use the
8791 @samp{%defines} directive.
8792 @end table
8793
8794 All these files are documented using Doxygen; run @command{doxygen}
8795 for a complete and accurate documentation.
8796
8797 @node C++ Semantic Values
8798 @subsection C++ Semantic Values
8799 @c - No objects in unions
8800 @c - YYSTYPE
8801 @c - Printer and destructor
8802
8803 Bison supports two different means to handle semantic values in C++. One is
8804 alike the C interface, and relies on unions (@pxref{C++ Unions}). As C++
8805 practitioners know, unions are inconvenient in C++, therefore another
8806 approach is provided, based on variants (@pxref{C++ Variants}).
8807
8808 @menu
8809 * C++ Unions:: Semantic values cannot be objects
8810 * C++ Variants:: Using objects as semantic values
8811 @end menu
8812
8813 @node C++ Unions
8814 @subsubsection C++ Unions
8815
8816 The @code{%union} directive works as for C, see @ref{Union Decl, ,The
8817 Collection of Value Types}. In particular it produces a genuine
8818 @code{union}, which have a few specific features in C++.
8819 @itemize @minus
8820 @item
8821 The type @code{YYSTYPE} is defined but its use is discouraged: rather
8822 you should refer to the parser's encapsulated type
8823 @code{yy::parser::semantic_type}.
8824 @item
8825 Non POD (Plain Old Data) types cannot be used. C++ forbids any
8826 instance of classes with constructors in unions: only @emph{pointers}
8827 to such objects are allowed.
8828 @end itemize
8829
8830 Because objects have to be stored via pointers, memory is not
8831 reclaimed automatically: using the @code{%destructor} directive is the
8832 only means to avoid leaks. @xref{Destructor Decl, , Freeing Discarded
8833 Symbols}.
8834
8835 @node C++ Variants
8836 @subsubsection C++ Variants
8837
8838 Starting with version 2.6, Bison provides a @emph{variant} based
8839 implementation of semantic values for C++. This alleviates all the
8840 limitations reported in the previous section, and in particular, object
8841 types can be used without pointers.
8842
8843 To enable variant-based semantic values, set @code{%define} variable
8844 @code{variant} (@pxref{Decl Summary, , variant}). Once this defined,
8845 @code{%union} is ignored, and instead of using the name of the fields of the
8846 @code{%union} to ``type'' the symbols, use genuine types.
8847
8848 For instance, instead of
8849
8850 @example
8851 %union
8852 @{
8853 int ival;
8854 std::string* sval;
8855 @}
8856 %token <ival> NUMBER;
8857 %token <sval> STRING;
8858 @end example
8859
8860 @noindent
8861 write
8862
8863 @example
8864 %token <int> NUMBER;
8865 %token <std::string> STRING;
8866 @end example
8867
8868 @code{STRING} is no longer a pointer, which should fairly simplify the user
8869 actions in the grammar and in the scanner (in particular the memory
8870 management).
8871
8872 Since C++ features destructors, and since it is customary to specialize
8873 @code{operator<<} to support uniform printing of values, variants also
8874 typically simplify Bison printers and destructors.
8875
8876 Variants are stricter than unions. When based on unions, you may play any
8877 dirty game with @code{yylval}, say storing an @code{int}, reading a
8878 @code{char*}, and then storing a @code{double} in it. This is no longer
8879 possible with variants: they must be initialized, then assigned to, and
8880 eventually, destroyed.
8881
8882 @deftypemethod {semantic_type} {T&} build<T> ()
8883 Initialize, but leave empty. Returns the address where the actual value may
8884 be stored. Requires that the variant was not initialized yet.
8885 @end deftypemethod
8886
8887 @deftypemethod {semantic_type} {T&} build<T> (const T& @var{t})
8888 Initialize, and copy-construct from @var{t}.
8889 @end deftypemethod
8890
8891
8892 @strong{Warning}: We do not use Boost.Variant, for two reasons. First, it
8893 appeared unacceptable to require Boost on the user's machine (i.e., the
8894 machine on which the generated parser will be compiled, not the machine on
8895 which @command{bison} was run). Second, for each possible semantic value,
8896 Boost.Variant not only stores the value, but also a tag specifying its
8897 type. But the parser already ``knows'' the type of the semantic value, so
8898 that would be duplicating the information.
8899
8900 Therefore we developed light-weight variants whose type tag is external (so
8901 they are really like @code{unions} for C++ actually). But our code is much
8902 less mature that Boost.Variant. So there is a number of limitations in
8903 (the current implementation of) variants:
8904 @itemize
8905 @item
8906 Alignment must be enforced: values should be aligned in memory according to
8907 the most demanding type. Computing the smallest alignment possible requires
8908 meta-programming techniques that are not currently implemented in Bison, and
8909 therefore, since, as far as we know, @code{double} is the most demanding
8910 type on all platforms, alignments are enforced for @code{double} whatever
8911 types are actually used. This may waste space in some cases.
8912
8913 @item
8914 Our implementation is not conforming with strict aliasing rules. Alias
8915 analysis is a technique used in optimizing compilers to detect when two
8916 pointers are disjoint (they cannot ``meet''). Our implementation breaks
8917 some of the rules that G++ 4.4 uses in its alias analysis, so @emph{strict
8918 alias analysis must be disabled}. Use the option
8919 @option{-fno-strict-aliasing} to compile the generated parser.
8920
8921 @item
8922 There might be portability issues we are not aware of.
8923 @end itemize
8924
8925 As far as we know, these limitations @emph{can} be alleviated. All it takes
8926 is some time and/or some talented C++ hacker willing to contribute to Bison.
8927
8928 @node C++ Location Values
8929 @subsection C++ Location Values
8930 @c - %locations
8931 @c - class Position
8932 @c - class Location
8933 @c - %define filename_type "const symbol::Symbol"
8934
8935 When the directive @code{%locations} is used, the C++ parser supports
8936 location tracking, see @ref{Locations, , Locations Overview}. Two
8937 auxiliary classes define a @code{position}, a single point in a file,
8938 and a @code{location}, a range composed of a pair of
8939 @code{position}s (possibly spanning several files).
8940
8941 @deftypemethod {position} {std::string*} file
8942 The name of the file. It will always be handled as a pointer, the
8943 parser will never duplicate nor deallocate it. As an experimental
8944 feature you may change it to @samp{@var{type}*} using @samp{%define
8945 filename_type "@var{type}"}.
8946 @end deftypemethod
8947
8948 @deftypemethod {position} {unsigned int} line
8949 The line, starting at 1.
8950 @end deftypemethod
8951
8952 @deftypemethod {position} {unsigned int} lines (int @var{height} = 1)
8953 Advance by @var{height} lines, resetting the column number.
8954 @end deftypemethod
8955
8956 @deftypemethod {position} {unsigned int} column
8957 The column, starting at 0.
8958 @end deftypemethod
8959
8960 @deftypemethod {position} {unsigned int} columns (int @var{width} = 1)
8961 Advance by @var{width} columns, without changing the line number.
8962 @end deftypemethod
8963
8964 @deftypemethod {position} {position&} operator+= (position& @var{pos}, int @var{width})
8965 @deftypemethodx {position} {position} operator+ (const position& @var{pos}, int @var{width})
8966 @deftypemethodx {position} {position&} operator-= (const position& @var{pos}, int @var{width})
8967 @deftypemethodx {position} {position} operator- (position& @var{pos}, int @var{width})
8968 Various forms of syntactic sugar for @code{columns}.
8969 @end deftypemethod
8970
8971 @deftypemethod {position} {position} operator<< (std::ostream @var{o}, const position& @var{p})
8972 Report @var{p} on @var{o} like this:
8973 @samp{@var{file}:@var{line}.@var{column}}, or
8974 @samp{@var{line}.@var{column}} if @var{file} is null.
8975 @end deftypemethod
8976
8977 @deftypemethod {location} {position} begin
8978 @deftypemethodx {location} {position} end
8979 The first, inclusive, position of the range, and the first beyond.
8980 @end deftypemethod
8981
8982 @deftypemethod {location} {unsigned int} columns (int @var{width} = 1)
8983 @deftypemethodx {location} {unsigned int} lines (int @var{height} = 1)
8984 Advance the @code{end} position.
8985 @end deftypemethod
8986
8987 @deftypemethod {location} {location} operator+ (const location& @var{begin}, const location& @var{end})
8988 @deftypemethodx {location} {location} operator+ (const location& @var{begin}, int @var{width})
8989 @deftypemethodx {location} {location} operator+= (const location& @var{loc}, int @var{width})
8990 Various forms of syntactic sugar.
8991 @end deftypemethod
8992
8993 @deftypemethod {location} {void} step ()
8994 Move @code{begin} onto @code{end}.
8995 @end deftypemethod
8996
8997
8998 @node C++ Parser Interface
8999 @subsection C++ Parser Interface
9000 @c - define parser_class_name
9001 @c - Ctor
9002 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
9003 @c debug_stream.
9004 @c - Reporting errors
9005
9006 The output files @file{@var{output}.hh} and @file{@var{output}.cc}
9007 declare and define the parser class in the namespace @code{yy}. The
9008 class name defaults to @code{parser}, but may be changed using
9009 @samp{%define parser_class_name "@var{name}"}. The interface of
9010 this class is detailed below. It can be extended using the
9011 @code{%parse-param} feature: its semantics is slightly changed since
9012 it describes an additional member of the parser class, and an
9013 additional argument for its constructor.
9014
9015 @defcv {Type} {parser} {semantic_type}
9016 @defcvx {Type} {parser} {location_type}
9017 The types for semantic values and locations (if enabled).
9018 @end defcv
9019
9020 @defcv {Type} {parser} {token}
9021 A structure that contains (only) the definition of the tokens as the
9022 @code{yytokentype} enumeration. To refer to the token @code{FOO}, the
9023 scanner should use @code{yy::parser::token::FOO}. The scanner can use
9024 @samp{typedef yy::parser::token token;} to ``import'' the token enumeration
9025 (@pxref{Calc++ Scanner}).
9026 @end defcv
9027
9028 @defcv {Type} {parser} {syntax_error}
9029 This class derives from @code{std::runtime_error}. Throw instances of it
9030 from user actions to raise parse errors. This is equivalent with first
9031 invoking @code{error} to report the location and message of the syntax
9032 error, and then to invoke @code{YYERROR} to enter the error-recovery mode.
9033 But contrary to @code{YYERROR} which can only be invoked from user actions
9034 (i.e., written in the action itself), the exception can be thrown from
9035 function invoked from the user action.
9036 @end defcv
9037
9038 @deftypemethod {parser} {} parser (@var{type1} @var{arg1}, ...)
9039 Build a new parser object. There are no arguments by default, unless
9040 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
9041 @end deftypemethod
9042
9043 @deftypemethod {syntax_error} {} syntax_error (const location_type& @var{l}, const std::string& @var{m})
9044 @deftypemethodx {syntax_error} {} syntax_error (const std::string& @var{m})
9045 Instantiate a syntax-error exception.
9046 @end deftypemethod
9047
9048 @deftypemethod {parser} {int} parse ()
9049 Run the syntactic analysis, and return 0 on success, 1 otherwise.
9050 @end deftypemethod
9051
9052 @deftypemethod {parser} {std::ostream&} debug_stream ()
9053 @deftypemethodx {parser} {void} set_debug_stream (std::ostream& @var{o})
9054 Get or set the stream used for tracing the parsing. It defaults to
9055 @code{std::cerr}.
9056 @end deftypemethod
9057
9058 @deftypemethod {parser} {debug_level_type} debug_level ()
9059 @deftypemethodx {parser} {void} set_debug_level (debug_level @var{l})
9060 Get or set the tracing level. Currently its value is either 0, no trace,
9061 or nonzero, full tracing.
9062 @end deftypemethod
9063
9064 @deftypemethod {parser} {void} error (const location_type& @var{l}, const std::string& @var{m})
9065 @deftypemethodx {parser} {void} error (const std::string& @var{m})
9066 The definition for this member function must be supplied by the user:
9067 the parser uses it to report a parser error occurring at @var{l},
9068 described by @var{m}. If location tracking is not enabled, the second
9069 signature is used.
9070 @end deftypemethod
9071
9072
9073 @node C++ Scanner Interface
9074 @subsection C++ Scanner Interface
9075 @c - prefix for yylex.
9076 @c - Pure interface to yylex
9077 @c - %lex-param
9078
9079 The parser invokes the scanner by calling @code{yylex}. Contrary to C
9080 parsers, C++ parsers are always pure: there is no point in using the
9081 @samp{%define api.pure} directive. The actual interface with @code{yylex}
9082 depends whether you use unions, or variants.
9083
9084 @menu
9085 * Split Symbols:: Passing symbols as two/three components
9086 * Complete Symbols:: Making symbols a whole
9087 @end menu
9088
9089 @node Split Symbols
9090 @subsubsection Split Symbols
9091
9092 Therefore the interface is as follows.
9093
9094 @deftypemethod {parser} {int} yylex (semantic_type* @var{yylval}, location_type* @var{yylloc}, @var{type1} @var{arg1}, ...)
9095 @deftypemethodx {parser} {int} yylex (semantic_type* @var{yylval}, @var{type1} @var{arg1}, ...)
9096 Return the next token. Its type is the return value, its semantic value and
9097 location (if enabled) being @var{yylval} and @var{yylloc}. Invocations of
9098 @samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
9099 @end deftypemethod
9100
9101 Note that when using variants, the interface for @code{yylex} is the same,
9102 but @code{yylval} is handled differently.
9103
9104 Regular union-based code in Lex scanner typically look like:
9105
9106 @example
9107 [0-9]+ @{
9108 yylval.ival = text_to_int (yytext);
9109 return yy::parser::INTEGER;
9110 @}
9111 [a-z]+ @{
9112 yylval.sval = new std::string (yytext);
9113 return yy::parser::IDENTIFIER;
9114 @}
9115 @end example
9116
9117 Using variants, @code{yylval} is already constructed, but it is not
9118 initialized. So the code would look like:
9119
9120 @example
9121 [0-9]+ @{
9122 yylval.build<int>() = text_to_int (yytext);
9123 return yy::parser::INTEGER;
9124 @}
9125 [a-z]+ @{
9126 yylval.build<std::string> = yytext;
9127 return yy::parser::IDENTIFIER;
9128 @}
9129 @end example
9130
9131 @noindent
9132 or
9133
9134 @example
9135 [0-9]+ @{
9136 yylval.build(text_to_int (yytext));
9137 return yy::parser::INTEGER;
9138 @}
9139 [a-z]+ @{
9140 yylval.build(yytext);
9141 return yy::parser::IDENTIFIER;
9142 @}
9143 @end example
9144
9145
9146 @node Complete Symbols
9147 @subsubsection Complete Symbols
9148
9149 If you specified both @code{%define variant} and @code{%define lex_symbol},
9150 the @code{parser} class also defines the class @code{parser::symbol_type}
9151 which defines a @emph{complete} symbol, aggregating its type (i.e., the
9152 traditional value returned by @code{yylex}), its semantic value (i.e., the
9153 value passed in @code{yylval}, and possibly its location (@code{yylloc}).
9154
9155 @deftypemethod {symbol_type} {} symbol_type (token_type @var{type}, const semantic_type& @var{value}, const location_type& @var{location})
9156 Build a complete terminal symbol which token type is @var{type}, and which
9157 semantic value is @var{value}. If location tracking is enabled, also pass
9158 the @var{location}.
9159 @end deftypemethod
9160
9161 This interface is low-level and should not be used for two reasons. First,
9162 it is inconvenient, as you still have to build the semantic value, which is
9163 a variant, and second, because consistency is not enforced: as with unions,
9164 it is still possible to give an integer as semantic value for a string.
9165
9166 So for each token type, Bison generates named constructors as follows.
9167
9168 @deftypemethod {symbol_type} {} make_@var{token} (const @var{value_type}& @var{value}, const location_type& @var{location})
9169 @deftypemethodx {symbol_type} {} make_@var{token} (const location_type& @var{location})
9170 Build a complete terminal symbol for the token type @var{token} (not
9171 including the @code{api.tokens.prefix}) whose possible semantic value is
9172 @var{value} of adequate @var{value_type}. If location tracking is enabled,
9173 also pass the @var{location}.
9174 @end deftypemethod
9175
9176 For instance, given the following declarations:
9177
9178 @example
9179 %define api.tokens.prefix "TOK_"
9180 %token <std::string> IDENTIFIER;
9181 %token <int> INTEGER;
9182 %token COLON;
9183 @end example
9184
9185 @noindent
9186 Bison generates the following functions:
9187
9188 @example
9189 symbol_type make_IDENTIFIER(const std::string& v,
9190 const location_type& l);
9191 symbol_type make_INTEGER(const int& v,
9192 const location_type& loc);
9193 symbol_type make_COLON(const location_type& loc);
9194 @end example
9195
9196 @noindent
9197 which should be used in a Lex-scanner as follows.
9198
9199 @example
9200 [0-9]+ return yy::parser::make_INTEGER(text_to_int (yytext), loc);
9201 [a-z]+ return yy::parser::make_IDENTIFIER(yytext, loc);
9202 ":" return yy::parser::make_COLON(loc);
9203 @end example
9204
9205 Tokens that do not have an identifier are not accessible: you cannot simply
9206 use characters such as @code{':'}, they must be declared with @code{%token}.
9207
9208 @node A Complete C++ Example
9209 @subsection A Complete C++ Example
9210
9211 This section demonstrates the use of a C++ parser with a simple but
9212 complete example. This example should be available on your system,
9213 ready to compile, in the directory @dfn{.../bison/examples/calc++}. It
9214 focuses on the use of Bison, therefore the design of the various C++
9215 classes is very naive: no accessors, no encapsulation of members etc.
9216 We will use a Lex scanner, and more precisely, a Flex scanner, to
9217 demonstrate the various interactions. A hand-written scanner is
9218 actually easier to interface with.
9219
9220 @menu
9221 * Calc++ --- C++ Calculator:: The specifications
9222 * Calc++ Parsing Driver:: An active parsing context
9223 * Calc++ Parser:: A parser class
9224 * Calc++ Scanner:: A pure C++ Flex scanner
9225 * Calc++ Top Level:: Conducting the band
9226 @end menu
9227
9228 @node Calc++ --- C++ Calculator
9229 @subsubsection Calc++ --- C++ Calculator
9230
9231 Of course the grammar is dedicated to arithmetics, a single
9232 expression, possibly preceded by variable assignments. An
9233 environment containing possibly predefined variables such as
9234 @code{one} and @code{two}, is exchanged with the parser. An example
9235 of valid input follows.
9236
9237 @example
9238 three := 3
9239 seven := one + two * three
9240 seven * seven
9241 @end example
9242
9243 @node Calc++ Parsing Driver
9244 @subsubsection Calc++ Parsing Driver
9245 @c - An env
9246 @c - A place to store error messages
9247 @c - A place for the result
9248
9249 To support a pure interface with the parser (and the scanner) the
9250 technique of the ``parsing context'' is convenient: a structure
9251 containing all the data to exchange. Since, in addition to simply
9252 launch the parsing, there are several auxiliary tasks to execute (open
9253 the file for parsing, instantiate the parser etc.), we recommend
9254 transforming the simple parsing context structure into a fully blown
9255 @dfn{parsing driver} class.
9256
9257 The declaration of this driver class, @file{calc++-driver.hh}, is as
9258 follows. The first part includes the CPP guard and imports the
9259 required standard library components, and the declaration of the parser
9260 class.
9261
9262 @comment file: calc++-driver.hh
9263 @example
9264 #ifndef CALCXX_DRIVER_HH
9265 # define CALCXX_DRIVER_HH
9266 # include <string>
9267 # include <map>
9268 # include "calc++-parser.hh"
9269 @end example
9270
9271
9272 @noindent
9273 Then comes the declaration of the scanning function. Flex expects
9274 the signature of @code{yylex} to be defined in the macro
9275 @code{YY_DECL}, and the C++ parser expects it to be declared. We can
9276 factor both as follows.
9277
9278 @comment file: calc++-driver.hh
9279 @example
9280 // Tell Flex the lexer's prototype ...
9281 # define YY_DECL \
9282 yy::calcxx_parser::symbol_type yylex (calcxx_driver& driver)
9283 // ... and declare it for the parser's sake.
9284 YY_DECL;
9285 @end example
9286
9287 @noindent
9288 The @code{calcxx_driver} class is then declared with its most obvious
9289 members.
9290
9291 @comment file: calc++-driver.hh
9292 @example
9293 // Conducting the whole scanning and parsing of Calc++.
9294 class calcxx_driver
9295 @{
9296 public:
9297 calcxx_driver ();
9298 virtual ~calcxx_driver ();
9299
9300 std::map<std::string, int> variables;
9301
9302 int result;
9303 @end example
9304
9305 @noindent
9306 To encapsulate the coordination with the Flex scanner, it is useful to have
9307 member functions to open and close the scanning phase.
9308
9309 @comment file: calc++-driver.hh
9310 @example
9311 // Handling the scanner.
9312 void scan_begin ();
9313 void scan_end ();
9314 bool trace_scanning;
9315 @end example
9316
9317 @noindent
9318 Similarly for the parser itself.
9319
9320 @comment file: calc++-driver.hh
9321 @example
9322 // Run the parser on file F.
9323 // Return 0 on success.
9324 int parse (const std::string& f);
9325 // The name of the file being parsed.
9326 // Used later to pass the file name to the location tracker.
9327 std::string file;
9328 // Whether parser traces should be generated.
9329 bool trace_parsing;
9330 @end example
9331
9332 @noindent
9333 To demonstrate pure handling of parse errors, instead of simply
9334 dumping them on the standard error output, we will pass them to the
9335 compiler driver using the following two member functions. Finally, we
9336 close the class declaration and CPP guard.
9337
9338 @comment file: calc++-driver.hh
9339 @example
9340 // Error handling.
9341 void error (const yy::location& l, const std::string& m);
9342 void error (const std::string& m);
9343 @};
9344 #endif // ! CALCXX_DRIVER_HH
9345 @end example
9346
9347 The implementation of the driver is straightforward. The @code{parse}
9348 member function deserves some attention. The @code{error} functions
9349 are simple stubs, they should actually register the located error
9350 messages and set error state.
9351
9352 @comment file: calc++-driver.cc
9353 @example
9354 #include "calc++-driver.hh"
9355 #include "calc++-parser.hh"
9356
9357 calcxx_driver::calcxx_driver ()
9358 : trace_scanning (false), trace_parsing (false)
9359 @{
9360 variables["one"] = 1;
9361 variables["two"] = 2;
9362 @}
9363
9364 calcxx_driver::~calcxx_driver ()
9365 @{
9366 @}
9367
9368 int
9369 calcxx_driver::parse (const std::string &f)
9370 @{
9371 file = f;
9372 scan_begin ();
9373 yy::calcxx_parser parser (*this);
9374 parser.set_debug_level (trace_parsing);
9375 int res = parser.parse ();
9376 scan_end ();
9377 return res;
9378 @}
9379
9380 void
9381 calcxx_driver::error (const yy::location& l, const std::string& m)
9382 @{
9383 std::cerr << l << ": " << m << std::endl;
9384 @}
9385
9386 void
9387 calcxx_driver::error (const std::string& m)
9388 @{
9389 std::cerr << m << std::endl;
9390 @}
9391 @end example
9392
9393 @node Calc++ Parser
9394 @subsubsection Calc++ Parser
9395
9396 The grammar file @file{calc++-parser.yy} starts by asking for the C++
9397 deterministic parser skeleton, the creation of the parser header file,
9398 and specifies the name of the parser class. Because the C++ skeleton
9399 changed several times, it is safer to require the version you designed
9400 the grammar for.
9401
9402 @comment file: calc++-parser.yy
9403 @example
9404 %skeleton "lalr1.cc" /* -*- C++ -*- */
9405 %require "@value{VERSION}"
9406 %defines
9407 %define parser_class_name "calcxx_parser"
9408 @end example
9409
9410 @noindent
9411 @findex %define variant
9412 @findex %define lex_symbol
9413 This example will use genuine C++ objects as semantic values, therefore, we
9414 require the variant-based interface. To make sure we properly use it, we
9415 enable assertions. To fully benefit from type-safety and more natural
9416 definition of ``symbol'', we enable @code{lex_symbol}.
9417
9418 @comment file: calc++-parser.yy
9419 @example
9420 %define variant
9421 %define parse.assert
9422 %define lex_symbol
9423 @end example
9424
9425 @noindent
9426 @findex %code requires
9427 Then come the declarations/inclusions needed by the semantic values.
9428 Because the parser uses the parsing driver and reciprocally, both would like
9429 to include the header of the other, which is, of course, insane. This
9430 mutual dependency will be broken using forward declarations. Because the
9431 driver's header needs detailed knowledge about the parser class (in
9432 particular its inner types), it is the parser's header which will use a
9433 forward declaration of the driver. @xref{Decl Summary, ,%code}.
9434
9435 @comment file: calc++-parser.yy
9436 @example
9437 %code requires
9438 @{
9439 # include <string>
9440 class calcxx_driver;
9441 @}
9442 @end example
9443
9444 @noindent
9445 The driver is passed by reference to the parser and to the scanner.
9446 This provides a simple but effective pure interface, not relying on
9447 global variables.
9448
9449 @comment file: calc++-parser.yy
9450 @example
9451 // The parsing context.
9452 %param @{ calcxx_driver& driver @}
9453 @end example
9454
9455 @noindent
9456 Then we request location tracking, and initialize the
9457 first location's file name. Afterward new locations are computed
9458 relatively to the previous locations: the file name will be
9459 propagated.
9460
9461 @comment file: calc++-parser.yy
9462 @example
9463 %locations
9464 %initial-action
9465 @{
9466 // Initialize the initial location.
9467 @@$.begin.filename = @@$.end.filename = &driver.file;
9468 @};
9469 @end example
9470
9471 @noindent
9472 Use the following two directives to enable parser tracing and verbose
9473 error messages.
9474
9475 @comment file: calc++-parser.yy
9476 @example
9477 %define parse.trace
9478 %define parse.error verbose
9479 @end example
9480
9481 @noindent
9482 @findex %code
9483 The code between @samp{%code @{} and @samp{@}} is output in the
9484 @file{*.cc} file; it needs detailed knowledge about the driver.
9485
9486 @comment file: calc++-parser.yy
9487 @example
9488 %code
9489 @{
9490 # include "calc++-driver.hh"
9491 @}
9492 @end example
9493
9494
9495 @noindent
9496 The token numbered as 0 corresponds to end of file; the following line
9497 allows for nicer error messages referring to ``end of file'' instead of
9498 ``$end''. Similarly user friendly names are provided for each symbol.
9499 To avoid name clashes in the generated files (@pxref{Calc++ Scanner}),
9500 prefix tokens with @code{TOK_} (@pxref{Decl Summary,, api.tokens.prefix}).
9501
9502 @comment file: calc++-parser.yy
9503 @example
9504 %define api.tokens.prefix "TOK_"
9505 %token
9506 END 0 "end of file"
9507 ASSIGN ":="
9508 MINUS "-"
9509 PLUS "+"
9510 STAR "*"
9511 SLASH "/"
9512 LPAREN "("
9513 RPAREN ")"
9514 ;
9515 @end example
9516
9517 @noindent
9518 Since we use variant-based semantic values, @code{%union} is not used, and
9519 both @code{%type} and @code{%token} expect genuine types, as opposed to type
9520 tags.
9521
9522 @comment file: calc++-parser.yy
9523 @example
9524 %token <std::string> IDENTIFIER "identifier"
9525 %token <int> NUMBER "number"
9526 %type <int> exp
9527 @end example
9528
9529 @noindent
9530 No @code{%destructor} is needed to enable memory deallocation during error
9531 recovery; the memory, for strings for instance, will be reclaimed by the
9532 regular destructors. All the values are printed using their
9533 @code{operator<<}.
9534
9535 @c FIXME: Document %printer, and mention that it takes a braced-code operand.
9536 @comment file: calc++-parser.yy
9537 @example
9538 %printer @{ debug_stream () << $$; @} <*>;
9539 @end example
9540
9541 @noindent
9542 The grammar itself is straightforward (@pxref{Location Tracking Calc, ,
9543 Location Tracking Calculator: @code{ltcalc}}).
9544
9545 @comment file: calc++-parser.yy
9546 @example
9547 %%
9548 %start unit;
9549 unit: assignments exp @{ driver.result = $2; @};
9550
9551 assignments:
9552 assignments assignment @{@}
9553 | /* Nothing. */ @{@};
9554
9555 assignment:
9556 "identifier" ":=" exp @{ driver.variables[$1] = $3; @};
9557
9558 %left "+" "-";
9559 %left "*" "/";
9560 exp:
9561 exp "+" exp @{ $$ = $1 + $3; @}
9562 | exp "-" exp @{ $$ = $1 - $3; @}
9563 | exp "*" exp @{ $$ = $1 * $3; @}
9564 | exp "/" exp @{ $$ = $1 / $3; @}
9565 | "(" exp ")" @{ std::swap ($$, $2); @}
9566 | "identifier" @{ $$ = driver.variables[$1]; @}
9567 | "number" @{ std::swap ($$, $1); @};
9568 %%
9569 @end example
9570
9571 @noindent
9572 Finally the @code{error} member function registers the errors to the
9573 driver.
9574
9575 @comment file: calc++-parser.yy
9576 @example
9577 void
9578 yy::calcxx_parser::error (const location_type& l,
9579 const std::string& m)
9580 @{
9581 driver.error (l, m);
9582 @}
9583 @end example
9584
9585 @node Calc++ Scanner
9586 @subsubsection Calc++ Scanner
9587
9588 The Flex scanner first includes the driver declaration, then the
9589 parser's to get the set of defined tokens.
9590
9591 @comment file: calc++-scanner.ll
9592 @example
9593 %@{ /* -*- C++ -*- */
9594 # include <cerrno>
9595 # include <climits>
9596 # include <cstdlib>
9597 # include <string>
9598 # include "calc++-driver.hh"
9599 # include "calc++-parser.hh"
9600
9601 // Work around an incompatibility in flex (at least versions
9602 // 2.5.31 through 2.5.33): it generates code that does
9603 // not conform to C89. See Debian bug 333231
9604 // <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>.
9605 # undef yywrap
9606 # define yywrap() 1
9607
9608 // The location of the current token.
9609 static yy::location loc;
9610 %@}
9611 @end example
9612
9613 @noindent
9614 Because there is no @code{#include}-like feature we don't need
9615 @code{yywrap}, we don't need @code{unput} either, and we parse an
9616 actual file, this is not an interactive session with the user.
9617 Finally, we enable scanner tracing.
9618
9619 @comment file: calc++-scanner.ll
9620 @example
9621 %option noyywrap nounput batch debug
9622 @end example
9623
9624 @noindent
9625 Abbreviations allow for more readable rules.
9626
9627 @comment file: calc++-scanner.ll
9628 @example
9629 id [a-zA-Z][a-zA-Z_0-9]*
9630 int [0-9]+
9631 blank [ \t]
9632 @end example
9633
9634 @noindent
9635 The following paragraph suffices to track locations accurately. Each
9636 time @code{yylex} is invoked, the begin position is moved onto the end
9637 position. Then when a pattern is matched, its width is added to the end
9638 column. When matching ends of lines, the end
9639 cursor is adjusted, and each time blanks are matched, the begin cursor
9640 is moved onto the end cursor to effectively ignore the blanks
9641 preceding tokens. Comments would be treated equally.
9642
9643 @comment file: calc++-scanner.ll
9644 @example
9645 %@{
9646 // Code run each time a pattern is matched.
9647 # define YY_USER_ACTION loc.columns (yyleng);
9648 %@}
9649 %%
9650 %@{
9651 // Code run each time yylex is called.
9652 loc.step ();
9653 %@}
9654 @{blank@}+ loc.step ();
9655 [\n]+ loc.lines (yyleng); loc.step ();
9656 @end example
9657
9658 @noindent
9659 The rules are simple. The driver is used to report errors.
9660
9661 @comment file: calc++-scanner.ll
9662 @example
9663 "-" return yy::calcxx_parser::make_MINUS(loc);
9664 "+" return yy::calcxx_parser::make_PLUS(loc);
9665 "*" return yy::calcxx_parser::make_STAR(loc);
9666 "/" return yy::calcxx_parser::make_SLASH(loc);
9667 "(" return yy::calcxx_parser::make_LPAREN(loc);
9668 ")" return yy::calcxx_parser::make_RPAREN(loc);
9669 ":=" return yy::calcxx_parser::make_ASSIGN(loc);
9670
9671 @{int@} @{
9672 errno = 0;
9673 long n = strtol (yytext, NULL, 10);
9674 if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
9675 driver.error (loc, "integer is out of range");
9676 return yy::calcxx_parser::make_NUMBER(n, loc);
9677 @}
9678 @{id@} return yy::calcxx_parser::make_IDENTIFIER(yytext, loc);
9679 . driver.error (loc, "invalid character");
9680 <<EOF>> return yy::calcxx_parser::make_END(loc);
9681 %%
9682 @end example
9683
9684 @noindent
9685 Finally, because the scanner-related driver's member-functions depend
9686 on the scanner's data, it is simpler to implement them in this file.
9687
9688 @comment file: calc++-scanner.ll
9689 @example
9690 void
9691 calcxx_driver::scan_begin ()
9692 @{
9693 yy_flex_debug = trace_scanning;
9694 if (file == "-")
9695 yyin = stdin;
9696 else if (!(yyin = fopen (file.c_str (), "r")))
9697 @{
9698 error (std::string ("cannot open ") + file + ": " + strerror(errno));
9699 exit (1);
9700 @}
9701 @}
9702
9703 void
9704 calcxx_driver::scan_end ()
9705 @{
9706 fclose (yyin);
9707 @}
9708 @end example
9709
9710 @node Calc++ Top Level
9711 @subsubsection Calc++ Top Level
9712
9713 The top level file, @file{calc++.cc}, poses no problem.
9714
9715 @comment file: calc++.cc
9716 @example
9717 #include <iostream>
9718 #include "calc++-driver.hh"
9719
9720 int
9721 main (int argc, char *argv[])
9722 @{
9723 int res = 0;
9724 calcxx_driver driver;
9725 for (++argv; argv[0]; ++argv)
9726 if (*argv == std::string ("-p"))
9727 driver.trace_parsing = true;
9728 else if (*argv == std::string ("-s"))
9729 driver.trace_scanning = true;
9730 else if (!driver.parse (*argv))
9731 std::cout << driver.result << std::endl;
9732 else
9733 res = 1;
9734 return res;
9735 @}
9736 @end example
9737
9738 @node Java Parsers
9739 @section Java Parsers
9740
9741 @menu
9742 * Java Bison Interface:: Asking for Java parser generation
9743 * Java Semantic Values:: %type and %token vs. Java
9744 * Java Location Values:: The position and location classes
9745 * Java Parser Interface:: Instantiating and running the parser
9746 * Java Scanner Interface:: Specifying the scanner for the parser
9747 * Java Action Features:: Special features for use in actions
9748 * Java Differences:: Differences between C/C++ and Java Grammars
9749 * Java Declarations Summary:: List of Bison declarations used with Java
9750 @end menu
9751
9752 @node Java Bison Interface
9753 @subsection Java Bison Interface
9754 @c - %language "Java"
9755
9756 (The current Java interface is experimental and may evolve.
9757 More user feedback will help to stabilize it.)
9758
9759 The Java parser skeletons are selected using the @code{%language "Java"}
9760 directive or the @option{-L java}/@option{--language=java} option.
9761
9762 @c FIXME: Documented bug.
9763 When generating a Java parser, @code{bison @var{basename}.y} will
9764 create a single Java source file named @file{@var{basename}.java}
9765 containing the parser implementation. Using a grammar file without a
9766 @file{.y} suffix is currently broken. The basename of the parser
9767 implementation file can be changed by the @code{%file-prefix}
9768 directive or the @option{-p}/@option{--name-prefix} option. The
9769 entire parser implementation file name can be changed by the
9770 @code{%output} directive or the @option{-o}/@option{--output} option.
9771 The parser implementation file contains a single class for the parser.
9772
9773 You can create documentation for generated parsers using Javadoc.
9774
9775 Contrary to C parsers, Java parsers do not use global variables; the
9776 state of the parser is always local to an instance of the parser class.
9777 Therefore, all Java parsers are ``pure'', and the @code{%pure-parser}
9778 and @samp{%define api.pure} directives does not do anything when used in
9779 Java.
9780
9781 Push parsers are currently unsupported in Java and @code{%define
9782 api.push-pull} have no effect.
9783
9784 GLR parsers are currently unsupported in Java. Do not use the
9785 @code{glr-parser} directive.
9786
9787 No header file can be generated for Java parsers. Do not use the
9788 @code{%defines} directive or the @option{-d}/@option{--defines} options.
9789
9790 @c FIXME: Possible code change.
9791 Currently, support for tracing is always compiled
9792 in. Thus the @samp{%define parse.trace} and @samp{%token-table}
9793 directives and the
9794 @option{-t}/@option{--debug} and @option{-k}/@option{--token-table}
9795 options have no effect. This may change in the future to eliminate
9796 unused code in the generated parser, so use @samp{%define parse.trace}
9797 explicitly
9798 if needed. Also, in the future the
9799 @code{%token-table} directive might enable a public interface to
9800 access the token names and codes.
9801
9802 Getting a ``code too large'' error from the Java compiler means the code
9803 hit the 64KB bytecode per method limitation of the Java class file.
9804 Try reducing the amount of code in actions and static initializers;
9805 otherwise, report a bug so that the parser skeleton will be improved.
9806
9807
9808 @node Java Semantic Values
9809 @subsection Java Semantic Values
9810 @c - No %union, specify type in %type/%token.
9811 @c - YYSTYPE
9812 @c - Printer and destructor
9813
9814 There is no @code{%union} directive in Java parsers. Instead, the
9815 semantic values' types (class names) should be specified in the
9816 @code{%type} or @code{%token} directive:
9817
9818 @example
9819 %type <Expression> expr assignment_expr term factor
9820 %type <Integer> number
9821 @end example
9822
9823 By default, the semantic stack is declared to have @code{Object} members,
9824 which means that the class types you specify can be of any class.
9825 To improve the type safety of the parser, you can declare the common
9826 superclass of all the semantic values using the @samp{%define stype}
9827 directive. For example, after the following declaration:
9828
9829 @example
9830 %define stype "ASTNode"
9831 @end example
9832
9833 @noindent
9834 any @code{%type} or @code{%token} specifying a semantic type which
9835 is not a subclass of ASTNode, will cause a compile-time error.
9836
9837 @c FIXME: Documented bug.
9838 Types used in the directives may be qualified with a package name.
9839 Primitive data types are accepted for Java version 1.5 or later. Note
9840 that in this case the autoboxing feature of Java 1.5 will be used.
9841 Generic types may not be used; this is due to a limitation in the
9842 implementation of Bison, and may change in future releases.
9843
9844 Java parsers do not support @code{%destructor}, since the language
9845 adopts garbage collection. The parser will try to hold references
9846 to semantic values for as little time as needed.
9847
9848 Java parsers do not support @code{%printer}, as @code{toString()}
9849 can be used to print the semantic values. This however may change
9850 (in a backwards-compatible way) in future versions of Bison.
9851
9852
9853 @node Java Location Values
9854 @subsection Java Location Values
9855 @c - %locations
9856 @c - class Position
9857 @c - class Location
9858
9859 When the directive @code{%locations} is used, the Java parser
9860 supports location tracking, see @ref{Locations, , Locations Overview}.
9861 An auxiliary user-defined class defines a @dfn{position}, a single point
9862 in a file; Bison itself defines a class representing a @dfn{location},
9863 a range composed of a pair of positions (possibly spanning several
9864 files). The location class is an inner class of the parser; the name
9865 is @code{Location} by default, and may also be renamed using
9866 @samp{%define location_type "@var{class-name}"}.
9867
9868 The location class treats the position as a completely opaque value.
9869 By default, the class name is @code{Position}, but this can be changed
9870 with @samp{%define position_type "@var{class-name}"}. This class must
9871 be supplied by the user.
9872
9873
9874 @deftypeivar {Location} {Position} begin
9875 @deftypeivarx {Location} {Position} end
9876 The first, inclusive, position of the range, and the first beyond.
9877 @end deftypeivar
9878
9879 @deftypeop {Constructor} {Location} {} Location (Position @var{loc})
9880 Create a @code{Location} denoting an empty range located at a given point.
9881 @end deftypeop
9882
9883 @deftypeop {Constructor} {Location} {} Location (Position @var{begin}, Position @var{end})
9884 Create a @code{Location} from the endpoints of the range.
9885 @end deftypeop
9886
9887 @deftypemethod {Location} {String} toString ()
9888 Prints the range represented by the location. For this to work
9889 properly, the position class should override the @code{equals} and
9890 @code{toString} methods appropriately.
9891 @end deftypemethod
9892
9893
9894 @node Java Parser Interface
9895 @subsection Java Parser Interface
9896 @c - define parser_class_name
9897 @c - Ctor
9898 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
9899 @c debug_stream.
9900 @c - Reporting errors
9901
9902 The name of the generated parser class defaults to @code{YYParser}. The
9903 @code{YY} prefix may be changed using the @code{%name-prefix} directive
9904 or the @option{-p}/@option{--name-prefix} option. Alternatively, use
9905 @samp{%define parser_class_name "@var{name}"} to give a custom name to
9906 the class. The interface of this class is detailed below.
9907
9908 By default, the parser class has package visibility. A declaration
9909 @samp{%define public} will change to public visibility. Remember that,
9910 according to the Java language specification, the name of the @file{.java}
9911 file should match the name of the class in this case. Similarly, you can
9912 use @code{abstract}, @code{final} and @code{strictfp} with the
9913 @code{%define} declaration to add other modifiers to the parser class.
9914 A single @samp{%define annotations "@var{annotations}"} directive can
9915 be used to add any number of annotations to the parser class.
9916
9917 The Java package name of the parser class can be specified using the
9918 @samp{%define package} directive. The superclass and the implemented
9919 interfaces of the parser class can be specified with the @code{%define
9920 extends} and @samp{%define implements} directives.
9921
9922 The parser class defines an inner class, @code{Location}, that is used
9923 for location tracking (see @ref{Java Location Values}), and a inner
9924 interface, @code{Lexer} (see @ref{Java Scanner Interface}). Other than
9925 these inner class/interface, and the members described in the interface
9926 below, all the other members and fields are preceded with a @code{yy} or
9927 @code{YY} prefix to avoid clashes with user code.
9928
9929 The parser class can be extended using the @code{%parse-param}
9930 directive. Each occurrence of the directive will add a @code{protected
9931 final} field to the parser class, and an argument to its constructor,
9932 which initialize them automatically.
9933
9934 @deftypeop {Constructor} {YYParser} {} YYParser (@var{lex_param}, @dots{}, @var{parse_param}, @dots{})
9935 Build a new parser object with embedded @code{%code lexer}. There are
9936 no parameters, unless @code{%param}s and/or @code{%parse-param}s and/or
9937 @code{%lex-param}s are used.
9938
9939 Use @code{%code init} for code added to the start of the constructor
9940 body. This is especially useful to initialize superclasses. Use
9941 @samp{%define init_throws} to specify any uncaught exceptions.
9942 @end deftypeop
9943
9944 @deftypeop {Constructor} {YYParser} {} YYParser (Lexer @var{lexer}, @var{parse_param}, @dots{})
9945 Build a new parser object using the specified scanner. There are no
9946 additional parameters unless @code{%param}s and/or @code{%parse-param}s are
9947 used.
9948
9949 If the scanner is defined by @code{%code lexer}, this constructor is
9950 declared @code{protected} and is called automatically with a scanner
9951 created with the correct @code{%param}s and/or @code{%lex-param}s.
9952
9953 Use @code{%code init} for code added to the start of the constructor
9954 body. This is especially useful to initialize superclasses. Use
9955 @samp{%define init_throws} to specify any uncatch exceptions.
9956 @end deftypeop
9957
9958 @deftypemethod {YYParser} {boolean} parse ()
9959 Run the syntactic analysis, and return @code{true} on success,
9960 @code{false} otherwise.
9961 @end deftypemethod
9962
9963 @deftypemethod {YYParser} {boolean} getErrorVerbose ()
9964 @deftypemethodx {YYParser} {void} setErrorVerbose (boolean @var{verbose})
9965 Get or set the option to produce verbose error messages. These are only
9966 available with @samp{%define parse.error verbose}, which also turns on
9967 verbose error messages.
9968 @end deftypemethod
9969
9970 @deftypemethod {YYParser} {void} yyerror (String @var{msg})
9971 @deftypemethodx {YYParser} {void} yyerror (Position @var{pos}, String @var{msg})
9972 @deftypemethodx {YYParser} {void} yyerror (Location @var{loc}, String @var{msg})
9973 Print an error message using the @code{yyerror} method of the scanner
9974 instance in use. The @code{Location} and @code{Position} parameters are
9975 available only if location tracking is active.
9976 @end deftypemethod
9977
9978 @deftypemethod {YYParser} {boolean} recovering ()
9979 During the syntactic analysis, return @code{true} if recovering
9980 from a syntax error.
9981 @xref{Error Recovery}.
9982 @end deftypemethod
9983
9984 @deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
9985 @deftypemethodx {YYParser} {void} setDebugStream (java.io.printStream @var{o})
9986 Get or set the stream used for tracing the parsing. It defaults to
9987 @code{System.err}.
9988 @end deftypemethod
9989
9990 @deftypemethod {YYParser} {int} getDebugLevel ()
9991 @deftypemethodx {YYParser} {void} setDebugLevel (int @var{l})
9992 Get or set the tracing level. Currently its value is either 0, no trace,
9993 or nonzero, full tracing.
9994 @end deftypemethod
9995
9996 @deftypecv {Constant} {YYParser} {String} {bisonVersion}
9997 @deftypecvx {Constant} {YYParser} {String} {bisonSkeleton}
9998 Identify the Bison version and skeleton used to generate this parser.
9999 @end deftypecv
10000
10001
10002 @node Java Scanner Interface
10003 @subsection Java Scanner Interface
10004 @c - %code lexer
10005 @c - %lex-param
10006 @c - Lexer interface
10007
10008 There are two possible ways to interface a Bison-generated Java parser
10009 with a scanner: the scanner may be defined by @code{%code lexer}, or
10010 defined elsewhere. In either case, the scanner has to implement the
10011 @code{Lexer} inner interface of the parser class. This interface also
10012 contain constants for all user-defined token names and the predefined
10013 @code{EOF} token.
10014
10015 In the first case, the body of the scanner class is placed in
10016 @code{%code lexer} blocks. If you want to pass parameters from the
10017 parser constructor to the scanner constructor, specify them with
10018 @code{%lex-param}; they are passed before @code{%parse-param}s to the
10019 constructor.
10020
10021 In the second case, the scanner has to implement the @code{Lexer} interface,
10022 which is defined within the parser class (e.g., @code{YYParser.Lexer}).
10023 The constructor of the parser object will then accept an object
10024 implementing the interface; @code{%lex-param} is not used in this
10025 case.
10026
10027 In both cases, the scanner has to implement the following methods.
10028
10029 @deftypemethod {Lexer} {void} yyerror (Location @var{loc}, String @var{msg})
10030 This method is defined by the user to emit an error message. The first
10031 parameter is omitted if location tracking is not active. Its type can be
10032 changed using @samp{%define location_type "@var{class-name}".}
10033 @end deftypemethod
10034
10035 @deftypemethod {Lexer} {int} yylex ()
10036 Return the next token. Its type is the return value, its semantic
10037 value and location are saved and returned by the their methods in the
10038 interface.
10039
10040 Use @samp{%define lex_throws} to specify any uncaught exceptions.
10041 Default is @code{java.io.IOException}.
10042 @end deftypemethod
10043
10044 @deftypemethod {Lexer} {Position} getStartPos ()
10045 @deftypemethodx {Lexer} {Position} getEndPos ()
10046 Return respectively the first position of the last token that
10047 @code{yylex} returned, and the first position beyond it. These
10048 methods are not needed unless location tracking is active.
10049
10050 The return type can be changed using @samp{%define position_type
10051 "@var{class-name}".}
10052 @end deftypemethod
10053
10054 @deftypemethod {Lexer} {Object} getLVal ()
10055 Return the semantic value of the last token that yylex returned.
10056
10057 The return type can be changed using @samp{%define stype
10058 "@var{class-name}".}
10059 @end deftypemethod
10060
10061
10062 @node Java Action Features
10063 @subsection Special Features for Use in Java Actions
10064
10065 The following special constructs can be uses in Java actions.
10066 Other analogous C action features are currently unavailable for Java.
10067
10068 Use @samp{%define throws} to specify any uncaught exceptions from parser
10069 actions, and initial actions specified by @code{%initial-action}.
10070
10071 @defvar $@var{n}
10072 The semantic value for the @var{n}th component of the current rule.
10073 This may not be assigned to.
10074 @xref{Java Semantic Values}.
10075 @end defvar
10076
10077 @defvar $<@var{typealt}>@var{n}
10078 Like @code{$@var{n}} but specifies a alternative type @var{typealt}.
10079 @xref{Java Semantic Values}.
10080 @end defvar
10081
10082 @defvar $$
10083 The semantic value for the grouping made by the current rule. As a
10084 value, this is in the base type (@code{Object} or as specified by
10085 @samp{%define stype}) as in not cast to the declared subtype because
10086 casts are not allowed on the left-hand side of Java assignments.
10087 Use an explicit Java cast if the correct subtype is needed.
10088 @xref{Java Semantic Values}.
10089 @end defvar
10090
10091 @defvar $<@var{typealt}>$
10092 Same as @code{$$} since Java always allow assigning to the base type.
10093 Perhaps we should use this and @code{$<>$} for the value and @code{$$}
10094 for setting the value but there is currently no easy way to distinguish
10095 these constructs.
10096 @xref{Java Semantic Values}.
10097 @end defvar
10098
10099 @defvar @@@var{n}
10100 The location information of the @var{n}th component of the current rule.
10101 This may not be assigned to.
10102 @xref{Java Location Values}.
10103 @end defvar
10104
10105 @defvar @@$
10106 The location information of the grouping made by the current rule.
10107 @xref{Java Location Values}.
10108 @end defvar
10109
10110 @deffn {Statement} {return YYABORT;}
10111 Return immediately from the parser, indicating failure.
10112 @xref{Java Parser Interface}.
10113 @end deffn
10114
10115 @deffn {Statement} {return YYACCEPT;}
10116 Return immediately from the parser, indicating success.
10117 @xref{Java Parser Interface}.
10118 @end deffn
10119
10120 @deffn {Statement} {return YYERROR;}
10121 Start error recovery without printing an error message.
10122 @xref{Error Recovery}.
10123 @end deffn
10124
10125 @deftypefn {Function} {boolean} recovering ()
10126 Return whether error recovery is being done. In this state, the parser
10127 reads token until it reaches a known state, and then restarts normal
10128 operation.
10129 @xref{Error Recovery}.
10130 @end deftypefn
10131
10132 @deftypefn {Function} {void} yyerror (String @var{msg})
10133 @deftypefnx {Function} {void} yyerror (Position @var{loc}, String @var{msg})
10134 @deftypefnx {Function} {void} yyerror (Location @var{loc}, String @var{msg})
10135 Print an error message using the @code{yyerror} method of the scanner
10136 instance in use. The @code{Location} and @code{Position} parameters are
10137 available only if location tracking is active.
10138 @end deftypefn
10139
10140
10141 @node Java Differences
10142 @subsection Differences between C/C++ and Java Grammars
10143
10144 The different structure of the Java language forces several differences
10145 between C/C++ grammars, and grammars designed for Java parsers. This
10146 section summarizes these differences.
10147
10148 @itemize
10149 @item
10150 Java lacks a preprocessor, so the @code{YYERROR}, @code{YYACCEPT},
10151 @code{YYABORT} symbols (@pxref{Table of Symbols}) cannot obviously be
10152 macros. Instead, they should be preceded by @code{return} when they
10153 appear in an action. The actual definition of these symbols is
10154 opaque to the Bison grammar, and it might change in the future. The
10155 only meaningful operation that you can do, is to return them.
10156 See @pxref{Java Action Features}.
10157
10158 Note that of these three symbols, only @code{YYACCEPT} and
10159 @code{YYABORT} will cause a return from the @code{yyparse}
10160 method@footnote{Java parsers include the actions in a separate
10161 method than @code{yyparse} in order to have an intuitive syntax that
10162 corresponds to these C macros.}.
10163
10164 @item
10165 Java lacks unions, so @code{%union} has no effect. Instead, semantic
10166 values have a common base type: @code{Object} or as specified by
10167 @samp{%define stype}. Angle brackets on @code{%token}, @code{type},
10168 @code{$@var{n}} and @code{$$} specify subtypes rather than fields of
10169 an union. The type of @code{$$}, even with angle brackets, is the base
10170 type since Java casts are not allow on the left-hand side of assignments.
10171 Also, @code{$@var{n}} and @code{@@@var{n}} are not allowed on the
10172 left-hand side of assignments. See @pxref{Java Semantic Values} and
10173 @pxref{Java Action Features}.
10174
10175 @item
10176 The prologue declarations have a different meaning than in C/C++ code.
10177 @table @asis
10178 @item @code{%code imports}
10179 blocks are placed at the beginning of the Java source code. They may
10180 include copyright notices. For a @code{package} declarations, it is
10181 suggested to use @samp{%define package} instead.
10182
10183 @item unqualified @code{%code}
10184 blocks are placed inside the parser class.
10185
10186 @item @code{%code lexer}
10187 blocks, if specified, should include the implementation of the
10188 scanner. If there is no such block, the scanner can be any class
10189 that implements the appropriate interface (see @pxref{Java Scanner
10190 Interface}).
10191 @end table
10192
10193 Other @code{%code} blocks are not supported in Java parsers.
10194 In particular, @code{%@{ @dots{} %@}} blocks should not be used
10195 and may give an error in future versions of Bison.
10196
10197 The epilogue has the same meaning as in C/C++ code and it can
10198 be used to define other classes used by the parser @emph{outside}
10199 the parser class.
10200 @end itemize
10201
10202
10203 @node Java Declarations Summary
10204 @subsection Java Declarations Summary
10205
10206 This summary only include declarations specific to Java or have special
10207 meaning when used in a Java parser.
10208
10209 @deffn {Directive} {%language "Java"}
10210 Generate a Java class for the parser.
10211 @end deffn
10212
10213 @deffn {Directive} %lex-param @{@var{type} @var{name}@}
10214 A parameter for the lexer class defined by @code{%code lexer}
10215 @emph{only}, added as parameters to the lexer constructor and the parser
10216 constructor that @emph{creates} a lexer. Default is none.
10217 @xref{Java Scanner Interface}.
10218 @end deffn
10219
10220 @deffn {Directive} %name-prefix "@var{prefix}"
10221 The prefix of the parser class name @code{@var{prefix}Parser} if
10222 @samp{%define parser_class_name} is not used. Default is @code{YY}.
10223 @xref{Java Bison Interface}.
10224 @end deffn
10225
10226 @deffn {Directive} %parse-param @{@var{type} @var{name}@}
10227 A parameter for the parser class added as parameters to constructor(s)
10228 and as fields initialized by the constructor(s). Default is none.
10229 @xref{Java Parser Interface}.
10230 @end deffn
10231
10232 @deffn {Directive} %token <@var{type}> @var{token} @dots{}
10233 Declare tokens. Note that the angle brackets enclose a Java @emph{type}.
10234 @xref{Java Semantic Values}.
10235 @end deffn
10236
10237 @deffn {Directive} %type <@var{type}> @var{nonterminal} @dots{}
10238 Declare the type of nonterminals. Note that the angle brackets enclose
10239 a Java @emph{type}.
10240 @xref{Java Semantic Values}.
10241 @end deffn
10242
10243 @deffn {Directive} %code @{ @var{code} @dots{} @}
10244 Code appended to the inside of the parser class.
10245 @xref{Java Differences}.
10246 @end deffn
10247
10248 @deffn {Directive} {%code imports} @{ @var{code} @dots{} @}
10249 Code inserted just after the @code{package} declaration.
10250 @xref{Java Differences}.
10251 @end deffn
10252
10253 @deffn {Directive} {%code init} @{ @var{code} @dots{} @}
10254 Code inserted at the beginning of the parser constructor body.
10255 @xref{Java Parser Interface}.
10256 @end deffn
10257
10258 @deffn {Directive} {%code lexer} @{ @var{code} @dots{} @}
10259 Code added to the body of a inner lexer class within the parser class.
10260 @xref{Java Scanner Interface}.
10261 @end deffn
10262
10263 @deffn {Directive} %% @var{code} @dots{}
10264 Code (after the second @code{%%}) appended to the end of the file,
10265 @emph{outside} the parser class.
10266 @xref{Java Differences}.
10267 @end deffn
10268
10269 @deffn {Directive} %@{ @var{code} @dots{} %@}
10270 Not supported. Use @code{%code imports} instead.
10271 @xref{Java Differences}.
10272 @end deffn
10273
10274 @deffn {Directive} {%define abstract}
10275 Whether the parser class is declared @code{abstract}. Default is false.
10276 @xref{Java Bison Interface}.
10277 @end deffn
10278
10279 @deffn {Directive} {%define annotations} "@var{annotations}"
10280 The Java annotations for the parser class. Default is none.
10281 @xref{Java Bison Interface}.
10282 @end deffn
10283
10284 @deffn {Directive} {%define extends} "@var{superclass}"
10285 The superclass of the parser class. Default is none.
10286 @xref{Java Bison Interface}.
10287 @end deffn
10288
10289 @deffn {Directive} {%define final}
10290 Whether the parser class is declared @code{final}. Default is false.
10291 @xref{Java Bison Interface}.
10292 @end deffn
10293
10294 @deffn {Directive} {%define implements} "@var{interfaces}"
10295 The implemented interfaces of the parser class, a comma-separated list.
10296 Default is none.
10297 @xref{Java Bison Interface}.
10298 @end deffn
10299
10300 @deffn {Directive} {%define init_throws} "@var{exceptions}"
10301 The exceptions thrown by @code{%code init} from the parser class
10302 constructor. Default is none.
10303 @xref{Java Parser Interface}.
10304 @end deffn
10305
10306 @deffn {Directive} {%define lex_throws} "@var{exceptions}"
10307 The exceptions thrown by the @code{yylex} method of the lexer, a
10308 comma-separated list. Default is @code{java.io.IOException}.
10309 @xref{Java Scanner Interface}.
10310 @end deffn
10311
10312 @deffn {Directive} {%define location_type} "@var{class}"
10313 The name of the class used for locations (a range between two
10314 positions). This class is generated as an inner class of the parser
10315 class by @command{bison}. Default is @code{Location}.
10316 @xref{Java Location Values}.
10317 @end deffn
10318
10319 @deffn {Directive} {%define package} "@var{package}"
10320 The package to put the parser class in. Default is none.
10321 @xref{Java Bison Interface}.
10322 @end deffn
10323
10324 @deffn {Directive} {%define parser_class_name} "@var{name}"
10325 The name of the parser class. Default is @code{YYParser} or
10326 @code{@var{name-prefix}Parser}.
10327 @xref{Java Bison Interface}.
10328 @end deffn
10329
10330 @deffn {Directive} {%define position_type} "@var{class}"
10331 The name of the class used for positions. This class must be supplied by
10332 the user. Default is @code{Position}.
10333 @xref{Java Location Values}.
10334 @end deffn
10335
10336 @deffn {Directive} {%define public}
10337 Whether the parser class is declared @code{public}. Default is false.
10338 @xref{Java Bison Interface}.
10339 @end deffn
10340
10341 @deffn {Directive} {%define stype} "@var{class}"
10342 The base type of semantic values. Default is @code{Object}.
10343 @xref{Java Semantic Values}.
10344 @end deffn
10345
10346 @deffn {Directive} {%define strictfp}
10347 Whether the parser class is declared @code{strictfp}. Default is false.
10348 @xref{Java Bison Interface}.
10349 @end deffn
10350
10351 @deffn {Directive} {%define throws} "@var{exceptions}"
10352 The exceptions thrown by user-supplied parser actions and
10353 @code{%initial-action}, a comma-separated list. Default is none.
10354 @xref{Java Parser Interface}.
10355 @end deffn
10356
10357
10358 @c ================================================= FAQ
10359
10360 @node FAQ
10361 @chapter Frequently Asked Questions
10362 @cindex frequently asked questions
10363 @cindex questions
10364
10365 Several questions about Bison come up occasionally. Here some of them
10366 are addressed.
10367
10368 @menu
10369 * Memory Exhausted:: Breaking the Stack Limits
10370 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
10371 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
10372 * Implementing Gotos/Loops:: Control Flow in the Calculator
10373 * Multiple start-symbols:: Factoring closely related grammars
10374 * Secure? Conform?:: Is Bison POSIX safe?
10375 * I can't build Bison:: Troubleshooting
10376 * Where can I find help?:: Troubleshouting
10377 * Bug Reports:: Troublereporting
10378 * More Languages:: Parsers in C++, Java, and so on
10379 * Beta Testing:: Experimenting development versions
10380 * Mailing Lists:: Meeting other Bison users
10381 @end menu
10382
10383 @node Memory Exhausted
10384 @section Memory Exhausted
10385
10386 @display
10387 My parser returns with error with a @samp{memory exhausted}
10388 message. What can I do?
10389 @end display
10390
10391 This question is already addressed elsewhere, @xref{Recursion,
10392 ,Recursive Rules}.
10393
10394 @node How Can I Reset the Parser
10395 @section How Can I Reset the Parser
10396
10397 The following phenomenon has several symptoms, resulting in the
10398 following typical questions:
10399
10400 @display
10401 I invoke @code{yyparse} several times, and on correct input it works
10402 properly; but when a parse error is found, all the other calls fail
10403 too. How can I reset the error flag of @code{yyparse}?
10404 @end display
10405
10406 @noindent
10407 or
10408
10409 @display
10410 My parser includes support for an @samp{#include}-like feature, in
10411 which case I run @code{yyparse} from @code{yyparse}. This fails
10412 although I did specify @samp{%define api.pure}.
10413 @end display
10414
10415 These problems typically come not from Bison itself, but from
10416 Lex-generated scanners. Because these scanners use large buffers for
10417 speed, they might not notice a change of input file. As a
10418 demonstration, consider the following source file,
10419 @file{first-line.l}:
10420
10421 @verbatim
10422 %{
10423 #include <stdio.h>
10424 #include <stdlib.h>
10425 %}
10426 %%
10427 .*\n ECHO; return 1;
10428 %%
10429 int
10430 yyparse (char const *file)
10431 {
10432 yyin = fopen (file, "r");
10433 if (!yyin)
10434 exit (2);
10435 /* One token only. */
10436 yylex ();
10437 if (fclose (yyin) != 0)
10438 exit (3);
10439 return 0;
10440 }
10441
10442 int
10443 main (void)
10444 {
10445 yyparse ("input");
10446 yyparse ("input");
10447 return 0;
10448 }
10449 @end verbatim
10450
10451 @noindent
10452 If the file @file{input} contains
10453
10454 @verbatim
10455 input:1: Hello,
10456 input:2: World!
10457 @end verbatim
10458
10459 @noindent
10460 then instead of getting the first line twice, you get:
10461
10462 @example
10463 $ @kbd{flex -ofirst-line.c first-line.l}
10464 $ @kbd{gcc -ofirst-line first-line.c -ll}
10465 $ @kbd{./first-line}
10466 input:1: Hello,
10467 input:2: World!
10468 @end example
10469
10470 Therefore, whenever you change @code{yyin}, you must tell the
10471 Lex-generated scanner to discard its current buffer and switch to the
10472 new one. This depends upon your implementation of Lex; see its
10473 documentation for more. For Flex, it suffices to call
10474 @samp{YY_FLUSH_BUFFER} after each change to @code{yyin}. If your
10475 Flex-generated scanner needs to read from several input streams to
10476 handle features like include files, you might consider using Flex
10477 functions like @samp{yy_switch_to_buffer} that manipulate multiple
10478 input buffers.
10479
10480 If your Flex-generated scanner uses start conditions (@pxref{Start
10481 conditions, , Start conditions, flex, The Flex Manual}), you might
10482 also want to reset the scanner's state, i.e., go back to the initial
10483 start condition, through a call to @samp{BEGIN (0)}.
10484
10485 @node Strings are Destroyed
10486 @section Strings are Destroyed
10487
10488 @display
10489 My parser seems to destroy old strings, or maybe it loses track of
10490 them. Instead of reporting @samp{"foo", "bar"}, it reports
10491 @samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
10492 @end display
10493
10494 This error is probably the single most frequent ``bug report'' sent to
10495 Bison lists, but is only concerned with a misunderstanding of the role
10496 of the scanner. Consider the following Lex code:
10497
10498 @verbatim
10499 %{
10500 #include <stdio.h>
10501 char *yylval = NULL;
10502 %}
10503 %%
10504 .* yylval = yytext; return 1;
10505 \n /* IGNORE */
10506 %%
10507 int
10508 main ()
10509 {
10510 /* Similar to using $1, $2 in a Bison action. */
10511 char *fst = (yylex (), yylval);
10512 char *snd = (yylex (), yylval);
10513 printf ("\"%s\", \"%s\"\n", fst, snd);
10514 return 0;
10515 }
10516 @end verbatim
10517
10518 If you compile and run this code, you get:
10519
10520 @example
10521 $ @kbd{flex -osplit-lines.c split-lines.l}
10522 $ @kbd{gcc -osplit-lines split-lines.c -ll}
10523 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
10524 "one
10525 two", "two"
10526 @end example
10527
10528 @noindent
10529 this is because @code{yytext} is a buffer provided for @emph{reading}
10530 in the action, but if you want to keep it, you have to duplicate it
10531 (e.g., using @code{strdup}). Note that the output may depend on how
10532 your implementation of Lex handles @code{yytext}. For instance, when
10533 given the Lex compatibility option @option{-l} (which triggers the
10534 option @samp{%array}) Flex generates a different behavior:
10535
10536 @example
10537 $ @kbd{flex -l -osplit-lines.c split-lines.l}
10538 $ @kbd{gcc -osplit-lines split-lines.c -ll}
10539 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
10540 "two", "two"
10541 @end example
10542
10543
10544 @node Implementing Gotos/Loops
10545 @section Implementing Gotos/Loops
10546
10547 @display
10548 My simple calculator supports variables, assignments, and functions,
10549 but how can I implement gotos, or loops?
10550 @end display
10551
10552 Although very pedagogical, the examples included in the document blur
10553 the distinction to make between the parser---whose job is to recover
10554 the structure of a text and to transmit it to subsequent modules of
10555 the program---and the processing (such as the execution) of this
10556 structure. This works well with so called straight line programs,
10557 i.e., precisely those that have a straightforward execution model:
10558 execute simple instructions one after the others.
10559
10560 @cindex abstract syntax tree
10561 @cindex AST
10562 If you want a richer model, you will probably need to use the parser
10563 to construct a tree that does represent the structure it has
10564 recovered; this tree is usually called the @dfn{abstract syntax tree},
10565 or @dfn{AST} for short. Then, walking through this tree,
10566 traversing it in various ways, will enable treatments such as its
10567 execution or its translation, which will result in an interpreter or a
10568 compiler.
10569
10570 This topic is way beyond the scope of this manual, and the reader is
10571 invited to consult the dedicated literature.
10572
10573
10574 @node Multiple start-symbols
10575 @section Multiple start-symbols
10576
10577 @display
10578 I have several closely related grammars, and I would like to share their
10579 implementations. In fact, I could use a single grammar but with
10580 multiple entry points.
10581 @end display
10582
10583 Bison does not support multiple start-symbols, but there is a very
10584 simple means to simulate them. If @code{foo} and @code{bar} are the two
10585 pseudo start-symbols, then introduce two new tokens, say
10586 @code{START_FOO} and @code{START_BAR}, and use them as switches from the
10587 real start-symbol:
10588
10589 @example
10590 %token START_FOO START_BAR;
10591 %start start;
10592 start: START_FOO foo
10593 | START_BAR bar;
10594 @end example
10595
10596 These tokens prevents the introduction of new conflicts. As far as the
10597 parser goes, that is all that is needed.
10598
10599 Now the difficult part is ensuring that the scanner will send these
10600 tokens first. If your scanner is hand-written, that should be
10601 straightforward. If your scanner is generated by Lex, them there is
10602 simple means to do it: recall that anything between @samp{%@{ ... %@}}
10603 after the first @code{%%} is copied verbatim in the top of the generated
10604 @code{yylex} function. Make sure a variable @code{start_token} is
10605 available in the scanner (e.g., a global variable or using
10606 @code{%lex-param} etc.), and use the following:
10607
10608 @example
10609 /* @r{Prologue.} */
10610 %%
10611 %@{
10612 if (start_token)
10613 @{
10614 int t = start_token;
10615 start_token = 0;
10616 return t;
10617 @}
10618 %@}
10619 /* @r{The rules.} */
10620 @end example
10621
10622
10623 @node Secure? Conform?
10624 @section Secure? Conform?
10625
10626 @display
10627 Is Bison secure? Does it conform to POSIX?
10628 @end display
10629
10630 If you're looking for a guarantee or certification, we don't provide it.
10631 However, Bison is intended to be a reliable program that conforms to the
10632 POSIX specification for Yacc. If you run into problems,
10633 please send us a bug report.
10634
10635 @node I can't build Bison
10636 @section I can't build Bison
10637
10638 @display
10639 I can't build Bison because @command{make} complains that
10640 @code{msgfmt} is not found.
10641 What should I do?
10642 @end display
10643
10644 Like most GNU packages with internationalization support, that feature
10645 is turned on by default. If you have problems building in the @file{po}
10646 subdirectory, it indicates that your system's internationalization
10647 support is lacking. You can re-configure Bison with
10648 @option{--disable-nls} to turn off this support, or you can install GNU
10649 gettext from @url{ftp://ftp.gnu.org/gnu/gettext/} and re-configure
10650 Bison. See the file @file{ABOUT-NLS} for more information.
10651
10652
10653 @node Where can I find help?
10654 @section Where can I find help?
10655
10656 @display
10657 I'm having trouble using Bison. Where can I find help?
10658 @end display
10659
10660 First, read this fine manual. Beyond that, you can send mail to
10661 @email{help-bison@@gnu.org}. This mailing list is intended to be
10662 populated with people who are willing to answer questions about using
10663 and installing Bison. Please keep in mind that (most of) the people on
10664 the list have aspects of their lives which are not related to Bison (!),
10665 so you may not receive an answer to your question right away. This can
10666 be frustrating, but please try not to honk them off; remember that any
10667 help they provide is purely voluntary and out of the kindness of their
10668 hearts.
10669
10670 @node Bug Reports
10671 @section Bug Reports
10672
10673 @display
10674 I found a bug. What should I include in the bug report?
10675 @end display
10676
10677 Before you send a bug report, make sure you are using the latest
10678 version. Check @url{ftp://ftp.gnu.org/pub/gnu/bison/} or one of its
10679 mirrors. Be sure to include the version number in your bug report. If
10680 the bug is present in the latest version but not in a previous version,
10681 try to determine the most recent version which did not contain the bug.
10682
10683 If the bug is parser-related, you should include the smallest grammar
10684 you can which demonstrates the bug. The grammar file should also be
10685 complete (i.e., I should be able to run it through Bison without having
10686 to edit or add anything). The smaller and simpler the grammar, the
10687 easier it will be to fix the bug.
10688
10689 Include information about your compilation environment, including your
10690 operating system's name and version and your compiler's name and
10691 version. If you have trouble compiling, you should also include a
10692 transcript of the build session, starting with the invocation of
10693 `configure'. Depending on the nature of the bug, you may be asked to
10694 send additional files as well (such as `config.h' or `config.cache').
10695
10696 Patches are most welcome, but not required. That is, do not hesitate to
10697 send a bug report just because you can not provide a fix.
10698
10699 Send bug reports to @email{bug-bison@@gnu.org}.
10700
10701 @node More Languages
10702 @section More Languages
10703
10704 @display
10705 Will Bison ever have C++ and Java support? How about @var{insert your
10706 favorite language here}?
10707 @end display
10708
10709 C++ and Java support is there now, and is documented. We'd love to add other
10710 languages; contributions are welcome.
10711
10712 @node Beta Testing
10713 @section Beta Testing
10714
10715 @display
10716 What is involved in being a beta tester?
10717 @end display
10718
10719 It's not terribly involved. Basically, you would download a test
10720 release, compile it, and use it to build and run a parser or two. After
10721 that, you would submit either a bug report or a message saying that
10722 everything is okay. It is important to report successes as well as
10723 failures because test releases eventually become mainstream releases,
10724 but only if they are adequately tested. If no one tests, development is
10725 essentially halted.
10726
10727 Beta testers are particularly needed for operating systems to which the
10728 developers do not have easy access. They currently have easy access to
10729 recent GNU/Linux and Solaris versions. Reports about other operating
10730 systems are especially welcome.
10731
10732 @node Mailing Lists
10733 @section Mailing Lists
10734
10735 @display
10736 How do I join the help-bison and bug-bison mailing lists?
10737 @end display
10738
10739 See @url{http://lists.gnu.org/}.
10740
10741 @c ================================================= Table of Symbols
10742
10743 @node Table of Symbols
10744 @appendix Bison Symbols
10745 @cindex Bison symbols, table of
10746 @cindex symbols in Bison, table of
10747
10748 @deffn {Variable} @@$
10749 In an action, the location of the left-hand side of the rule.
10750 @xref{Locations, , Locations Overview}.
10751 @end deffn
10752
10753 @deffn {Variable} @@@var{n}
10754 In an action, the location of the @var{n}-th symbol of the right-hand
10755 side of the rule. @xref{Locations, , Locations Overview}.
10756 @end deffn
10757
10758 @deffn {Variable} @@@var{name}
10759 In an action, the location of a symbol addressed by name.
10760 @xref{Locations, , Locations Overview}.
10761 @end deffn
10762
10763 @deffn {Variable} @@[@var{name}]
10764 In an action, the location of a symbol addressed by name.
10765 @xref{Locations, , Locations Overview}.
10766 @end deffn
10767
10768 @deffn {Variable} $$
10769 In an action, the semantic value of the left-hand side of the rule.
10770 @xref{Actions}.
10771 @end deffn
10772
10773 @deffn {Variable} $@var{n}
10774 In an action, the semantic value of the @var{n}-th symbol of the
10775 right-hand side of the rule. @xref{Actions}.
10776 @end deffn
10777
10778 @deffn {Variable} $@var{name}
10779 In an action, the semantic value of a symbol addressed by name.
10780 @xref{Actions}.
10781 @end deffn
10782
10783 @deffn {Variable} $[@var{name}]
10784 In an action, the semantic value of a symbol addressed by name.
10785 @xref{Actions}.
10786 @end deffn
10787
10788 @deffn {Delimiter} %%
10789 Delimiter used to separate the grammar rule section from the
10790 Bison declarations section or the epilogue.
10791 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
10792 @end deffn
10793
10794 @c Don't insert spaces, or check the DVI output.
10795 @deffn {Delimiter} %@{@var{code}%@}
10796 All code listed between @samp{%@{} and @samp{%@}} is copied verbatim
10797 to the parser implementation file. Such code forms the prologue of
10798 the grammar file. @xref{Grammar Outline, ,Outline of a Bison
10799 Grammar}.
10800 @end deffn
10801
10802 @deffn {Directive} %?@{@var{expression}@}
10803 Predicate actions. This is a type of action clause that may appear in
10804 rules. The expression is evaluated, and if false, causes a syntax error. In
10805 GLR parsers during nondeterministic operation,
10806 this silently causes an alternative parse to die. During deterministic
10807 operation, it is the same as the effect of YYERROR.
10808 @xref{Semantic Predicates}.
10809
10810 This feature is experimental.
10811 More user feedback will help to determine whether it should become a permanent
10812 feature.
10813 @end deffn
10814
10815 @deffn {Construct} /*@dots{}*/
10816 Comment delimiters, as in C.
10817 @end deffn
10818
10819 @deffn {Delimiter} :
10820 Separates a rule's result from its components. @xref{Rules, ,Syntax of
10821 Grammar Rules}.
10822 @end deffn
10823
10824 @deffn {Delimiter} ;
10825 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
10826 @end deffn
10827
10828 @deffn {Delimiter} |
10829 Separates alternate rules for the same result nonterminal.
10830 @xref{Rules, ,Syntax of Grammar Rules}.
10831 @end deffn
10832
10833 @deffn {Directive} <*>
10834 Used to define a default tagged @code{%destructor} or default tagged
10835 @code{%printer}.
10836
10837 This feature is experimental.
10838 More user feedback will help to determine whether it should become a permanent
10839 feature.
10840
10841 @xref{Destructor Decl, , Freeing Discarded Symbols}.
10842 @end deffn
10843
10844 @deffn {Directive} <>
10845 Used to define a default tagless @code{%destructor} or default tagless
10846 @code{%printer}.
10847
10848 This feature is experimental.
10849 More user feedback will help to determine whether it should become a permanent
10850 feature.
10851
10852 @xref{Destructor Decl, , Freeing Discarded Symbols}.
10853 @end deffn
10854
10855 @deffn {Symbol} $accept
10856 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
10857 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
10858 Start-Symbol}. It cannot be used in the grammar.
10859 @end deffn
10860
10861 @deffn {Directive} %code @{@var{code}@}
10862 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
10863 Insert @var{code} verbatim into output parser source.
10864 @xref{Decl Summary,,%code}.
10865 @end deffn
10866
10867 @deffn {Directive} %debug
10868 Equip the parser for debugging. @xref{Decl Summary}.
10869 @end deffn
10870
10871 @ifset defaultprec
10872 @deffn {Directive} %default-prec
10873 Assign a precedence to rules that lack an explicit @samp{%prec}
10874 modifier. @xref{Contextual Precedence, ,Context-Dependent
10875 Precedence}.
10876 @end deffn
10877 @end ifset
10878
10879 @deffn {Directive} %define @var{define-variable}
10880 @deffnx {Directive} %define @var{define-variable} @var{value}
10881 @deffnx {Directive} %define @var{define-variable} "@var{value}"
10882 Define a variable to adjust Bison's behavior.
10883 @xref{Decl Summary,,%define}.
10884 @end deffn
10885
10886 @deffn {Directive} %defines
10887 Bison declaration to create a parser header file, which is usually
10888 meant for the scanner. @xref{Decl Summary}.
10889 @end deffn
10890
10891 @deffn {Directive} %defines @var{defines-file}
10892 Same as above, but save in the file @var{defines-file}.
10893 @xref{Decl Summary}.
10894 @end deffn
10895
10896 @deffn {Directive} %destructor
10897 Specify how the parser should reclaim the memory associated to
10898 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
10899 @end deffn
10900
10901 @deffn {Directive} %dprec
10902 Bison declaration to assign a precedence to a rule that is used at parse
10903 time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
10904 GLR Parsers}.
10905 @end deffn
10906
10907 @deffn {Symbol} $end
10908 The predefined token marking the end of the token stream. It cannot be
10909 used in the grammar.
10910 @end deffn
10911
10912 @deffn {Symbol} error
10913 A token name reserved for error recovery. This token may be used in
10914 grammar rules so as to allow the Bison parser to recognize an error in
10915 the grammar without halting the process. In effect, a sentence
10916 containing an error may be recognized as valid. On a syntax error, the
10917 token @code{error} becomes the current lookahead token. Actions
10918 corresponding to @code{error} are then executed, and the lookahead
10919 token is reset to the token that originally caused the violation.
10920 @xref{Error Recovery}.
10921 @end deffn
10922
10923 @deffn {Directive} %error-verbose
10924 An obsolete directive standing for @samp{%define parse.error verbose}.
10925 @end deffn
10926
10927 @deffn {Directive} %file-prefix "@var{prefix}"
10928 Bison declaration to set the prefix of the output files. @xref{Decl
10929 Summary}.
10930 @end deffn
10931
10932 @deffn {Directive} %glr-parser
10933 Bison declaration to produce a GLR parser. @xref{GLR
10934 Parsers, ,Writing GLR Parsers}.
10935 @end deffn
10936
10937 @deffn {Directive} %initial-action
10938 Run user code before parsing. @xref{Initial Action Decl, , Performing Actions before Parsing}.
10939 @end deffn
10940
10941 @deffn {Directive} %language
10942 Specify the programming language for the generated parser.
10943 @xref{Decl Summary}.
10944 @end deffn
10945
10946 @deffn {Directive} %left
10947 Bison declaration to assign precedence and left associativity to token(s).
10948 @xref{Precedence Decl, ,Operator Precedence}.
10949 @end deffn
10950
10951 @deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
10952 Bison declaration to specifying additional arguments that
10953 @code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
10954 for Pure Parsers}.
10955 @end deffn
10956
10957 @deffn {Directive} %merge
10958 Bison declaration to assign a merging function to a rule. If there is a
10959 reduce/reduce conflict with a rule having the same merging function, the
10960 function is applied to the two semantic values to get a single result.
10961 @xref{GLR Parsers, ,Writing GLR Parsers}.
10962 @end deffn
10963
10964 @deffn {Directive} %name-prefix "@var{prefix}"
10965 Bison declaration to rename the external symbols. @xref{Decl Summary}.
10966 @end deffn
10967
10968 @ifset defaultprec
10969 @deffn {Directive} %no-default-prec
10970 Do not assign a precedence to rules that lack an explicit @samp{%prec}
10971 modifier. @xref{Contextual Precedence, ,Context-Dependent
10972 Precedence}.
10973 @end deffn
10974 @end ifset
10975
10976 @deffn {Directive} %no-lines
10977 Bison declaration to avoid generating @code{#line} directives in the
10978 parser implementation file. @xref{Decl Summary}.
10979 @end deffn
10980
10981 @deffn {Directive} %nonassoc
10982 Bison declaration to assign precedence and nonassociativity to token(s).
10983 @xref{Precedence Decl, ,Operator Precedence}.
10984 @end deffn
10985
10986 @deffn {Directive} %output "@var{file}"
10987 Bison declaration to set the name of the parser implementation file.
10988 @xref{Decl Summary}.
10989 @end deffn
10990
10991 @deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
10992 Bison declaration to specify additional arguments that both
10993 @code{yylex} and @code{yyparse} should accept. @xref{Parser Function,, The
10994 Parser Function @code{yyparse}}.
10995 @end deffn
10996
10997 @deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
10998 Bison declaration to specify additional arguments that @code{yyparse}
10999 should accept. @xref{Parser Function,, The Parser Function @code{yyparse}}.
11000 @end deffn
11001
11002 @deffn {Directive} %prec
11003 Bison declaration to assign a precedence to a specific rule.
11004 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
11005 @end deffn
11006
11007 @deffn {Directive} %precedence
11008 Bison declaration to assign precedence to token(s), but no associativity
11009 @xref{Precedence Decl, ,Operator Precedence}.
11010 @end deffn
11011
11012 @deffn {Directive} %pure-parser
11013 Deprecated version of @samp{%define api.pure} (@pxref{Decl Summary, ,%define}),
11014 for which Bison is more careful to warn about unreasonable usage.
11015 @end deffn
11016
11017 @deffn {Directive} %require "@var{version}"
11018 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
11019 Require a Version of Bison}.
11020 @end deffn
11021
11022 @deffn {Directive} %right
11023 Bison declaration to assign precedence and right associativity to token(s).
11024 @xref{Precedence Decl, ,Operator Precedence}.
11025 @end deffn
11026
11027 @deffn {Directive} %skeleton
11028 Specify the skeleton to use; usually for development.
11029 @xref{Decl Summary}.
11030 @end deffn
11031
11032 @deffn {Directive} %start
11033 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
11034 Start-Symbol}.
11035 @end deffn
11036
11037 @deffn {Directive} %token
11038 Bison declaration to declare token(s) without specifying precedence.
11039 @xref{Token Decl, ,Token Type Names}.
11040 @end deffn
11041
11042 @deffn {Directive} %token-table
11043 Bison declaration to include a token name table in the parser
11044 implementation file. @xref{Decl Summary}.
11045 @end deffn
11046
11047 @deffn {Directive} %type
11048 Bison declaration to declare nonterminals. @xref{Type Decl,
11049 ,Nonterminal Symbols}.
11050 @end deffn
11051
11052 @deffn {Symbol} $undefined
11053 The predefined token onto which all undefined values returned by
11054 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
11055 @code{error}.
11056 @end deffn
11057
11058 @deffn {Directive} %union
11059 Bison declaration to specify several possible data types for semantic
11060 values. @xref{Union Decl, ,The Collection of Value Types}.
11061 @end deffn
11062
11063 @deffn {Macro} YYABORT
11064 Macro to pretend that an unrecoverable syntax error has occurred, by
11065 making @code{yyparse} return 1 immediately. The error reporting
11066 function @code{yyerror} is not called. @xref{Parser Function, ,The
11067 Parser Function @code{yyparse}}.
11068
11069 For Java parsers, this functionality is invoked using @code{return YYABORT;}
11070 instead.
11071 @end deffn
11072
11073 @deffn {Macro} YYACCEPT
11074 Macro to pretend that a complete utterance of the language has been
11075 read, by making @code{yyparse} return 0 immediately.
11076 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
11077
11078 For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
11079 instead.
11080 @end deffn
11081
11082 @deffn {Macro} YYBACKUP
11083 Macro to discard a value from the parser stack and fake a lookahead
11084 token. @xref{Action Features, ,Special Features for Use in Actions}.
11085 @end deffn
11086
11087 @deffn {Variable} yychar
11088 External integer variable that contains the integer value of the
11089 lookahead token. (In a pure parser, it is a local variable within
11090 @code{yyparse}.) Error-recovery rule actions may examine this variable.
11091 @xref{Action Features, ,Special Features for Use in Actions}.
11092 @end deffn
11093
11094 @deffn {Variable} yyclearin
11095 Macro used in error-recovery rule actions. It clears the previous
11096 lookahead token. @xref{Error Recovery}.
11097 @end deffn
11098
11099 @deffn {Macro} YYDEBUG
11100 Macro to define to equip the parser with tracing code. @xref{Tracing,
11101 ,Tracing Your Parser}.
11102 @end deffn
11103
11104 @deffn {Variable} yydebug
11105 External integer variable set to zero by default. If @code{yydebug}
11106 is given a nonzero value, the parser will output information on input
11107 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
11108 @end deffn
11109
11110 @deffn {Macro} yyerrok
11111 Macro to cause parser to recover immediately to its normal mode
11112 after a syntax error. @xref{Error Recovery}.
11113 @end deffn
11114
11115 @deffn {Macro} YYERROR
11116 Macro to pretend that a syntax error has just been detected: call
11117 @code{yyerror} and then perform normal error recovery if possible
11118 (@pxref{Error Recovery}), or (if recovery is impossible) make
11119 @code{yyparse} return 1. @xref{Error Recovery}.
11120
11121 For Java parsers, this functionality is invoked using @code{return YYERROR;}
11122 instead.
11123 @end deffn
11124
11125 @deffn {Function} yyerror
11126 User-supplied function to be called by @code{yyparse} on error.
11127 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
11128 @end deffn
11129
11130 @deffn {Macro} YYERROR_VERBOSE
11131 An obsolete macro used in the @file{yacc.c} skeleton, that you define
11132 with @code{#define} in the prologue to request verbose, specific error
11133 message strings when @code{yyerror} is called. It doesn't matter what
11134 definition you use for @code{YYERROR_VERBOSE}, just whether you define
11135 it. Using @samp{%define parse.error verbose} is preferred
11136 (@pxref{Error Reporting, ,The Error Reporting Function @code{yyerror}}).
11137 @end deffn
11138
11139 @deffn {Macro} YYINITDEPTH
11140 Macro for specifying the initial size of the parser stack.
11141 @xref{Memory Management}.
11142 @end deffn
11143
11144 @deffn {Function} yylex
11145 User-supplied lexical analyzer function, called with no arguments to get
11146 the next token. @xref{Lexical, ,The Lexical Analyzer Function
11147 @code{yylex}}.
11148 @end deffn
11149
11150 @deffn {Macro} YYLEX_PARAM
11151 An obsolete macro for specifying an extra argument (or list of extra
11152 arguments) for @code{yyparse} to pass to @code{yylex}. The use of this
11153 macro is deprecated, and is supported only for Yacc like parsers.
11154 @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
11155 @end deffn
11156
11157 @deffn {Variable} yylloc
11158 External variable in which @code{yylex} should place the line and column
11159 numbers associated with a token. (In a pure parser, it is a local
11160 variable within @code{yyparse}, and its address is passed to
11161 @code{yylex}.)
11162 You can ignore this variable if you don't use the @samp{@@} feature in the
11163 grammar actions.
11164 @xref{Token Locations, ,Textual Locations of Tokens}.
11165 In semantic actions, it stores the location of the lookahead token.
11166 @xref{Actions and Locations, ,Actions and Locations}.
11167 @end deffn
11168
11169 @deffn {Type} YYLTYPE
11170 Data type of @code{yylloc}; by default, a structure with four
11171 members. @xref{Location Type, , Data Types of Locations}.
11172 @end deffn
11173
11174 @deffn {Variable} yylval
11175 External variable in which @code{yylex} should place the semantic
11176 value associated with a token. (In a pure parser, it is a local
11177 variable within @code{yyparse}, and its address is passed to
11178 @code{yylex}.)
11179 @xref{Token Values, ,Semantic Values of Tokens}.
11180 In semantic actions, it stores the semantic value of the lookahead token.
11181 @xref{Actions, ,Actions}.
11182 @end deffn
11183
11184 @deffn {Macro} YYMAXDEPTH
11185 Macro for specifying the maximum size of the parser stack. @xref{Memory
11186 Management}.
11187 @end deffn
11188
11189 @deffn {Variable} yynerrs
11190 Global variable which Bison increments each time it reports a syntax error.
11191 (In a pure parser, it is a local variable within @code{yyparse}. In a
11192 pure push parser, it is a member of yypstate.)
11193 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
11194 @end deffn
11195
11196 @deffn {Function} yyparse
11197 The parser function produced by Bison; call this function to start
11198 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
11199 @end deffn
11200
11201 @deffn {Function} yypstate_delete
11202 The function to delete a parser instance, produced by Bison in push mode;
11203 call this function to delete the memory associated with a parser.
11204 @xref{Parser Delete Function, ,The Parser Delete Function
11205 @code{yypstate_delete}}.
11206 (The current push parsing interface is experimental and may evolve.
11207 More user feedback will help to stabilize it.)
11208 @end deffn
11209
11210 @deffn {Function} yypstate_new
11211 The function to create a parser instance, produced by Bison in push mode;
11212 call this function to create a new parser.
11213 @xref{Parser Create Function, ,The Parser Create Function
11214 @code{yypstate_new}}.
11215 (The current push parsing interface is experimental and may evolve.
11216 More user feedback will help to stabilize it.)
11217 @end deffn
11218
11219 @deffn {Function} yypull_parse
11220 The parser function produced by Bison in push mode; call this function to
11221 parse the rest of the input stream.
11222 @xref{Pull Parser Function, ,The Pull Parser Function
11223 @code{yypull_parse}}.
11224 (The current push parsing interface is experimental and may evolve.
11225 More user feedback will help to stabilize it.)
11226 @end deffn
11227
11228 @deffn {Function} yypush_parse
11229 The parser function produced by Bison in push mode; call this function to
11230 parse a single token. @xref{Push Parser Function, ,The Push Parser Function
11231 @code{yypush_parse}}.
11232 (The current push parsing interface is experimental and may evolve.
11233 More user feedback will help to stabilize it.)
11234 @end deffn
11235
11236 @deffn {Macro} YYPARSE_PARAM
11237 An obsolete macro for specifying the name of a parameter that
11238 @code{yyparse} should accept. The use of this macro is deprecated, and
11239 is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
11240 Conventions for Pure Parsers}.
11241 @end deffn
11242
11243 @deffn {Macro} YYRECOVERING
11244 The expression @code{YYRECOVERING ()} yields 1 when the parser
11245 is recovering from a syntax error, and 0 otherwise.
11246 @xref{Action Features, ,Special Features for Use in Actions}.
11247 @end deffn
11248
11249 @deffn {Macro} YYSTACK_USE_ALLOCA
11250 Macro used to control the use of @code{alloca} when the
11251 deterministic parser in C needs to extend its stacks. If defined to 0,
11252 the parser will use @code{malloc} to extend its stacks. If defined to
11253 1, the parser will use @code{alloca}. Values other than 0 and 1 are
11254 reserved for future Bison extensions. If not defined,
11255 @code{YYSTACK_USE_ALLOCA} defaults to 0.
11256
11257 In the all-too-common case where your code may run on a host with a
11258 limited stack and with unreliable stack-overflow checking, you should
11259 set @code{YYMAXDEPTH} to a value that cannot possibly result in
11260 unchecked stack overflow on any of your target hosts when
11261 @code{alloca} is called. You can inspect the code that Bison
11262 generates in order to determine the proper numeric values. This will
11263 require some expertise in low-level implementation details.
11264 @end deffn
11265
11266 @deffn {Type} YYSTYPE
11267 Data type of semantic values; @code{int} by default.
11268 @xref{Value Type, ,Data Types of Semantic Values}.
11269 @end deffn
11270
11271 @node Glossary
11272 @appendix Glossary
11273 @cindex glossary
11274
11275 @table @asis
11276 @item Accepting State
11277 A state whose only action is the accept action.
11278 The accepting state is thus a consistent state.
11279 @xref{Understanding,,}.
11280
11281 @item Backus-Naur Form (BNF; also called ``Backus Normal Form'')
11282 Formal method of specifying context-free grammars originally proposed
11283 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
11284 committee document contributing to what became the Algol 60 report.
11285 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11286
11287 @item Consistent State
11288 A state containing only one possible action.
11289 @xref{Decl Summary,,lr.default-reductions}.
11290
11291 @item Context-free grammars
11292 Grammars specified as rules that can be applied regardless of context.
11293 Thus, if there is a rule which says that an integer can be used as an
11294 expression, integers are allowed @emph{anywhere} an expression is
11295 permitted. @xref{Language and Grammar, ,Languages and Context-Free
11296 Grammars}.
11297
11298 @item Default Reduction
11299 The reduction that a parser should perform if the current parser state
11300 contains no other action for the lookahead token.
11301 In permitted parser states, Bison declares the reduction with the
11302 largest lookahead set to be the default reduction and removes that
11303 lookahead set.
11304 @xref{Decl Summary,,lr.default-reductions}.
11305
11306 @item Dynamic allocation
11307 Allocation of memory that occurs during execution, rather than at
11308 compile time or on entry to a function.
11309
11310 @item Empty string
11311 Analogous to the empty set in set theory, the empty string is a
11312 character string of length zero.
11313
11314 @item Finite-state stack machine
11315 A ``machine'' that has discrete states in which it is said to exist at
11316 each instant in time. As input to the machine is processed, the
11317 machine moves from state to state as specified by the logic of the
11318 machine. In the case of the parser, the input is the language being
11319 parsed, and the states correspond to various stages in the grammar
11320 rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
11321
11322 @item Generalized LR (GLR)
11323 A parsing algorithm that can handle all context-free grammars, including those
11324 that are not LR(1). It resolves situations that Bison's
11325 deterministic parsing
11326 algorithm cannot by effectively splitting off multiple parsers, trying all
11327 possible parsers, and discarding those that fail in the light of additional
11328 right context. @xref{Generalized LR Parsing, ,Generalized
11329 LR Parsing}.
11330
11331 @item Grouping
11332 A language construct that is (in general) grammatically divisible;
11333 for example, `expression' or `declaration' in C@.
11334 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11335
11336 @item IELR(1)
11337 A minimal LR(1) parser table generation algorithm.
11338 That is, given any context-free grammar, IELR(1) generates
11339 parser tables with the full language recognition power of canonical
11340 LR(1) but with nearly the same number of parser states as
11341 LALR(1).
11342 This reduction in parser states is often an order of magnitude.
11343 More importantly, because canonical LR(1)'s extra parser
11344 states may contain duplicate conflicts in the case of
11345 non-LR(1) grammars, the number of conflicts for
11346 IELR(1) is often an order of magnitude less as well.
11347 This can significantly reduce the complexity of developing of a grammar.
11348 @xref{Decl Summary,,lr.type}.
11349
11350 @item Infix operator
11351 An arithmetic operator that is placed between the operands on which it
11352 performs some operation.
11353
11354 @item Input stream
11355 A continuous flow of data between devices or programs.
11356
11357 @item LAC (Lookahead Correction)
11358 A parsing mechanism that fixes the problem of delayed syntax error
11359 detection, which is caused by LR state merging, default reductions, and
11360 the use of @code{%nonassoc}. Delayed syntax error detection results in
11361 unexpected semantic actions, initiation of error recovery in the wrong
11362 syntactic context, and an incorrect list of expected tokens in a verbose
11363 syntax error message. @xref{Decl Summary,,parse.lac}.
11364
11365 @item Language construct
11366 One of the typical usage schemas of the language. For example, one of
11367 the constructs of the C language is the @code{if} statement.
11368 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11369
11370 @item Left associativity
11371 Operators having left associativity are analyzed from left to right:
11372 @samp{a+b+c} first computes @samp{a+b} and then combines with
11373 @samp{c}. @xref{Precedence, ,Operator Precedence}.
11374
11375 @item Left recursion
11376 A rule whose result symbol is also its first component symbol; for
11377 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
11378 Rules}.
11379
11380 @item Left-to-right parsing
11381 Parsing a sentence of a language by analyzing it token by token from
11382 left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
11383
11384 @item Lexical analyzer (scanner)
11385 A function that reads an input stream and returns tokens one by one.
11386 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
11387
11388 @item Lexical tie-in
11389 A flag, set by actions in the grammar rules, which alters the way
11390 tokens are parsed. @xref{Lexical Tie-ins}.
11391
11392 @item Literal string token
11393 A token which consists of two or more fixed characters. @xref{Symbols}.
11394
11395 @item Lookahead token
11396 A token already read but not yet shifted. @xref{Lookahead, ,Lookahead
11397 Tokens}.
11398
11399 @item LALR(1)
11400 The class of context-free grammars that Bison (like most other parser
11401 generators) can handle by default; a subset of LR(1).
11402 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
11403
11404 @item LR(1)
11405 The class of context-free grammars in which at most one token of
11406 lookahead is needed to disambiguate the parsing of any piece of input.
11407
11408 @item Nonterminal symbol
11409 A grammar symbol standing for a grammatical construct that can
11410 be expressed through rules in terms of smaller constructs; in other
11411 words, a construct that is not a token. @xref{Symbols}.
11412
11413 @item Parser
11414 A function that recognizes valid sentences of a language by analyzing
11415 the syntax structure of a set of tokens passed to it from a lexical
11416 analyzer.
11417
11418 @item Postfix operator
11419 An arithmetic operator that is placed after the operands upon which it
11420 performs some operation.
11421
11422 @item Reduction
11423 Replacing a string of nonterminals and/or terminals with a single
11424 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
11425 Parser Algorithm}.
11426
11427 @item Reentrant
11428 A reentrant subprogram is a subprogram which can be in invoked any
11429 number of times in parallel, without interference between the various
11430 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
11431
11432 @item Reverse polish notation
11433 A language in which all operators are postfix operators.
11434
11435 @item Right recursion
11436 A rule whose result symbol is also its last component symbol; for
11437 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
11438 Rules}.
11439
11440 @item Semantics
11441 In computer languages, the semantics are specified by the actions
11442 taken for each instance of the language, i.e., the meaning of
11443 each statement. @xref{Semantics, ,Defining Language Semantics}.
11444
11445 @item Shift
11446 A parser is said to shift when it makes the choice of analyzing
11447 further input from the stream rather than reducing immediately some
11448 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
11449
11450 @item Single-character literal
11451 A single character that is recognized and interpreted as is.
11452 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
11453
11454 @item Start symbol
11455 The nonterminal symbol that stands for a complete valid utterance in
11456 the language being parsed. The start symbol is usually listed as the
11457 first nonterminal symbol in a language specification.
11458 @xref{Start Decl, ,The Start-Symbol}.
11459
11460 @item Symbol table
11461 A data structure where symbol names and associated data are stored
11462 during parsing to allow for recognition and use of existing
11463 information in repeated uses of a symbol. @xref{Multi-function Calc}.
11464
11465 @item Syntax error
11466 An error encountered during parsing of an input stream due to invalid
11467 syntax. @xref{Error Recovery}.
11468
11469 @item Token
11470 A basic, grammatically indivisible unit of a language. The symbol
11471 that describes a token in the grammar is a terminal symbol.
11472 The input of the Bison parser is a stream of tokens which comes from
11473 the lexical analyzer. @xref{Symbols}.
11474
11475 @item Terminal symbol
11476 A grammar symbol that has no rules in the grammar and therefore is
11477 grammatically indivisible. The piece of text it represents is a token.
11478 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11479 @end table
11480
11481 @node Copying This Manual
11482 @appendix Copying This Manual
11483 @include fdl.texi
11484
11485 @node Index
11486 @unnumbered Index
11487
11488 @printindex cp
11489
11490 @bye
11491
11492 @c LocalWords: texinfo setfilename settitle setchapternewpage finalout texi FSF
11493 @c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex FSF's
11494 @c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry Naur
11495 @c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa Multi
11496 @c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc multi
11497 @c LocalWords: rpcalc Lexer Expr ltcalc mfcalc yylex defaultprec Donnelly Gotos
11498 @c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref yypush
11499 @c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex lr
11500 @c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init stmtMerge POSIX
11501 @c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG yypull
11502 @c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit nonfree
11503 @c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok rr
11504 @c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln Stallman Destructor
11505 @c LocalWords: smallexample symrec val tptr FNCT fnctptr func struct sym enum
11506 @c LocalWords: fnct putsym getsym fname arith fncts atan ptr malloc sizeof Lex
11507 @c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum DOTDOT
11508 @c LocalWords: ptypes itype YYPRINT trigraphs yytname expseq vindex dtype Unary
11509 @c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs nonterminal
11510 @c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES reentrant
11511 @c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param yypstate
11512 @c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP subrange
11513 @c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword loc
11514 @c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH inline
11515 @c LocalWords: YYINITDEPTH stmnts ref stmnt initdcl maybeasm notype Lookahead
11516 @c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args Autoconf
11517 @c LocalWords: infile ypp yxx outfile itemx tex leaderfill Troubleshouting sqrt
11518 @c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll lookahead
11519 @c LocalWords: nbar yytext fst snd osplit ntwo strdup AST Troublereporting th
11520 @c LocalWords: YYSTACK DVI fdl printindex IELR nondeterministic nonterminals ps
11521 @c LocalWords: subexpressions declarator nondeferred config libintl postfix LAC
11522 @c LocalWords: preprocessor nonpositive unary nonnumeric typedef extern rhs
11523 @c LocalWords: yytokentype destructor multicharacter nonnull EBCDIC
11524 @c LocalWords: lvalue nonnegative XNUM CHR chr TAGLESS tagless stdout api TOK
11525 @c LocalWords: destructors Reentrancy nonreentrant subgrammar nonassociative
11526 @c LocalWords: deffnx namespace xml goto lalr ielr runtime lex yacc yyps env
11527 @c LocalWords: yystate variadic Unshift NLS gettext po UTF Automake LOCALEDIR
11528 @c LocalWords: YYENABLE bindtextdomain Makefile DEFS CPPFLAGS DBISON DeRemer
11529 @c LocalWords: autoreconf Pennello multisets nondeterminism Generalised baz
11530 @c LocalWords: redeclare automata Dparse localedir datadir XSLT midrule Wno
11531 @c LocalWords: Graphviz multitable headitem hh basename Doxygen fno
11532 @c LocalWords: doxygen ival sval deftypemethod deallocate pos deftypemethodx
11533 @c LocalWords: Ctor defcv defcvx arg accessors arithmetics CPP ifndef CALCXX
11534 @c LocalWords: lexer's calcxx bool LPAREN RPAREN deallocation cerrno climits
11535 @c LocalWords: cstdlib Debian undef yywrap unput noyywrap nounput zA yyleng
11536 @c LocalWords: errno strtol ERANGE str strerror iostream argc argv Javadoc
11537 @c LocalWords: bytecode initializers superclass stype ASTNode autoboxing nls
11538 @c LocalWords: toString deftypeivar deftypeivarx deftypeop YYParser strictfp
11539 @c LocalWords: superclasses boolean getErrorVerbose setErrorVerbose deftypecv
11540 @c LocalWords: getDebugStream setDebugStream getDebugLevel setDebugLevel url
11541 @c LocalWords: bisonVersion deftypecvx bisonSkeleton getStartPos getEndPos
11542 @c LocalWords: getLVal defvar deftypefn deftypefnx gotos msgfmt Corbett
11543 @c LocalWords: subdirectory Solaris nonassociativity
11544
11545 @c Local Variables:
11546 @c ispell-dictionary: "american"
11547 @c fill-column: 76
11548 @c End: