]> git.saurik.com Git - bison.git/blob - doc/bison.texinfo
doc: add bibliography to manual.
[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 * Bibliography:: Publications cited in this manual.
113 * Index:: Cross-references to the text.
114
115 @detailmenu
116 --- The Detailed Node Listing ---
117
118 The Concepts of Bison
119
120 * Language and Grammar:: Languages and context-free grammars,
121 as mathematical ideas.
122 * Grammar in Bison:: How we represent grammars for Bison's sake.
123 * Semantic Values:: Each token or syntactic grouping can have
124 a semantic value (the value of an integer,
125 the name of an identifier, etc.).
126 * Semantic Actions:: Each rule can have an action containing C code.
127 * GLR Parsers:: Writing parsers for general context-free languages.
128 * Locations Overview:: Tracking Locations.
129 * Bison Parser:: What are Bison's input and output,
130 how is the output used?
131 * Stages:: Stages in writing and running Bison grammars.
132 * Grammar Layout:: Overall structure of a Bison grammar file.
133
134 Writing GLR Parsers
135
136 * Simple GLR Parsers:: Using GLR parsers on unambiguous grammars.
137 * Merging GLR Parses:: Using GLR parsers to resolve ambiguities.
138 * GLR Semantic Actions:: Considerations for semantic values and deferred actions.
139 * Semantic Predicates:: Controlling a parse with arbitrary computations.
140 * Compiler Requirements:: GLR parsers require a modern C compiler.
141
142 Examples
143
144 * RPN Calc:: Reverse polish notation calculator;
145 a first example with no operator precedence.
146 * Infix Calc:: Infix (algebraic) notation calculator.
147 Operator precedence is introduced.
148 * Simple Error Recovery:: Continuing after syntax errors.
149 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
150 * Multi-function Calc:: Calculator with memory and trig functions.
151 It uses multiple data-types for semantic values.
152 * Exercises:: Ideas for improving the multi-function calculator.
153
154 Reverse Polish Notation Calculator
155
156 * Rpcalc Declarations:: Prologue (declarations) for rpcalc.
157 * Rpcalc Rules:: Grammar Rules for rpcalc, with explanation.
158 * Rpcalc Lexer:: The lexical analyzer.
159 * Rpcalc Main:: The controlling function.
160 * Rpcalc Error:: The error reporting function.
161 * Rpcalc Generate:: Running Bison on the grammar file.
162 * Rpcalc Compile:: Run the C compiler on the output code.
163
164 Grammar Rules for @code{rpcalc}
165
166 * Rpcalc Input::
167 * Rpcalc Line::
168 * Rpcalc Expr::
169
170 Location Tracking Calculator: @code{ltcalc}
171
172 * Ltcalc Declarations:: Bison and C declarations for ltcalc.
173 * Ltcalc Rules:: Grammar rules for ltcalc, with explanations.
174 * Ltcalc Lexer:: The lexical analyzer.
175
176 Multi-Function Calculator: @code{mfcalc}
177
178 * Mfcalc Declarations:: Bison declarations for multi-function calculator.
179 * Mfcalc Rules:: Grammar rules for the calculator.
180 * Mfcalc Symbol Table:: Symbol table management subroutines.
181
182 Bison Grammar Files
183
184 * Grammar Outline:: Overall layout of the grammar file.
185 * Symbols:: Terminal and nonterminal symbols.
186 * Rules:: How to write grammar rules.
187 * Recursion:: Writing recursive rules.
188 * Semantics:: Semantic values and actions.
189 * Locations:: Locations and actions.
190 * Declarations:: All kinds of Bison declarations are described here.
191 * Multiple Parsers:: Putting more than one Bison parser in one program.
192
193 Outline of a Bison Grammar
194
195 * Prologue:: Syntax and usage of the prologue.
196 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
197 * Bison Declarations:: Syntax and usage of the Bison declarations section.
198 * Grammar Rules:: Syntax and usage of the grammar rules section.
199 * Epilogue:: Syntax and usage of the epilogue.
200
201 Defining Language Semantics
202
203 * Value Type:: Specifying one data type for all semantic values.
204 * Multiple Types:: Specifying several alternative data types.
205 * Actions:: An action is the semantic definition of a grammar rule.
206 * Action Types:: Specifying data types for actions to operate on.
207 * Mid-Rule Actions:: Most actions go at the end of a rule.
208 This says when, why and how to use the exceptional
209 action in the middle of a rule.
210 * Named References:: Using named references in actions.
211
212 Tracking Locations
213
214 * Location Type:: Specifying a data type for locations.
215 * Actions and Locations:: Using locations in actions.
216 * Location Default Action:: Defining a general way to compute locations.
217
218 Bison Declarations
219
220 * Require Decl:: Requiring a Bison version.
221 * Token Decl:: Declaring terminal symbols.
222 * Precedence Decl:: Declaring terminals with precedence and associativity.
223 * Union Decl:: Declaring the set of all semantic value types.
224 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
225 * Initial Action Decl:: Code run before parsing starts.
226 * Destructor Decl:: Declaring how symbols are freed.
227 * Expect Decl:: Suppressing warnings about parsing conflicts.
228 * Start Decl:: Specifying the start symbol.
229 * Pure Decl:: Requesting a reentrant parser.
230 * Push Decl:: Requesting a push parser.
231 * Decl Summary:: Table of all Bison declarations.
232 * %define Summary:: Defining variables to adjust Bison's behavior.
233 * %code Summary:: Inserting code into the parser source.
234
235 Parser C-Language Interface
236
237 * Parser Function:: How to call @code{yyparse} and what it returns.
238 * Push Parser Function:: How to call @code{yypush_parse} and what it returns.
239 * Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
240 * Parser Create Function:: How to call @code{yypstate_new} and what it returns.
241 * Parser Delete Function:: How to call @code{yypstate_delete} and what it returns.
242 * Lexical:: You must supply a function @code{yylex}
243 which reads tokens.
244 * Error Reporting:: You must supply a function @code{yyerror}.
245 * Action Features:: Special features for use in actions.
246 * Internationalization:: How to let the parser speak in the user's
247 native language.
248
249 The Lexical Analyzer Function @code{yylex}
250
251 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
252 * Token Values:: How @code{yylex} must return the semantic value
253 of the token it has read.
254 * Token Locations:: How @code{yylex} must return the text location
255 (line number, etc.) of the token, if the
256 actions want that.
257 * Pure Calling:: How the calling convention differs in a pure parser
258 (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
259
260 The Bison Parser Algorithm
261
262 * Lookahead:: Parser looks one token ahead when deciding what to do.
263 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
264 * Precedence:: Operator precedence works by resolving conflicts.
265 * Contextual Precedence:: When an operator's precedence depends on context.
266 * Parser States:: The parser is a finite-state-machine with stack.
267 * Reduce/Reduce:: When two rules are applicable in the same situation.
268 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
269 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
270 * Memory Management:: What happens when memory is exhausted. How to avoid it.
271
272 Operator Precedence
273
274 * Why Precedence:: An example showing why precedence is needed.
275 * Using Precedence:: How to specify precedence and associativity.
276 * Precedence Only:: How to specify precedence only.
277 * Precedence Examples:: How these features are used in the previous example.
278 * How Precedence:: How they work.
279
280 Handling Context Dependencies
281
282 * Semantic Tokens:: Token parsing can depend on the semantic context.
283 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
284 * Tie-in Recovery:: Lexical tie-ins have implications for how
285 error recovery rules must be written.
286
287 Debugging Your Parser
288
289 * Understanding:: Understanding the structure of your parser.
290 * Tracing:: Tracing the execution of your parser.
291
292 Invoking Bison
293
294 * Bison Options:: All the options described in detail,
295 in alphabetical order by short options.
296 * Option Cross Key:: Alphabetical list of long options.
297 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
298
299 Parsers Written In Other Languages
300
301 * C++ Parsers:: The interface to generate C++ parser classes
302 * Java Parsers:: The interface to generate Java parser classes
303
304 C++ Parsers
305
306 * C++ Bison Interface:: Asking for C++ parser generation
307 * C++ Semantic Values:: %union vs. C++
308 * C++ Location Values:: The position and location classes
309 * C++ Parser Interface:: Instantiating and running the parser
310 * C++ Scanner Interface:: Exchanges between yylex and parse
311 * A Complete C++ Example:: Demonstrating their use
312
313 A Complete C++ Example
314
315 * Calc++ --- C++ Calculator:: The specifications
316 * Calc++ Parsing Driver:: An active parsing context
317 * Calc++ Parser:: A parser class
318 * Calc++ Scanner:: A pure C++ Flex scanner
319 * Calc++ Top Level:: Conducting the band
320
321 Java Parsers
322
323 * Java Bison Interface:: Asking for Java parser generation
324 * Java Semantic Values:: %type and %token vs. Java
325 * Java Location Values:: The position and location classes
326 * Java Parser Interface:: Instantiating and running the parser
327 * Java Scanner Interface:: Specifying the scanner for the parser
328 * Java Action Features:: Special features for use in actions
329 * Java Differences:: Differences between C/C++ and Java Grammars
330 * Java Declarations Summary:: List of Bison declarations used with Java
331
332 Frequently Asked Questions
333
334 * Memory Exhausted:: Breaking the Stack Limits
335 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
336 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
337 * Implementing Gotos/Loops:: Control Flow in the Calculator
338 * Multiple start-symbols:: Factoring closely related grammars
339 * Secure? Conform?:: Is Bison POSIX safe?
340 * I can't build Bison:: Troubleshooting
341 * Where can I find help?:: Troubleshouting
342 * Bug Reports:: Troublereporting
343 * More Languages:: Parsers in C++, Java, and so on
344 * Beta Testing:: Experimenting development versions
345 * Mailing Lists:: Meeting other Bison users
346
347 Copying This Manual
348
349 * Copying This Manual:: License for copying this manual.
350
351 @end detailmenu
352 @end menu
353
354 @node Introduction
355 @unnumbered Introduction
356 @cindex introduction
357
358 @dfn{Bison} is a general-purpose parser generator that converts an
359 annotated context-free grammar into a deterministic LR or generalized
360 LR (GLR) parser employing LALR(1) parser tables. As an experimental
361 feature, Bison can also generate IELR(1) or canonical LR(1) parser
362 tables. Once you are proficient with Bison, you can use it to develop
363 a wide range of language parsers, from those used in simple desk
364 calculators to complex programming languages.
365
366 Bison is upward compatible with Yacc: all properly-written Yacc
367 grammars ought to work with Bison with no change. Anyone familiar
368 with Yacc should be able to use Bison with little trouble. You need
369 to be fluent in C or C++ programming in order to use Bison or to
370 understand this manual. Java is also supported as an experimental
371 feature.
372
373 We begin with tutorial chapters that explain the basic concepts of
374 using Bison and show three explained examples, each building on the
375 last. If you don't know Bison or Yacc, start by reading these
376 chapters. Reference chapters follow, which describe specific aspects
377 of Bison in detail.
378
379 Bison was written originally by Robert Corbett. Richard Stallman made
380 it Yacc-compatible. Wilfred Hansen of Carnegie Mellon University
381 added multi-character string literals and other features. Since then,
382 Bison has grown more robust and evolved many other new features thanks
383 to the hard work of a long list of volunteers. For details, see the
384 @file{THANKS} and @file{ChangeLog} files included in the Bison
385 distribution.
386
387 This edition corresponds to version @value{VERSION} of Bison.
388
389 @node Conditions
390 @unnumbered Conditions for Using Bison
391
392 The distribution terms for Bison-generated parsers permit using the
393 parsers in nonfree programs. Before Bison version 2.2, these extra
394 permissions applied only when Bison was generating LALR(1)
395 parsers in C@. And before Bison version 1.24, Bison-generated
396 parsers could be used only in programs that were free software.
397
398 The other GNU programming tools, such as the GNU C
399 compiler, have never
400 had such a requirement. They could always be used for nonfree
401 software. The reason Bison was different was not due to a special
402 policy decision; it resulted from applying the usual General Public
403 License to all of the Bison source code.
404
405 The main output of the Bison utility---the Bison parser implementation
406 file---contains a verbatim copy of a sizable piece of Bison, which is
407 the code for the parser's implementation. (The actions from your
408 grammar are inserted into this implementation at one point, but most
409 of the rest of the implementation is not changed.) When we applied
410 the GPL terms to the skeleton code for the parser's implementation,
411 the effect was to restrict the use of Bison output to free software.
412
413 We didn't change the terms because of sympathy for people who want to
414 make software proprietary. @strong{Software should be free.} But we
415 concluded that limiting Bison's use to free software was doing little to
416 encourage people to make other software free. So we decided to make the
417 practical conditions for using Bison match the practical conditions for
418 using the other GNU tools.
419
420 This exception applies when Bison is generating code for a parser.
421 You can tell whether the exception applies to a Bison output file by
422 inspecting the file for text beginning with ``As a special
423 exception@dots{}''. The text spells out the exact terms of the
424 exception.
425
426 @node Copying
427 @unnumbered GNU GENERAL PUBLIC LICENSE
428 @include gpl-3.0.texi
429
430 @node Concepts
431 @chapter The Concepts of Bison
432
433 This chapter introduces many of the basic concepts without which the
434 details of Bison will not make sense. If you do not already know how to
435 use Bison or Yacc, we suggest you start by reading this chapter carefully.
436
437 @menu
438 * Language and Grammar:: Languages and context-free grammars,
439 as mathematical ideas.
440 * Grammar in Bison:: How we represent grammars for Bison's sake.
441 * Semantic Values:: Each token or syntactic grouping can have
442 a semantic value (the value of an integer,
443 the name of an identifier, etc.).
444 * Semantic Actions:: Each rule can have an action containing C code.
445 * GLR Parsers:: Writing parsers for general context-free languages.
446 * Locations Overview:: Tracking Locations.
447 * Bison Parser:: What are Bison's input and output,
448 how is the output used?
449 * Stages:: Stages in writing and running Bison grammars.
450 * Grammar Layout:: Overall structure of a Bison grammar file.
451 @end menu
452
453 @node Language and Grammar
454 @section Languages and Context-Free Grammars
455
456 @cindex context-free grammar
457 @cindex grammar, context-free
458 In order for Bison to parse a language, it must be described by a
459 @dfn{context-free grammar}. This means that you specify one or more
460 @dfn{syntactic groupings} and give rules for constructing them from their
461 parts. For example, in the C language, one kind of grouping is called an
462 `expression'. One rule for making an expression might be, ``An expression
463 can be made of a minus sign and another expression''. Another would be,
464 ``An expression can be an integer''. As you can see, rules are often
465 recursive, but there must be at least one rule which leads out of the
466 recursion.
467
468 @cindex BNF
469 @cindex Backus-Naur form
470 The most common formal system for presenting such rules for humans to read
471 is @dfn{Backus-Naur Form} or ``BNF'', which was developed in
472 order to specify the language Algol 60. Any grammar expressed in
473 BNF is a context-free grammar. The input to Bison is
474 essentially machine-readable BNF.
475
476 @cindex LALR(1) grammars
477 @cindex IELR(1) grammars
478 @cindex LR(1) grammars
479 There are various important subclasses of context-free grammars.
480 Although it can handle almost all context-free grammars, Bison is
481 optimized for what are called LR(1) grammars.
482 In brief, in these grammars, it must be possible to tell how to parse
483 any portion of an input string with just a single token of lookahead.
484 For historical reasons, Bison by default is limited by the additional
485 restrictions of LALR(1), which is hard to explain simply.
486 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}, for
487 more information on this.
488 As an experimental feature, you can escape these additional restrictions by
489 requesting IELR(1) or canonical LR(1) parser tables.
490 @xref{%define Summary,,lr.type}, to learn how.
491
492 @cindex GLR parsing
493 @cindex generalized LR (GLR) parsing
494 @cindex ambiguous grammars
495 @cindex nondeterministic parsing
496
497 Parsers for LR(1) grammars are @dfn{deterministic}, meaning
498 roughly that the next grammar rule to apply at any point in the input is
499 uniquely determined by the preceding input and a fixed, finite portion
500 (called a @dfn{lookahead}) of the remaining input. A context-free
501 grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
502 apply the grammar rules to get the same inputs. Even unambiguous
503 grammars can be @dfn{nondeterministic}, meaning that no fixed
504 lookahead always suffices to determine the next grammar rule to apply.
505 With the proper declarations, Bison is also able to parse these more
506 general context-free grammars, using a technique known as GLR
507 parsing (for Generalized LR). Bison's GLR parsers
508 are able to handle any context-free grammar for which the number of
509 possible parses of any given string is finite.
510
511 @cindex symbols (abstract)
512 @cindex token
513 @cindex syntactic grouping
514 @cindex grouping, syntactic
515 In the formal grammatical rules for a language, each kind of syntactic
516 unit or grouping is named by a @dfn{symbol}. Those which are built by
517 grouping smaller constructs according to grammatical rules are called
518 @dfn{nonterminal symbols}; those which can't be subdivided are called
519 @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
520 corresponding to a single terminal symbol a @dfn{token}, and a piece
521 corresponding to a single nonterminal symbol a @dfn{grouping}.
522
523 We can use the C language as an example of what symbols, terminal and
524 nonterminal, mean. The tokens of C are identifiers, constants (numeric
525 and string), and the various keywords, arithmetic operators and
526 punctuation marks. So the terminal symbols of a grammar for C include
527 `identifier', `number', `string', plus one symbol for each keyword,
528 operator or punctuation mark: `if', `return', `const', `static', `int',
529 `char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
530 (These tokens can be subdivided into characters, but that is a matter of
531 lexicography, not grammar.)
532
533 Here is a simple C function subdivided into tokens:
534
535 @ifinfo
536 @example
537 int /* @r{keyword `int'} */
538 square (int x) /* @r{identifier, open-paren, keyword `int',}
539 @r{identifier, close-paren} */
540 @{ /* @r{open-brace} */
541 return x * x; /* @r{keyword `return', identifier, asterisk,}
542 @r{identifier, semicolon} */
543 @} /* @r{close-brace} */
544 @end example
545 @end ifinfo
546 @ifnotinfo
547 @example
548 int /* @r{keyword `int'} */
549 square (int x) /* @r{identifier, open-paren, keyword `int', identifier, close-paren} */
550 @{ /* @r{open-brace} */
551 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
552 @} /* @r{close-brace} */
553 @end example
554 @end ifnotinfo
555
556 The syntactic groupings of C include the expression, the statement, the
557 declaration, and the function definition. These are represented in the
558 grammar of C by nonterminal symbols `expression', `statement',
559 `declaration' and `function definition'. The full grammar uses dozens of
560 additional language constructs, each with its own nonterminal symbol, in
561 order to express the meanings of these four. The example above is a
562 function definition; it contains one declaration, and one statement. In
563 the statement, each @samp{x} is an expression and so is @samp{x * x}.
564
565 Each nonterminal symbol must have grammatical rules showing how it is made
566 out of simpler constructs. For example, one kind of C statement is the
567 @code{return} statement; this would be described with a grammar rule which
568 reads informally as follows:
569
570 @quotation
571 A `statement' can be made of a `return' keyword, an `expression' and a
572 `semicolon'.
573 @end quotation
574
575 @noindent
576 There would be many other rules for `statement', one for each kind of
577 statement in C.
578
579 @cindex start symbol
580 One nonterminal symbol must be distinguished as the special one which
581 defines a complete utterance in the language. It is called the @dfn{start
582 symbol}. In a compiler, this means a complete input program. In the C
583 language, the nonterminal symbol `sequence of definitions and declarations'
584 plays this role.
585
586 For example, @samp{1 + 2} is a valid C expression---a valid part of a C
587 program---but it is not valid as an @emph{entire} C program. In the
588 context-free grammar of C, this follows from the fact that `expression' is
589 not the start symbol.
590
591 The Bison parser reads a sequence of tokens as its input, and groups the
592 tokens using the grammar rules. If the input is valid, the end result is
593 that the entire token sequence reduces to a single grouping whose symbol is
594 the grammar's start symbol. If we use a grammar for C, the entire input
595 must be a `sequence of definitions and declarations'. If not, the parser
596 reports a syntax error.
597
598 @node Grammar in Bison
599 @section From Formal Rules to Bison Input
600 @cindex Bison grammar
601 @cindex grammar, Bison
602 @cindex formal grammar
603
604 A formal grammar is a mathematical construct. To define the language
605 for Bison, you must write a file expressing the grammar in Bison syntax:
606 a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
607
608 A nonterminal symbol in the formal grammar is represented in Bison input
609 as an identifier, like an identifier in C@. By convention, it should be
610 in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
611
612 The Bison representation for a terminal symbol is also called a @dfn{token
613 type}. Token types as well can be represented as C-like identifiers. By
614 convention, these identifiers should be upper case to distinguish them from
615 nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
616 @code{RETURN}. A terminal symbol that stands for a particular keyword in
617 the language should be named after that keyword converted to upper case.
618 The terminal symbol @code{error} is reserved for error recovery.
619 @xref{Symbols}.
620
621 A terminal symbol can also be represented as a character literal, just like
622 a C character constant. You should do this whenever a token is just a
623 single character (parenthesis, plus-sign, etc.): use that same character in
624 a literal as the terminal symbol for that token.
625
626 A third way to represent a terminal symbol is with a C string constant
627 containing several characters. @xref{Symbols}, for more information.
628
629 The grammar rules also have an expression in Bison syntax. For example,
630 here is the Bison rule for a C @code{return} statement. The semicolon in
631 quotes is a literal character token, representing part of the C syntax for
632 the statement; the naked semicolon, and the colon, are Bison punctuation
633 used in every rule.
634
635 @example
636 stmt: RETURN expr ';'
637 ;
638 @end example
639
640 @noindent
641 @xref{Rules, ,Syntax of Grammar Rules}.
642
643 @node Semantic Values
644 @section Semantic Values
645 @cindex semantic value
646 @cindex value, semantic
647
648 A formal grammar selects tokens only by their classifications: for example,
649 if a rule mentions the terminal symbol `integer constant', it means that
650 @emph{any} integer constant is grammatically valid in that position. The
651 precise value of the constant is irrelevant to how to parse the input: if
652 @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
653 grammatical.
654
655 But the precise value is very important for what the input means once it is
656 parsed. A compiler is useless if it fails to distinguish between 4, 1 and
657 3989 as constants in the program! Therefore, each token in a Bison grammar
658 has both a token type and a @dfn{semantic value}. @xref{Semantics,
659 ,Defining Language Semantics},
660 for details.
661
662 The token type is a terminal symbol defined in the grammar, such as
663 @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
664 you need to know to decide where the token may validly appear and how to
665 group it with other tokens. The grammar rules know nothing about tokens
666 except their types.
667
668 The semantic value has all the rest of the information about the
669 meaning of the token, such as the value of an integer, or the name of an
670 identifier. (A token such as @code{','} which is just punctuation doesn't
671 need to have any semantic value.)
672
673 For example, an input token might be classified as token type
674 @code{INTEGER} and have the semantic value 4. Another input token might
675 have the same token type @code{INTEGER} but value 3989. When a grammar
676 rule says that @code{INTEGER} is allowed, either of these tokens is
677 acceptable because each is an @code{INTEGER}. When the parser accepts the
678 token, it keeps track of the token's semantic value.
679
680 Each grouping can also have a semantic value as well as its nonterminal
681 symbol. For example, in a calculator, an expression typically has a
682 semantic value that is a number. In a compiler for a programming
683 language, an expression typically has a semantic value that is a tree
684 structure describing the meaning of the expression.
685
686 @node Semantic Actions
687 @section Semantic Actions
688 @cindex semantic actions
689 @cindex actions, semantic
690
691 In order to be useful, a program must do more than parse input; it must
692 also produce some output based on the input. In a Bison grammar, a grammar
693 rule can have an @dfn{action} made up of C statements. Each time the
694 parser recognizes a match for that rule, the action is executed.
695 @xref{Actions}.
696
697 Most of the time, the purpose of an action is to compute the semantic value
698 of the whole construct from the semantic values of its parts. For example,
699 suppose we have a rule which says an expression can be the sum of two
700 expressions. When the parser recognizes such a sum, each of the
701 subexpressions has a semantic value which describes how it was built up.
702 The action for this rule should create a similar sort of value for the
703 newly recognized larger expression.
704
705 For example, here is a rule that says an expression can be the sum of
706 two subexpressions:
707
708 @example
709 expr: expr '+' expr @{ $$ = $1 + $3; @}
710 ;
711 @end example
712
713 @noindent
714 The action says how to produce the semantic value of the sum expression
715 from the values of the two subexpressions.
716
717 @node GLR Parsers
718 @section Writing GLR Parsers
719 @cindex GLR parsing
720 @cindex generalized LR (GLR) parsing
721 @findex %glr-parser
722 @cindex conflicts
723 @cindex shift/reduce conflicts
724 @cindex reduce/reduce conflicts
725
726 In some grammars, Bison's deterministic
727 LR(1) parsing algorithm cannot decide whether to apply a
728 certain grammar rule at a given point. That is, it may not be able to
729 decide (on the basis of the input read so far) which of two possible
730 reductions (applications of a grammar rule) applies, or whether to apply
731 a reduction or read more of the input and apply a reduction later in the
732 input. These are known respectively as @dfn{reduce/reduce} conflicts
733 (@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
734 (@pxref{Shift/Reduce}).
735
736 To use a grammar that is not easily modified to be LR(1), a
737 more general parsing algorithm is sometimes necessary. If you include
738 @code{%glr-parser} among the Bison declarations in your file
739 (@pxref{Grammar Outline}), the result is a Generalized LR
740 (GLR) parser. These parsers handle Bison grammars that
741 contain no unresolved conflicts (i.e., after applying precedence
742 declarations) identically to deterministic parsers. However, when
743 faced with unresolved shift/reduce and reduce/reduce conflicts,
744 GLR parsers use the simple expedient of doing both,
745 effectively cloning the parser to follow both possibilities. Each of
746 the resulting parsers can again split, so that at any given time, there
747 can be any number of possible parses being explored. The parsers
748 proceed in lockstep; that is, all of them consume (shift) a given input
749 symbol before any of them proceed to the next. Each of the cloned
750 parsers eventually meets one of two possible fates: either it runs into
751 a parsing error, in which case it simply vanishes, or it merges with
752 another parser, because the two of them have reduced the input to an
753 identical set of symbols.
754
755 During the time that there are multiple parsers, semantic actions are
756 recorded, but not performed. When a parser disappears, its recorded
757 semantic actions disappear as well, and are never performed. When a
758 reduction makes two parsers identical, causing them to merge, Bison
759 records both sets of semantic actions. Whenever the last two parsers
760 merge, reverting to the single-parser case, Bison resolves all the
761 outstanding actions either by precedences given to the grammar rules
762 involved, or by performing both actions, and then calling a designated
763 user-defined function on the resulting values to produce an arbitrary
764 merged result.
765
766 @menu
767 * Simple GLR Parsers:: Using GLR parsers on unambiguous grammars.
768 * Merging GLR Parses:: Using GLR parsers to resolve ambiguities.
769 * GLR Semantic Actions:: Considerations for semantic values and deferred actions.
770 * Semantic Predicates:: Controlling a parse with arbitrary computations.
771 * Compiler Requirements:: GLR parsers require a modern C compiler.
772 @end menu
773
774 @node Simple GLR Parsers
775 @subsection Using GLR on Unambiguous Grammars
776 @cindex GLR parsing, unambiguous grammars
777 @cindex generalized LR (GLR) parsing, unambiguous grammars
778 @findex %glr-parser
779 @findex %expect-rr
780 @cindex conflicts
781 @cindex reduce/reduce conflicts
782 @cindex shift/reduce conflicts
783
784 In the simplest cases, you can use the GLR algorithm
785 to parse grammars that are unambiguous but fail to be LR(1).
786 Such grammars typically require more than one symbol of lookahead.
787
788 Consider a problem that
789 arises in the declaration of enumerated and subrange types in the
790 programming language Pascal. Here are some examples:
791
792 @example
793 type subrange = lo .. hi;
794 type enum = (a, b, c);
795 @end example
796
797 @noindent
798 The original language standard allows only numeric
799 literals and constant identifiers for the subrange bounds (@samp{lo}
800 and @samp{hi}), but Extended Pascal (ISO/IEC
801 10206) and many other
802 Pascal implementations allow arbitrary expressions there. This gives
803 rise to the following situation, containing a superfluous pair of
804 parentheses:
805
806 @example
807 type subrange = (a) .. b;
808 @end example
809
810 @noindent
811 Compare this to the following declaration of an enumerated
812 type with only one value:
813
814 @example
815 type enum = (a);
816 @end example
817
818 @noindent
819 (These declarations are contrived, but they are syntactically
820 valid, and more-complicated cases can come up in practical programs.)
821
822 These two declarations look identical until the @samp{..} token.
823 With normal LR(1) one-token lookahead it is not
824 possible to decide between the two forms when the identifier
825 @samp{a} is parsed. It is, however, desirable
826 for a parser to decide this, since in the latter case
827 @samp{a} must become a new identifier to represent the enumeration
828 value, while in the former case @samp{a} must be evaluated with its
829 current meaning, which may be a constant or even a function call.
830
831 You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
832 to be resolved later, but this typically requires substantial
833 contortions in both semantic actions and large parts of the
834 grammar, where the parentheses are nested in the recursive rules for
835 expressions.
836
837 You might think of using the lexer to distinguish between the two
838 forms by returning different tokens for currently defined and
839 undefined identifiers. But if these declarations occur in a local
840 scope, and @samp{a} is defined in an outer scope, then both forms
841 are possible---either locally redefining @samp{a}, or using the
842 value of @samp{a} from the outer scope. So this approach cannot
843 work.
844
845 A simple solution to this problem is to declare the parser to
846 use the GLR algorithm.
847 When the GLR parser reaches the critical state, it
848 merely splits into two branches and pursues both syntax rules
849 simultaneously. Sooner or later, one of them runs into a parsing
850 error. If there is a @samp{..} token before the next
851 @samp{;}, the rule for enumerated types fails since it cannot
852 accept @samp{..} anywhere; otherwise, the subrange type rule
853 fails since it requires a @samp{..} token. So one of the branches
854 fails silently, and the other one continues normally, performing
855 all the intermediate actions that were postponed during the split.
856
857 If the input is syntactically incorrect, both branches fail and the parser
858 reports a syntax error as usual.
859
860 The effect of all this is that the parser seems to ``guess'' the
861 correct branch to take, or in other words, it seems to use more
862 lookahead than the underlying LR(1) algorithm actually allows
863 for. In this example, LR(2) would suffice, but also some cases
864 that are not LR(@math{k}) for any @math{k} can be handled this way.
865
866 In general, a GLR parser can take quadratic or cubic worst-case time,
867 and the current Bison parser even takes exponential time and space
868 for some grammars. In practice, this rarely happens, and for many
869 grammars it is possible to prove that it cannot happen.
870 The present example contains only one conflict between two
871 rules, and the type-declaration context containing the conflict
872 cannot be nested. So the number of
873 branches that can exist at any time is limited by the constant 2,
874 and the parsing time is still linear.
875
876 Here is a Bison grammar corresponding to the example above. It
877 parses a vastly simplified form of Pascal type declarations.
878
879 @example
880 %token TYPE DOTDOT ID
881
882 @group
883 %left '+' '-'
884 %left '*' '/'
885 @end group
886
887 %%
888
889 @group
890 type_decl : TYPE ID '=' type ';'
891 ;
892 @end group
893
894 @group
895 type : '(' id_list ')'
896 | expr DOTDOT expr
897 ;
898 @end group
899
900 @group
901 id_list : ID
902 | id_list ',' ID
903 ;
904 @end group
905
906 @group
907 expr : '(' expr ')'
908 | expr '+' expr
909 | expr '-' expr
910 | expr '*' expr
911 | expr '/' expr
912 | ID
913 ;
914 @end group
915 @end example
916
917 When used as a normal LR(1) grammar, Bison correctly complains
918 about one reduce/reduce conflict. In the conflicting situation the
919 parser chooses one of the alternatives, arbitrarily the one
920 declared first. Therefore the following correct input is not
921 recognized:
922
923 @example
924 type t = (a) .. b;
925 @end example
926
927 The parser can be turned into a GLR parser, while also telling Bison
928 to be silent about the one known reduce/reduce conflict, by adding
929 these two declarations to the Bison grammar file (before the first
930 @samp{%%}):
931
932 @example
933 %glr-parser
934 %expect-rr 1
935 @end example
936
937 @noindent
938 No change in the grammar itself is required. Now the
939 parser recognizes all valid declarations, according to the
940 limited syntax above, transparently. In fact, the user does not even
941 notice when the parser splits.
942
943 So here we have a case where we can use the benefits of GLR,
944 almost without disadvantages. Even in simple cases like this, however,
945 there are at least two potential problems to beware. First, always
946 analyze the conflicts reported by Bison to make sure that GLR
947 splitting is only done where it is intended. A GLR parser
948 splitting inadvertently may cause problems less obvious than an
949 LR parser statically choosing the wrong alternative in a
950 conflict. Second, consider interactions with the lexer (@pxref{Semantic
951 Tokens}) with great care. Since a split parser consumes tokens without
952 performing any actions during the split, the lexer cannot obtain
953 information via parser actions. Some cases of lexer interactions can be
954 eliminated by using GLR to shift the complications from the
955 lexer to the parser. You must check the remaining cases for
956 correctness.
957
958 In our example, it would be safe for the lexer to return tokens based on
959 their current meanings in some symbol table, because no new symbols are
960 defined in the middle of a type declaration. Though it is possible for
961 a parser to define the enumeration constants as they are parsed, before
962 the type declaration is completed, it actually makes no difference since
963 they cannot be used within the same enumerated type declaration.
964
965 @node Merging GLR Parses
966 @subsection Using GLR to Resolve Ambiguities
967 @cindex GLR parsing, ambiguous grammars
968 @cindex generalized LR (GLR) parsing, ambiguous grammars
969 @findex %dprec
970 @findex %merge
971 @cindex conflicts
972 @cindex reduce/reduce conflicts
973
974 Let's consider an example, vastly simplified from a C++ grammar.
975
976 @example
977 %@{
978 #include <stdio.h>
979 #define YYSTYPE char const *
980 int yylex (void);
981 void yyerror (char const *);
982 %@}
983
984 %token TYPENAME ID
985
986 %right '='
987 %left '+'
988
989 %glr-parser
990
991 %%
992
993 prog :
994 | prog stmt @{ printf ("\n"); @}
995 ;
996
997 stmt : expr ';' %dprec 1
998 | decl %dprec 2
999 ;
1000
1001 expr : ID @{ printf ("%s ", $$); @}
1002 | TYPENAME '(' expr ')'
1003 @{ printf ("%s <cast> ", $1); @}
1004 | expr '+' expr @{ printf ("+ "); @}
1005 | expr '=' expr @{ printf ("= "); @}
1006 ;
1007
1008 decl : TYPENAME declarator ';'
1009 @{ printf ("%s <declare> ", $1); @}
1010 | TYPENAME declarator '=' expr ';'
1011 @{ printf ("%s <init-declare> ", $1); @}
1012 ;
1013
1014 declarator : ID @{ printf ("\"%s\" ", $1); @}
1015 | '(' declarator ')'
1016 ;
1017 @end example
1018
1019 @noindent
1020 This models a problematic part of the C++ grammar---the ambiguity between
1021 certain declarations and statements. For example,
1022
1023 @example
1024 T (x) = y+z;
1025 @end example
1026
1027 @noindent
1028 parses as either an @code{expr} or a @code{stmt}
1029 (assuming that @samp{T} is recognized as a @code{TYPENAME} and
1030 @samp{x} as an @code{ID}).
1031 Bison detects this as a reduce/reduce conflict between the rules
1032 @code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
1033 time it encounters @code{x} in the example above. Since this is a
1034 GLR parser, it therefore splits the problem into two parses, one for
1035 each choice of resolving the reduce/reduce conflict.
1036 Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1037 however, neither of these parses ``dies,'' because the grammar as it stands is
1038 ambiguous. One of the parsers eventually reduces @code{stmt : expr ';'} and
1039 the other reduces @code{stmt : decl}, after which both parsers are in an
1040 identical state: they've seen @samp{prog stmt} and have the same unprocessed
1041 input remaining. We say that these parses have @dfn{merged.}
1042
1043 At this point, the GLR parser requires a specification in the
1044 grammar of how to choose between the competing parses.
1045 In the example above, the two @code{%dprec}
1046 declarations specify that Bison is to give precedence
1047 to the parse that interprets the example as a
1048 @code{decl}, which implies that @code{x} is a declarator.
1049 The parser therefore prints
1050
1051 @example
1052 "x" y z + T <init-declare>
1053 @end example
1054
1055 The @code{%dprec} declarations only come into play when more than one
1056 parse survives. Consider a different input string for this parser:
1057
1058 @example
1059 T (x) + y;
1060 @end example
1061
1062 @noindent
1063 This is another example of using GLR to parse an unambiguous
1064 construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
1065 Here, there is no ambiguity (this cannot be parsed as a declaration).
1066 However, at the time the Bison parser encounters @code{x}, it does not
1067 have enough information to resolve the reduce/reduce conflict (again,
1068 between @code{x} as an @code{expr} or a @code{declarator}). In this
1069 case, no precedence declaration is used. Again, the parser splits
1070 into two, one assuming that @code{x} is an @code{expr}, and the other
1071 assuming @code{x} is a @code{declarator}. The second of these parsers
1072 then vanishes when it sees @code{+}, and the parser prints
1073
1074 @example
1075 x T <cast> y +
1076 @end example
1077
1078 Suppose that instead of resolving the ambiguity, you wanted to see all
1079 the possibilities. For this purpose, you must merge the semantic
1080 actions of the two possible parsers, rather than choosing one over the
1081 other. To do so, you could change the declaration of @code{stmt} as
1082 follows:
1083
1084 @example
1085 stmt : expr ';' %merge <stmtMerge>
1086 | decl %merge <stmtMerge>
1087 ;
1088 @end example
1089
1090 @noindent
1091 and define the @code{stmtMerge} function as:
1092
1093 @example
1094 static YYSTYPE
1095 stmtMerge (YYSTYPE x0, YYSTYPE x1)
1096 @{
1097 printf ("<OR> ");
1098 return "";
1099 @}
1100 @end example
1101
1102 @noindent
1103 with an accompanying forward declaration
1104 in the C declarations at the beginning of the file:
1105
1106 @example
1107 %@{
1108 #define YYSTYPE char const *
1109 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
1110 %@}
1111 @end example
1112
1113 @noindent
1114 With these declarations, the resulting parser parses the first example
1115 as both an @code{expr} and a @code{decl}, and prints
1116
1117 @example
1118 "x" y z + T <init-declare> x T <cast> y z + = <OR>
1119 @end example
1120
1121 Bison requires that all of the
1122 productions that participate in any particular merge have identical
1123 @samp{%merge} clauses. Otherwise, the ambiguity would be unresolvable,
1124 and the parser will report an error during any parse that results in
1125 the offending merge.
1126
1127 @node GLR Semantic Actions
1128 @subsection GLR Semantic Actions
1129
1130 The nature of GLR parsing and the structure of the generated
1131 parsers give rise to certain restrictions on semantic values and actions.
1132
1133 @subsubsection Deferred semantic actions
1134 @cindex deferred semantic actions
1135 By definition, a deferred semantic action is not performed at the same time as
1136 the associated reduction.
1137 This raises caveats for several Bison features you might use in a semantic
1138 action in a GLR parser.
1139
1140 @vindex yychar
1141 @cindex GLR parsers and @code{yychar}
1142 @vindex yylval
1143 @cindex GLR parsers and @code{yylval}
1144 @vindex yylloc
1145 @cindex GLR parsers and @code{yylloc}
1146 In any semantic action, you can examine @code{yychar} to determine the type of
1147 the lookahead token present at the time of the associated reduction.
1148 After checking that @code{yychar} is not set to @code{YYEMPTY} or @code{YYEOF},
1149 you can then examine @code{yylval} and @code{yylloc} to determine the
1150 lookahead token's semantic value and location, if any.
1151 In a nondeferred semantic action, you can also modify any of these variables to
1152 influence syntax analysis.
1153 @xref{Lookahead, ,Lookahead Tokens}.
1154
1155 @findex yyclearin
1156 @cindex GLR parsers and @code{yyclearin}
1157 In a deferred semantic action, it's too late to influence syntax analysis.
1158 In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1159 shallow copies of the values they had at the time of the associated reduction.
1160 For this reason alone, modifying them is dangerous.
1161 Moreover, the result of modifying them is undefined and subject to change with
1162 future versions of Bison.
1163 For example, if a semantic action might be deferred, you should never write it
1164 to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1165 memory referenced by @code{yylval}.
1166
1167 @subsubsection YYERROR
1168 @findex YYERROR
1169 @cindex GLR parsers and @code{YYERROR}
1170 Another Bison feature requiring special consideration is @code{YYERROR}
1171 (@pxref{Action Features}), which you can invoke in a semantic action to
1172 initiate error recovery.
1173 During deterministic GLR operation, the effect of @code{YYERROR} is
1174 the same as its effect in a deterministic parser.
1175 The effect in a deferred action is similar, but the precise point of the
1176 error is undefined; instead, the parser reverts to deterministic operation,
1177 selecting an unspecified stack on which to continue with a syntax error.
1178 In a semantic predicate (see @ref{Semantic Predicates}) during nondeterministic
1179 parsing, @code{YYERROR} silently prunes
1180 the parse that invoked the test.
1181
1182 @subsubsection Restrictions on semantic values and locations
1183 GLR parsers require that you use POD (Plain Old Data) types for
1184 semantic values and location types when using the generated parsers as
1185 C++ code.
1186
1187 @node Semantic Predicates
1188 @subsection Controlling a Parse with Arbitrary Predicates
1189 @findex %?
1190 @cindex Semantic predicates in GLR parsers
1191
1192 In addition to the @code{%dprec} and @code{%merge} directives,
1193 GLR parsers
1194 allow you to reject parses on the basis of arbitrary computations executed
1195 in user code, without having Bison treat this rejection as an error
1196 if there are alternative parses. (This feature is experimental and may
1197 evolve. We welcome user feedback.) For example,
1198
1199 @smallexample
1200 widget :
1201 %?@{ new_syntax @} "widget" id new_args @{ $$ = f($3, $4); @}
1202 | %?@{ !new_syntax @} "widget" id old_args @{ $$ = f($3, $4); @}
1203 ;
1204 @end smallexample
1205
1206 @noindent
1207 is one way to allow the same parser to handle two different syntaxes for
1208 widgets. The clause preceded by @code{%?} is treated like an ordinary
1209 action, except that its text is treated as an expression and is always
1210 evaluated immediately (even when in nondeterministic mode). If the
1211 expression yields 0 (false), the clause is treated as a syntax error,
1212 which, in a nondeterministic parser, causes the stack in which it is reduced
1213 to die. In a deterministic parser, it acts like YYERROR.
1214
1215 As the example shows, predicates otherwise look like semantic actions, and
1216 therefore you must be take them into account when determining the numbers
1217 to use for denoting the semantic values of right-hand side symbols.
1218 Predicate actions, however, have no defined value, and may not be given
1219 labels.
1220
1221 There is a subtle difference between semantic predicates and ordinary
1222 actions in nondeterministic mode, since the latter are deferred.
1223 For example, we could try to rewrite the previous example as
1224
1225 @smallexample
1226 widget :
1227 @{ if (!new_syntax) YYERROR; @} "widget" id new_args @{ $$ = f($3, $4); @}
1228 | @{ if (new_syntax) YYERROR; @} "widget" id old_args @{ $$ = f($3, $4); @}
1229 ;
1230 @end smallexample
1231
1232 @noindent
1233 (reversing the sense of the predicate tests to cause an error when they are
1234 false). However, this
1235 does @emph{not} have the same effect if @code{new_args} and @code{old_args}
1236 have overlapping syntax.
1237 Since the mid-rule actions testing @code{new_syntax} are deferred,
1238 a GLR parser first encounters the unresolved ambiguous reduction
1239 for cases where @code{new_args} and @code{old_args} recognize the same string
1240 @emph{before} performing the tests of @code{new_syntax}. It therefore
1241 reports an error.
1242
1243 Finally, be careful in writing predicates: deferred actions have not been
1244 evaluated, so that using them in a predicate will have undefined effects.
1245
1246 @node Compiler Requirements
1247 @subsection Considerations when Compiling GLR Parsers
1248 @cindex @code{inline}
1249 @cindex GLR parsers and @code{inline}
1250
1251 The GLR parsers require a compiler for ISO C89 or
1252 later. In addition, they use the @code{inline} keyword, which is not
1253 C89, but is C99 and is a common extension in pre-C99 compilers. It is
1254 up to the user of these parsers to handle
1255 portability issues. For instance, if using Autoconf and the Autoconf
1256 macro @code{AC_C_INLINE}, a mere
1257
1258 @example
1259 %@{
1260 #include <config.h>
1261 %@}
1262 @end example
1263
1264 @noindent
1265 will suffice. Otherwise, we suggest
1266
1267 @example
1268 %@{
1269 #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
1270 #define inline
1271 #endif
1272 %@}
1273 @end example
1274
1275 @node Locations Overview
1276 @section Locations
1277 @cindex location
1278 @cindex textual location
1279 @cindex location, textual
1280
1281 Many applications, like interpreters or compilers, have to produce verbose
1282 and useful error messages. To achieve this, one must be able to keep track of
1283 the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
1284 Bison provides a mechanism for handling these locations.
1285
1286 Each token has a semantic value. In a similar fashion, each token has an
1287 associated location, but the type of locations is the same for all tokens and
1288 groupings. Moreover, the output parser is equipped with a default data
1289 structure for storing locations (@pxref{Locations}, for more details).
1290
1291 Like semantic values, locations can be reached in actions using a dedicated
1292 set of constructs. In the example above, the location of the whole grouping
1293 is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1294 @code{@@3}.
1295
1296 When a rule is matched, a default action is used to compute the semantic value
1297 of its left hand side (@pxref{Actions}). In the same way, another default
1298 action is used for locations. However, the action for locations is general
1299 enough for most cases, meaning there is usually no need to describe for each
1300 rule how @code{@@$} should be formed. When building a new location for a given
1301 grouping, the default behavior of the output parser is to take the beginning
1302 of the first symbol, and the end of the last symbol.
1303
1304 @node Bison Parser
1305 @section Bison Output: the Parser Implementation File
1306 @cindex Bison parser
1307 @cindex Bison utility
1308 @cindex lexical analyzer, purpose
1309 @cindex parser
1310
1311 When you run Bison, you give it a Bison grammar file as input. The
1312 most important output is a C source file that implements a parser for
1313 the language described by the grammar. This parser is called a
1314 @dfn{Bison parser}, and this file is called a @dfn{Bison parser
1315 implementation file}. Keep in mind that the Bison utility and the
1316 Bison parser are two distinct programs: the Bison utility is a program
1317 whose output is the Bison parser implementation file that becomes part
1318 of your program.
1319
1320 The job of the Bison parser is to group tokens into groupings according to
1321 the grammar rules---for example, to build identifiers and operators into
1322 expressions. As it does this, it runs the actions for the grammar rules it
1323 uses.
1324
1325 The tokens come from a function called the @dfn{lexical analyzer} that
1326 you must supply in some fashion (such as by writing it in C). The Bison
1327 parser calls the lexical analyzer each time it wants a new token. It
1328 doesn't know what is ``inside'' the tokens (though their semantic values
1329 may reflect this). Typically the lexical analyzer makes the tokens by
1330 parsing characters of text, but Bison does not depend on this.
1331 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
1332
1333 The Bison parser implementation file is C code which defines a
1334 function named @code{yyparse} which implements that grammar. This
1335 function does not make a complete C program: you must supply some
1336 additional functions. One is the lexical analyzer. Another is an
1337 error-reporting function which the parser calls to report an error.
1338 In addition, a complete C program must start with a function called
1339 @code{main}; you have to provide this, and arrange for it to call
1340 @code{yyparse} or the parser will never run. @xref{Interface, ,Parser
1341 C-Language Interface}.
1342
1343 Aside from the token type names and the symbols in the actions you
1344 write, all symbols defined in the Bison parser implementation file
1345 itself begin with @samp{yy} or @samp{YY}. This includes interface
1346 functions such as the lexical analyzer function @code{yylex}, the
1347 error reporting function @code{yyerror} and the parser function
1348 @code{yyparse} itself. This also includes numerous identifiers used
1349 for internal purposes. Therefore, you should avoid using C
1350 identifiers starting with @samp{yy} or @samp{YY} in the Bison grammar
1351 file except for the ones defined in this manual. Also, you should
1352 avoid using the C identifiers @samp{malloc} and @samp{free} for
1353 anything other than their usual meanings.
1354
1355 In some cases the Bison parser implementation file includes system
1356 headers, and in those cases your code should respect the identifiers
1357 reserved by those headers. On some non-GNU hosts, @code{<alloca.h>},
1358 @code{<malloc.h>}, @code{<stddef.h>}, and @code{<stdlib.h>} are
1359 included as needed to declare memory allocators and related types.
1360 @code{<libintl.h>} is included if message translation is in use
1361 (@pxref{Internationalization}). Other system headers may be included
1362 if you define @code{YYDEBUG} to a nonzero value (@pxref{Tracing,
1363 ,Tracing Your Parser}).
1364
1365 @node Stages
1366 @section Stages in Using Bison
1367 @cindex stages in using Bison
1368 @cindex using Bison
1369
1370 The actual language-design process using Bison, from grammar specification
1371 to a working compiler or interpreter, has these parts:
1372
1373 @enumerate
1374 @item
1375 Formally specify the grammar in a form recognized by Bison
1376 (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
1377 in the language, describe the action that is to be taken when an
1378 instance of that rule is recognized. The action is described by a
1379 sequence of C statements.
1380
1381 @item
1382 Write a lexical analyzer to process input and pass tokens to the parser.
1383 The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
1384 Lexical Analyzer Function @code{yylex}}). It could also be produced
1385 using Lex, but the use of Lex is not discussed in this manual.
1386
1387 @item
1388 Write a controlling function that calls the Bison-produced parser.
1389
1390 @item
1391 Write error-reporting routines.
1392 @end enumerate
1393
1394 To turn this source code as written into a runnable program, you
1395 must follow these steps:
1396
1397 @enumerate
1398 @item
1399 Run Bison on the grammar to produce the parser.
1400
1401 @item
1402 Compile the code output by Bison, as well as any other source files.
1403
1404 @item
1405 Link the object files to produce the finished product.
1406 @end enumerate
1407
1408 @node Grammar Layout
1409 @section The Overall Layout of a Bison Grammar
1410 @cindex grammar file
1411 @cindex file format
1412 @cindex format of grammar file
1413 @cindex layout of Bison grammar
1414
1415 The input file for the Bison utility is a @dfn{Bison grammar file}. The
1416 general form of a Bison grammar file is as follows:
1417
1418 @example
1419 %@{
1420 @var{Prologue}
1421 %@}
1422
1423 @var{Bison declarations}
1424
1425 %%
1426 @var{Grammar rules}
1427 %%
1428 @var{Epilogue}
1429 @end example
1430
1431 @noindent
1432 The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1433 in every Bison grammar file to separate the sections.
1434
1435 The prologue may define types and variables used in the actions. You can
1436 also use preprocessor commands to define macros used there, and use
1437 @code{#include} to include header files that do any of these things.
1438 You need to declare the lexical analyzer @code{yylex} and the error
1439 printer @code{yyerror} here, along with any other global identifiers
1440 used by the actions in the grammar rules.
1441
1442 The Bison declarations declare the names of the terminal and nonterminal
1443 symbols, and may also describe operator precedence and the data types of
1444 semantic values of various symbols.
1445
1446 The grammar rules define how to construct each nonterminal symbol from its
1447 parts.
1448
1449 The epilogue can contain any code you want to use. Often the
1450 definitions of functions declared in the prologue go here. In a
1451 simple program, all the rest of the program can go here.
1452
1453 @node Examples
1454 @chapter Examples
1455 @cindex simple examples
1456 @cindex examples, simple
1457
1458 Now we show and explain three sample programs written using Bison: a
1459 reverse polish notation calculator, an algebraic (infix) notation
1460 calculator, and a multi-function calculator. All three have been tested
1461 under BSD Unix 4.3; each produces a usable, though limited, interactive
1462 desk-top calculator.
1463
1464 These examples are simple, but Bison grammars for real programming
1465 languages are written the same way. You can copy these examples into a
1466 source file to try them.
1467
1468 @menu
1469 * RPN Calc:: Reverse polish notation calculator;
1470 a first example with no operator precedence.
1471 * Infix Calc:: Infix (algebraic) notation calculator.
1472 Operator precedence is introduced.
1473 * Simple Error Recovery:: Continuing after syntax errors.
1474 * Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
1475 * Multi-function Calc:: Calculator with memory and trig functions.
1476 It uses multiple data-types for semantic values.
1477 * Exercises:: Ideas for improving the multi-function calculator.
1478 @end menu
1479
1480 @node RPN Calc
1481 @section Reverse Polish Notation Calculator
1482 @cindex reverse polish notation
1483 @cindex polish notation calculator
1484 @cindex @code{rpcalc}
1485 @cindex calculator, simple
1486
1487 The first example is that of a simple double-precision @dfn{reverse polish
1488 notation} calculator (a calculator using postfix operators). This example
1489 provides a good starting point, since operator precedence is not an issue.
1490 The second example will illustrate how operator precedence is handled.
1491
1492 The source code for this calculator is named @file{rpcalc.y}. The
1493 @samp{.y} extension is a convention used for Bison grammar files.
1494
1495 @menu
1496 * Rpcalc Declarations:: Prologue (declarations) for rpcalc.
1497 * Rpcalc Rules:: Grammar Rules for rpcalc, with explanation.
1498 * Rpcalc Lexer:: The lexical analyzer.
1499 * Rpcalc Main:: The controlling function.
1500 * Rpcalc Error:: The error reporting function.
1501 * Rpcalc Generate:: Running Bison on the grammar file.
1502 * Rpcalc Compile:: Run the C compiler on the output code.
1503 @end menu
1504
1505 @node Rpcalc Declarations
1506 @subsection Declarations for @code{rpcalc}
1507
1508 Here are the C and Bison declarations for the reverse polish notation
1509 calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1510
1511 @example
1512 /* Reverse polish notation calculator. */
1513
1514 %@{
1515 #define YYSTYPE double
1516 #include <math.h>
1517 int yylex (void);
1518 void yyerror (char const *);
1519 %@}
1520
1521 %token NUM
1522
1523 %% /* Grammar rules and actions follow. */
1524 @end example
1525
1526 The declarations section (@pxref{Prologue, , The prologue}) contains two
1527 preprocessor directives and two forward declarations.
1528
1529 The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1530 specifying the C data type for semantic values of both tokens and
1531 groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1532 Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1533 don't define it, @code{int} is the default. Because we specify
1534 @code{double}, each token and each expression has an associated value,
1535 which is a floating point number.
1536
1537 The @code{#include} directive is used to declare the exponentiation
1538 function @code{pow}.
1539
1540 The forward declarations for @code{yylex} and @code{yyerror} are
1541 needed because the C language requires that functions be declared
1542 before they are used. These functions will be defined in the
1543 epilogue, but the parser calls them so they must be declared in the
1544 prologue.
1545
1546 The second section, Bison declarations, provides information to Bison
1547 about the token types (@pxref{Bison Declarations, ,The Bison
1548 Declarations Section}). Each terminal symbol that is not a
1549 single-character literal must be declared here. (Single-character
1550 literals normally don't need to be declared.) In this example, all the
1551 arithmetic operators are designated by single-character literals, so the
1552 only terminal symbol that needs to be declared is @code{NUM}, the token
1553 type for numeric constants.
1554
1555 @node Rpcalc Rules
1556 @subsection Grammar Rules for @code{rpcalc}
1557
1558 Here are the grammar rules for the reverse polish notation calculator.
1559
1560 @example
1561 input: /* empty */
1562 | input line
1563 ;
1564
1565 line: '\n'
1566 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1567 ;
1568
1569 exp: NUM @{ $$ = $1; @}
1570 | exp exp '+' @{ $$ = $1 + $2; @}
1571 | exp exp '-' @{ $$ = $1 - $2; @}
1572 | exp exp '*' @{ $$ = $1 * $2; @}
1573 | exp exp '/' @{ $$ = $1 / $2; @}
1574 /* Exponentiation */
1575 | exp exp '^' @{ $$ = pow ($1, $2); @}
1576 /* Unary minus */
1577 | exp 'n' @{ $$ = -$1; @}
1578 ;
1579 %%
1580 @end example
1581
1582 The groupings of the rpcalc ``language'' defined here are the expression
1583 (given the name @code{exp}), the line of input (@code{line}), and the
1584 complete input transcript (@code{input}). Each of these nonterminal
1585 symbols has several alternate rules, joined by the vertical bar @samp{|}
1586 which is read as ``or''. The following sections explain what these rules
1587 mean.
1588
1589 The semantics of the language is determined by the actions taken when a
1590 grouping is recognized. The actions are the C code that appears inside
1591 braces. @xref{Actions}.
1592
1593 You must specify these actions in C, but Bison provides the means for
1594 passing semantic values between the rules. In each action, the
1595 pseudo-variable @code{$$} stands for the semantic value for the grouping
1596 that the rule is going to construct. Assigning a value to @code{$$} is the
1597 main job of most actions. The semantic values of the components of the
1598 rule are referred to as @code{$1}, @code{$2}, and so on.
1599
1600 @menu
1601 * Rpcalc Input::
1602 * Rpcalc Line::
1603 * Rpcalc Expr::
1604 @end menu
1605
1606 @node Rpcalc Input
1607 @subsubsection Explanation of @code{input}
1608
1609 Consider the definition of @code{input}:
1610
1611 @example
1612 input: /* empty */
1613 | input line
1614 ;
1615 @end example
1616
1617 This definition reads as follows: ``A complete input is either an empty
1618 string, or a complete input followed by an input line''. Notice that
1619 ``complete input'' is defined in terms of itself. This definition is said
1620 to be @dfn{left recursive} since @code{input} appears always as the
1621 leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1622
1623 The first alternative is empty because there are no symbols between the
1624 colon and the first @samp{|}; this means that @code{input} can match an
1625 empty string of input (no tokens). We write the rules this way because it
1626 is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1627 It's conventional to put an empty alternative first and write the comment
1628 @samp{/* empty */} in it.
1629
1630 The second alternate rule (@code{input line}) handles all nontrivial input.
1631 It means, ``After reading any number of lines, read one more line if
1632 possible.'' The left recursion makes this rule into a loop. Since the
1633 first alternative matches empty input, the loop can be executed zero or
1634 more times.
1635
1636 The parser function @code{yyparse} continues to process input until a
1637 grammatical error is seen or the lexical analyzer says there are no more
1638 input tokens; we will arrange for the latter to happen at end-of-input.
1639
1640 @node Rpcalc Line
1641 @subsubsection Explanation of @code{line}
1642
1643 Now consider the definition of @code{line}:
1644
1645 @example
1646 line: '\n'
1647 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1648 ;
1649 @end example
1650
1651 The first alternative is a token which is a newline character; this means
1652 that rpcalc accepts a blank line (and ignores it, since there is no
1653 action). The second alternative is an expression followed by a newline.
1654 This is the alternative that makes rpcalc useful. The semantic value of
1655 the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1656 question is the first symbol in the alternative. The action prints this
1657 value, which is the result of the computation the user asked for.
1658
1659 This action is unusual because it does not assign a value to @code{$$}. As
1660 a consequence, the semantic value associated with the @code{line} is
1661 uninitialized (its value will be unpredictable). This would be a bug if
1662 that value were ever used, but we don't use it: once rpcalc has printed the
1663 value of the user's input line, that value is no longer needed.
1664
1665 @node Rpcalc Expr
1666 @subsubsection Explanation of @code{expr}
1667
1668 The @code{exp} grouping has several rules, one for each kind of expression.
1669 The first rule handles the simplest expressions: those that are just numbers.
1670 The second handles an addition-expression, which looks like two expressions
1671 followed by a plus-sign. The third handles subtraction, and so on.
1672
1673 @example
1674 exp: NUM
1675 | exp exp '+' @{ $$ = $1 + $2; @}
1676 | exp exp '-' @{ $$ = $1 - $2; @}
1677 @dots{}
1678 ;
1679 @end example
1680
1681 We have used @samp{|} to join all the rules for @code{exp}, but we could
1682 equally well have written them separately:
1683
1684 @example
1685 exp: NUM ;
1686 exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1687 exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1688 @dots{}
1689 @end example
1690
1691 Most of the rules have actions that compute the value of the expression in
1692 terms of the value of its parts. For example, in the rule for addition,
1693 @code{$1} refers to the first component @code{exp} and @code{$2} refers to
1694 the second one. The third component, @code{'+'}, has no meaningful
1695 associated semantic value, but if it had one you could refer to it as
1696 @code{$3}. When @code{yyparse} recognizes a sum expression using this
1697 rule, the sum of the two subexpressions' values is produced as the value of
1698 the entire expression. @xref{Actions}.
1699
1700 You don't have to give an action for every rule. When a rule has no
1701 action, Bison by default copies the value of @code{$1} into @code{$$}.
1702 This is what happens in the first rule (the one that uses @code{NUM}).
1703
1704 The formatting shown here is the recommended convention, but Bison does
1705 not require it. You can add or change white space as much as you wish.
1706 For example, this:
1707
1708 @example
1709 exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
1710 @end example
1711
1712 @noindent
1713 means the same thing as this:
1714
1715 @example
1716 exp: NUM
1717 | exp exp '+' @{ $$ = $1 + $2; @}
1718 | @dots{}
1719 ;
1720 @end example
1721
1722 @noindent
1723 The latter, however, is much more readable.
1724
1725 @node Rpcalc Lexer
1726 @subsection The @code{rpcalc} Lexical Analyzer
1727 @cindex writing a lexical analyzer
1728 @cindex lexical analyzer, writing
1729
1730 The lexical analyzer's job is low-level parsing: converting characters
1731 or sequences of characters into tokens. The Bison parser gets its
1732 tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1733 Analyzer Function @code{yylex}}.
1734
1735 Only a simple lexical analyzer is needed for the RPN
1736 calculator. This
1737 lexical analyzer skips blanks and tabs, then reads in numbers as
1738 @code{double} and returns them as @code{NUM} tokens. Any other character
1739 that isn't part of a number is a separate token. Note that the token-code
1740 for such a single-character token is the character itself.
1741
1742 The return value of the lexical analyzer function is a numeric code which
1743 represents a token type. The same text used in Bison rules to stand for
1744 this token type is also a C expression for the numeric code for the type.
1745 This works in two ways. If the token type is a character literal, then its
1746 numeric code is that of the character; you can use the same
1747 character literal in the lexical analyzer to express the number. If the
1748 token type is an identifier, that identifier is defined by Bison as a C
1749 macro whose definition is the appropriate number. In this example,
1750 therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1751
1752 The semantic value of the token (if it has one) is stored into the
1753 global variable @code{yylval}, which is where the Bison parser will look
1754 for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1755 defined at the beginning of the grammar; @pxref{Rpcalc Declarations,
1756 ,Declarations for @code{rpcalc}}.)
1757
1758 A token type code of zero is returned if the end-of-input is encountered.
1759 (Bison recognizes any nonpositive value as indicating end-of-input.)
1760
1761 Here is the code for the lexical analyzer:
1762
1763 @example
1764 @group
1765 /* The lexical analyzer returns a double floating point
1766 number on the stack and the token NUM, or the numeric code
1767 of the character read if not a number. It skips all blanks
1768 and tabs, and returns 0 for end-of-input. */
1769
1770 #include <ctype.h>
1771 @end group
1772
1773 @group
1774 int
1775 yylex (void)
1776 @{
1777 int c;
1778
1779 /* Skip white space. */
1780 while ((c = getchar ()) == ' ' || c == '\t')
1781 ;
1782 @end group
1783 @group
1784 /* Process numbers. */
1785 if (c == '.' || isdigit (c))
1786 @{
1787 ungetc (c, stdin);
1788 scanf ("%lf", &yylval);
1789 return NUM;
1790 @}
1791 @end group
1792 @group
1793 /* Return end-of-input. */
1794 if (c == EOF)
1795 return 0;
1796 /* Return a single char. */
1797 return c;
1798 @}
1799 @end group
1800 @end example
1801
1802 @node Rpcalc Main
1803 @subsection The Controlling Function
1804 @cindex controlling function
1805 @cindex main function in simple example
1806
1807 In keeping with the spirit of this example, the controlling function is
1808 kept to the bare minimum. The only requirement is that it call
1809 @code{yyparse} to start the process of parsing.
1810
1811 @example
1812 @group
1813 int
1814 main (void)
1815 @{
1816 return yyparse ();
1817 @}
1818 @end group
1819 @end example
1820
1821 @node Rpcalc Error
1822 @subsection The Error Reporting Routine
1823 @cindex error reporting routine
1824
1825 When @code{yyparse} detects a syntax error, it calls the error reporting
1826 function @code{yyerror} to print an error message (usually but not
1827 always @code{"syntax error"}). It is up to the programmer to supply
1828 @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1829 here is the definition we will use:
1830
1831 @example
1832 @group
1833 #include <stdio.h>
1834
1835 /* Called by yyparse on error. */
1836 void
1837 yyerror (char const *s)
1838 @{
1839 fprintf (stderr, "%s\n", s);
1840 @}
1841 @end group
1842 @end example
1843
1844 After @code{yyerror} returns, the Bison parser may recover from the error
1845 and continue parsing if the grammar contains a suitable error rule
1846 (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1847 have not written any error rules in this example, so any invalid input will
1848 cause the calculator program to exit. This is not clean behavior for a
1849 real calculator, but it is adequate for the first example.
1850
1851 @node Rpcalc Generate
1852 @subsection Running Bison to Make the Parser
1853 @cindex running Bison (introduction)
1854
1855 Before running Bison to produce a parser, we need to decide how to
1856 arrange all the source code in one or more source files. For such a
1857 simple example, the easiest thing is to put everything in one file,
1858 the grammar file. The definitions of @code{yylex}, @code{yyerror} and
1859 @code{main} go at the end, in the epilogue of the grammar file
1860 (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
1861
1862 For a large project, you would probably have several source files, and use
1863 @code{make} to arrange to recompile them.
1864
1865 With all the source in the grammar file, you use the following command
1866 to convert it into a parser implementation file:
1867
1868 @example
1869 bison @var{file}.y
1870 @end example
1871
1872 @noindent
1873 In this example, the grammar file is called @file{rpcalc.y} (for
1874 ``Reverse Polish @sc{calc}ulator''). Bison produces a parser
1875 implementation file named @file{@var{file}.tab.c}, removing the
1876 @samp{.y} from the grammar file name. The parser implementation file
1877 contains the source code for @code{yyparse}. The additional functions
1878 in the grammar file (@code{yylex}, @code{yyerror} and @code{main}) are
1879 copied verbatim to the parser implementation file.
1880
1881 @node Rpcalc Compile
1882 @subsection Compiling the Parser Implementation File
1883 @cindex compiling the parser
1884
1885 Here is how to compile and run the parser implementation file:
1886
1887 @example
1888 @group
1889 # @r{List files in current directory.}
1890 $ @kbd{ls}
1891 rpcalc.tab.c rpcalc.y
1892 @end group
1893
1894 @group
1895 # @r{Compile the Bison parser.}
1896 # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
1897 $ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
1898 @end group
1899
1900 @group
1901 # @r{List files again.}
1902 $ @kbd{ls}
1903 rpcalc rpcalc.tab.c rpcalc.y
1904 @end group
1905 @end example
1906
1907 The file @file{rpcalc} now contains the executable code. Here is an
1908 example session using @code{rpcalc}.
1909
1910 @example
1911 $ @kbd{rpcalc}
1912 @kbd{4 9 +}
1913 13
1914 @kbd{3 7 + 3 4 5 *+-}
1915 -13
1916 @kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
1917 13
1918 @kbd{5 6 / 4 n +}
1919 -3.166666667
1920 @kbd{3 4 ^} @r{Exponentiation}
1921 81
1922 @kbd{^D} @r{End-of-file indicator}
1923 $
1924 @end example
1925
1926 @node Infix Calc
1927 @section Infix Notation Calculator: @code{calc}
1928 @cindex infix notation calculator
1929 @cindex @code{calc}
1930 @cindex calculator, infix notation
1931
1932 We now modify rpcalc to handle infix operators instead of postfix. Infix
1933 notation involves the concept of operator precedence and the need for
1934 parentheses nested to arbitrary depth. Here is the Bison code for
1935 @file{calc.y}, an infix desk-top calculator.
1936
1937 @example
1938 /* Infix notation calculator. */
1939
1940 %@{
1941 #define YYSTYPE double
1942 #include <math.h>
1943 #include <stdio.h>
1944 int yylex (void);
1945 void yyerror (char const *);
1946 %@}
1947
1948 /* Bison declarations. */
1949 %token NUM
1950 %left '-' '+'
1951 %left '*' '/'
1952 %precedence NEG /* negation--unary minus */
1953 %right '^' /* exponentiation */
1954
1955 %% /* The grammar follows. */
1956 input: /* empty */
1957 | input line
1958 ;
1959
1960 line: '\n'
1961 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1962 ;
1963
1964 exp: NUM @{ $$ = $1; @}
1965 | exp '+' exp @{ $$ = $1 + $3; @}
1966 | exp '-' exp @{ $$ = $1 - $3; @}
1967 | exp '*' exp @{ $$ = $1 * $3; @}
1968 | exp '/' exp @{ $$ = $1 / $3; @}
1969 | '-' exp %prec NEG @{ $$ = -$2; @}
1970 | exp '^' exp @{ $$ = pow ($1, $3); @}
1971 | '(' exp ')' @{ $$ = $2; @}
1972 ;
1973 %%
1974 @end example
1975
1976 @noindent
1977 The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1978 same as before.
1979
1980 There are two important new features shown in this code.
1981
1982 In the second section (Bison declarations), @code{%left} declares token
1983 types and says they are left-associative operators. The declarations
1984 @code{%left} and @code{%right} (right associativity) take the place of
1985 @code{%token} which is used to declare a token type name without
1986 associativity/precedence. (These tokens are single-character literals, which
1987 ordinarily don't need to be declared. We declare them here to specify
1988 the associativity/precedence.)
1989
1990 Operator precedence is determined by the line ordering of the
1991 declarations; the higher the line number of the declaration (lower on
1992 the page or screen), the higher the precedence. Hence, exponentiation
1993 has the highest precedence, unary minus (@code{NEG}) is next, followed
1994 by @samp{*} and @samp{/}, and so on. Unary minus is not associative,
1995 only precedence matters (@code{%precedence}. @xref{Precedence, ,Operator
1996 Precedence}.
1997
1998 The other important new feature is the @code{%prec} in the grammar
1999 section for the unary minus operator. The @code{%prec} simply instructs
2000 Bison that the rule @samp{| '-' exp} has the same precedence as
2001 @code{NEG}---in this case the next-to-highest. @xref{Contextual
2002 Precedence, ,Context-Dependent Precedence}.
2003
2004 Here is a sample run of @file{calc.y}:
2005
2006 @need 500
2007 @example
2008 $ @kbd{calc}
2009 @kbd{4 + 4.5 - (34/(8*3+-3))}
2010 6.880952381
2011 @kbd{-56 + 2}
2012 -54
2013 @kbd{3 ^ 2}
2014 9
2015 @end example
2016
2017 @node Simple Error Recovery
2018 @section Simple Error Recovery
2019 @cindex error recovery, simple
2020
2021 Up to this point, this manual has not addressed the issue of @dfn{error
2022 recovery}---how to continue parsing after the parser detects a syntax
2023 error. All we have handled is error reporting with @code{yyerror}.
2024 Recall that by default @code{yyparse} returns after calling
2025 @code{yyerror}. This means that an erroneous input line causes the
2026 calculator program to exit. Now we show how to rectify this deficiency.
2027
2028 The Bison language itself includes the reserved word @code{error}, which
2029 may be included in the grammar rules. In the example below it has
2030 been added to one of the alternatives for @code{line}:
2031
2032 @example
2033 @group
2034 line: '\n'
2035 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2036 | error '\n' @{ yyerrok; @}
2037 ;
2038 @end group
2039 @end example
2040
2041 This addition to the grammar allows for simple error recovery in the
2042 event of a syntax error. If an expression that cannot be evaluated is
2043 read, the error will be recognized by the third rule for @code{line},
2044 and parsing will continue. (The @code{yyerror} function is still called
2045 upon to print its message as well.) The action executes the statement
2046 @code{yyerrok}, a macro defined automatically by Bison; its meaning is
2047 that error recovery is complete (@pxref{Error Recovery}). Note the
2048 difference between @code{yyerrok} and @code{yyerror}; neither one is a
2049 misprint.
2050
2051 This form of error recovery deals with syntax errors. There are other
2052 kinds of errors; for example, division by zero, which raises an exception
2053 signal that is normally fatal. A real calculator program must handle this
2054 signal and use @code{longjmp} to return to @code{main} and resume parsing
2055 input lines; it would also have to discard the rest of the current line of
2056 input. We won't discuss this issue further because it is not specific to
2057 Bison programs.
2058
2059 @node Location Tracking Calc
2060 @section Location Tracking Calculator: @code{ltcalc}
2061 @cindex location tracking calculator
2062 @cindex @code{ltcalc}
2063 @cindex calculator, location tracking
2064
2065 This example extends the infix notation calculator with location
2066 tracking. This feature will be used to improve the error messages. For
2067 the sake of clarity, this example is a simple integer calculator, since
2068 most of the work needed to use locations will be done in the lexical
2069 analyzer.
2070
2071 @menu
2072 * Ltcalc Declarations:: Bison and C declarations for ltcalc.
2073 * Ltcalc Rules:: Grammar rules for ltcalc, with explanations.
2074 * Ltcalc Lexer:: The lexical analyzer.
2075 @end menu
2076
2077 @node Ltcalc Declarations
2078 @subsection Declarations for @code{ltcalc}
2079
2080 The C and Bison declarations for the location tracking calculator are
2081 the same as the declarations for the infix notation calculator.
2082
2083 @example
2084 /* Location tracking calculator. */
2085
2086 %@{
2087 #define YYSTYPE int
2088 #include <math.h>
2089 int yylex (void);
2090 void yyerror (char const *);
2091 %@}
2092
2093 /* Bison declarations. */
2094 %token NUM
2095
2096 %left '-' '+'
2097 %left '*' '/'
2098 %precedence NEG
2099 %right '^'
2100
2101 %% /* The grammar follows. */
2102 @end example
2103
2104 @noindent
2105 Note there are no declarations specific to locations. Defining a data
2106 type for storing locations is not needed: we will use the type provided
2107 by default (@pxref{Location Type, ,Data Types of Locations}), which is a
2108 four member structure with the following integer fields:
2109 @code{first_line}, @code{first_column}, @code{last_line} and
2110 @code{last_column}. By conventions, and in accordance with the GNU
2111 Coding Standards and common practice, the line and column count both
2112 start at 1.
2113
2114 @node Ltcalc Rules
2115 @subsection Grammar Rules for @code{ltcalc}
2116
2117 Whether handling locations or not has no effect on the syntax of your
2118 language. Therefore, grammar rules for this example will be very close
2119 to those of the previous example: we will only modify them to benefit
2120 from the new information.
2121
2122 Here, we will use locations to report divisions by zero, and locate the
2123 wrong expressions or subexpressions.
2124
2125 @example
2126 @group
2127 input : /* empty */
2128 | input line
2129 ;
2130 @end group
2131
2132 @group
2133 line : '\n'
2134 | exp '\n' @{ printf ("%d\n", $1); @}
2135 ;
2136 @end group
2137
2138 @group
2139 exp : NUM @{ $$ = $1; @}
2140 | exp '+' exp @{ $$ = $1 + $3; @}
2141 | exp '-' exp @{ $$ = $1 - $3; @}
2142 | exp '*' exp @{ $$ = $1 * $3; @}
2143 @end group
2144 @group
2145 | exp '/' exp
2146 @{
2147 if ($3)
2148 $$ = $1 / $3;
2149 else
2150 @{
2151 $$ = 1;
2152 fprintf (stderr, "%d.%d-%d.%d: division by zero",
2153 @@3.first_line, @@3.first_column,
2154 @@3.last_line, @@3.last_column);
2155 @}
2156 @}
2157 @end group
2158 @group
2159 | '-' exp %prec NEG @{ $$ = -$2; @}
2160 | exp '^' exp @{ $$ = pow ($1, $3); @}
2161 | '(' exp ')' @{ $$ = $2; @}
2162 @end group
2163 @end example
2164
2165 This code shows how to reach locations inside of semantic actions, by
2166 using the pseudo-variables @code{@@@var{n}} for rule components, and the
2167 pseudo-variable @code{@@$} for groupings.
2168
2169 We don't need to assign a value to @code{@@$}: the output parser does it
2170 automatically. By default, before executing the C code of each action,
2171 @code{@@$} is set to range from the beginning of @code{@@1} to the end
2172 of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
2173 can be redefined (@pxref{Location Default Action, , Default Action for
2174 Locations}), and for very specific rules, @code{@@$} can be computed by
2175 hand.
2176
2177 @node Ltcalc Lexer
2178 @subsection The @code{ltcalc} Lexical Analyzer.
2179
2180 Until now, we relied on Bison's defaults to enable location
2181 tracking. The next step is to rewrite the lexical analyzer, and make it
2182 able to feed the parser with the token locations, as it already does for
2183 semantic values.
2184
2185 To this end, we must take into account every single character of the
2186 input text, to avoid the computed locations of being fuzzy or wrong:
2187
2188 @example
2189 @group
2190 int
2191 yylex (void)
2192 @{
2193 int c;
2194 @end group
2195
2196 @group
2197 /* Skip white space. */
2198 while ((c = getchar ()) == ' ' || c == '\t')
2199 ++yylloc.last_column;
2200 @end group
2201
2202 @group
2203 /* Step. */
2204 yylloc.first_line = yylloc.last_line;
2205 yylloc.first_column = yylloc.last_column;
2206 @end group
2207
2208 @group
2209 /* Process numbers. */
2210 if (isdigit (c))
2211 @{
2212 yylval = c - '0';
2213 ++yylloc.last_column;
2214 while (isdigit (c = getchar ()))
2215 @{
2216 ++yylloc.last_column;
2217 yylval = yylval * 10 + c - '0';
2218 @}
2219 ungetc (c, stdin);
2220 return NUM;
2221 @}
2222 @end group
2223
2224 /* Return end-of-input. */
2225 if (c == EOF)
2226 return 0;
2227
2228 /* Return a single char, and update location. */
2229 if (c == '\n')
2230 @{
2231 ++yylloc.last_line;
2232 yylloc.last_column = 0;
2233 @}
2234 else
2235 ++yylloc.last_column;
2236 return c;
2237 @}
2238 @end example
2239
2240 Basically, the lexical analyzer performs the same processing as before:
2241 it skips blanks and tabs, and reads numbers or single-character tokens.
2242 In addition, it updates @code{yylloc}, the global variable (of type
2243 @code{YYLTYPE}) containing the token's location.
2244
2245 Now, each time this function returns a token, the parser has its number
2246 as well as its semantic value, and its location in the text. The last
2247 needed change is to initialize @code{yylloc}, for example in the
2248 controlling function:
2249
2250 @example
2251 @group
2252 int
2253 main (void)
2254 @{
2255 yylloc.first_line = yylloc.last_line = 1;
2256 yylloc.first_column = yylloc.last_column = 0;
2257 return yyparse ();
2258 @}
2259 @end group
2260 @end example
2261
2262 Remember that computing locations is not a matter of syntax. Every
2263 character must be associated to a location update, whether it is in
2264 valid input, in comments, in literal strings, and so on.
2265
2266 @node Multi-function Calc
2267 @section Multi-Function Calculator: @code{mfcalc}
2268 @cindex multi-function calculator
2269 @cindex @code{mfcalc}
2270 @cindex calculator, multi-function
2271
2272 Now that the basics of Bison have been discussed, it is time to move on to
2273 a more advanced problem. The above calculators provided only five
2274 functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
2275 be nice to have a calculator that provides other mathematical functions such
2276 as @code{sin}, @code{cos}, etc.
2277
2278 It is easy to add new operators to the infix calculator as long as they are
2279 only single-character literals. The lexical analyzer @code{yylex} passes
2280 back all nonnumeric characters as tokens, so new grammar rules suffice for
2281 adding a new operator. But we want something more flexible: built-in
2282 functions whose syntax has this form:
2283
2284 @example
2285 @var{function_name} (@var{argument})
2286 @end example
2287
2288 @noindent
2289 At the same time, we will add memory to the calculator, by allowing you
2290 to create named variables, store values in them, and use them later.
2291 Here is a sample session with the multi-function calculator:
2292
2293 @example
2294 $ @kbd{mfcalc}
2295 @kbd{pi = 3.141592653589}
2296 3.1415926536
2297 @kbd{sin(pi)}
2298 0.0000000000
2299 @kbd{alpha = beta1 = 2.3}
2300 2.3000000000
2301 @kbd{alpha}
2302 2.3000000000
2303 @kbd{ln(alpha)}
2304 0.8329091229
2305 @kbd{exp(ln(beta1))}
2306 2.3000000000
2307 $
2308 @end example
2309
2310 Note that multiple assignment and nested function calls are permitted.
2311
2312 @menu
2313 * Mfcalc Declarations:: Bison declarations for multi-function calculator.
2314 * Mfcalc Rules:: Grammar rules for the calculator.
2315 * Mfcalc Symbol Table:: Symbol table management subroutines.
2316 @end menu
2317
2318 @node Mfcalc Declarations
2319 @subsection Declarations for @code{mfcalc}
2320
2321 Here are the C and Bison declarations for the multi-function calculator.
2322
2323 @smallexample
2324 @group
2325 %@{
2326 #include <math.h> /* For math functions, cos(), sin(), etc. */
2327 #include "calc.h" /* Contains definition of `symrec'. */
2328 int yylex (void);
2329 void yyerror (char const *);
2330 %@}
2331 @end group
2332 @group
2333 %union @{
2334 double val; /* For returning numbers. */
2335 symrec *tptr; /* For returning symbol-table pointers. */
2336 @}
2337 @end group
2338 %token <val> NUM /* Simple double precision number. */
2339 %token <tptr> VAR FNCT /* Variable and Function. */
2340 %type <val> exp
2341
2342 @group
2343 %right '='
2344 %left '-' '+'
2345 %left '*' '/'
2346 %precedence NEG /* negation--unary minus */
2347 %right '^' /* exponentiation */
2348 @end group
2349 %% /* The grammar follows. */
2350 @end smallexample
2351
2352 The above grammar introduces only two new features of the Bison language.
2353 These features allow semantic values to have various data types
2354 (@pxref{Multiple Types, ,More Than One Value Type}).
2355
2356 The @code{%union} declaration specifies the entire list of possible types;
2357 this is instead of defining @code{YYSTYPE}. The allowable types are now
2358 double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
2359 the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
2360
2361 Since values can now have various types, it is necessary to associate a
2362 type with each grammar symbol whose semantic value is used. These symbols
2363 are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
2364 declarations are augmented with information about their data type (placed
2365 between angle brackets).
2366
2367 The Bison construct @code{%type} is used for declaring nonterminal
2368 symbols, just as @code{%token} is used for declaring token types. We
2369 have not used @code{%type} before because nonterminal symbols are
2370 normally declared implicitly by the rules that define them. But
2371 @code{exp} must be declared explicitly so we can specify its value type.
2372 @xref{Type Decl, ,Nonterminal Symbols}.
2373
2374 @node Mfcalc Rules
2375 @subsection Grammar Rules for @code{mfcalc}
2376
2377 Here are the grammar rules for the multi-function calculator.
2378 Most of them are copied directly from @code{calc}; three rules,
2379 those which mention @code{VAR} or @code{FNCT}, are new.
2380
2381 @smallexample
2382 @group
2383 input: /* empty */
2384 | input line
2385 ;
2386 @end group
2387
2388 @group
2389 line:
2390 '\n'
2391 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2392 | error '\n' @{ yyerrok; @}
2393 ;
2394 @end group
2395
2396 @group
2397 exp: NUM @{ $$ = $1; @}
2398 | VAR @{ $$ = $1->value.var; @}
2399 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
2400 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
2401 | exp '+' exp @{ $$ = $1 + $3; @}
2402 | exp '-' exp @{ $$ = $1 - $3; @}
2403 | exp '*' exp @{ $$ = $1 * $3; @}
2404 | exp '/' exp @{ $$ = $1 / $3; @}
2405 | '-' exp %prec NEG @{ $$ = -$2; @}
2406 | exp '^' exp @{ $$ = pow ($1, $3); @}
2407 | '(' exp ')' @{ $$ = $2; @}
2408 ;
2409 @end group
2410 /* End of grammar. */
2411 %%
2412 @end smallexample
2413
2414 @node Mfcalc Symbol Table
2415 @subsection The @code{mfcalc} Symbol Table
2416 @cindex symbol table example
2417
2418 The multi-function calculator requires a symbol table to keep track of the
2419 names and meanings of variables and functions. This doesn't affect the
2420 grammar rules (except for the actions) or the Bison declarations, but it
2421 requires some additional C functions for support.
2422
2423 The symbol table itself consists of a linked list of records. Its
2424 definition, which is kept in the header @file{calc.h}, is as follows. It
2425 provides for either functions or variables to be placed in the table.
2426
2427 @smallexample
2428 @group
2429 /* Function type. */
2430 typedef double (*func_t) (double);
2431 @end group
2432
2433 @group
2434 /* Data type for links in the chain of symbols. */
2435 struct symrec
2436 @{
2437 char *name; /* name of symbol */
2438 int type; /* type of symbol: either VAR or FNCT */
2439 union
2440 @{
2441 double var; /* value of a VAR */
2442 func_t fnctptr; /* value of a FNCT */
2443 @} value;
2444 struct symrec *next; /* link field */
2445 @};
2446 @end group
2447
2448 @group
2449 typedef struct symrec symrec;
2450
2451 /* The symbol table: a chain of `struct symrec'. */
2452 extern symrec *sym_table;
2453
2454 symrec *putsym (char const *, int);
2455 symrec *getsym (char const *);
2456 @end group
2457 @end smallexample
2458
2459 The new version of @code{main} includes a call to @code{init_table}, a
2460 function that initializes the symbol table. Here it is, and
2461 @code{init_table} as well:
2462
2463 @smallexample
2464 #include <stdio.h>
2465
2466 @group
2467 /* Called by yyparse on error. */
2468 void
2469 yyerror (char const *s)
2470 @{
2471 printf ("%s\n", s);
2472 @}
2473 @end group
2474
2475 @group
2476 struct init
2477 @{
2478 char const *fname;
2479 double (*fnct) (double);
2480 @};
2481 @end group
2482
2483 @group
2484 struct init const arith_fncts[] =
2485 @{
2486 "sin", sin,
2487 "cos", cos,
2488 "atan", atan,
2489 "ln", log,
2490 "exp", exp,
2491 "sqrt", sqrt,
2492 0, 0
2493 @};
2494 @end group
2495
2496 @group
2497 /* The symbol table: a chain of `struct symrec'. */
2498 symrec *sym_table;
2499 @end group
2500
2501 @group
2502 /* Put arithmetic functions in table. */
2503 void
2504 init_table (void)
2505 @{
2506 int i;
2507 symrec *ptr;
2508 for (i = 0; arith_fncts[i].fname != 0; i++)
2509 @{
2510 ptr = putsym (arith_fncts[i].fname, FNCT);
2511 ptr->value.fnctptr = arith_fncts[i].fnct;
2512 @}
2513 @}
2514 @end group
2515
2516 @group
2517 int
2518 main (void)
2519 @{
2520 init_table ();
2521 return yyparse ();
2522 @}
2523 @end group
2524 @end smallexample
2525
2526 By simply editing the initialization list and adding the necessary include
2527 files, you can add additional functions to the calculator.
2528
2529 Two important functions allow look-up and installation of symbols in the
2530 symbol table. The function @code{putsym} is passed a name and the type
2531 (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2532 linked to the front of the list, and a pointer to the object is returned.
2533 The function @code{getsym} is passed the name of the symbol to look up. If
2534 found, a pointer to that symbol is returned; otherwise zero is returned.
2535
2536 @smallexample
2537 symrec *
2538 putsym (char const *sym_name, int sym_type)
2539 @{
2540 symrec *ptr;
2541 ptr = (symrec *) malloc (sizeof (symrec));
2542 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2543 strcpy (ptr->name,sym_name);
2544 ptr->type = sym_type;
2545 ptr->value.var = 0; /* Set value to 0 even if fctn. */
2546 ptr->next = (struct symrec *)sym_table;
2547 sym_table = ptr;
2548 return ptr;
2549 @}
2550
2551 symrec *
2552 getsym (char const *sym_name)
2553 @{
2554 symrec *ptr;
2555 for (ptr = sym_table; ptr != (symrec *) 0;
2556 ptr = (symrec *)ptr->next)
2557 if (strcmp (ptr->name,sym_name) == 0)
2558 return ptr;
2559 return 0;
2560 @}
2561 @end smallexample
2562
2563 The function @code{yylex} must now recognize variables, numeric values, and
2564 the single-character arithmetic operators. Strings of alphanumeric
2565 characters with a leading letter are recognized as either variables or
2566 functions depending on what the symbol table says about them.
2567
2568 The string is passed to @code{getsym} for look up in the symbol table. If
2569 the name appears in the table, a pointer to its location and its type
2570 (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2571 already in the table, then it is installed as a @code{VAR} using
2572 @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
2573 returned to @code{yyparse}.
2574
2575 No change is needed in the handling of numeric values and arithmetic
2576 operators in @code{yylex}.
2577
2578 @smallexample
2579 @group
2580 #include <ctype.h>
2581 @end group
2582
2583 @group
2584 int
2585 yylex (void)
2586 @{
2587 int c;
2588
2589 /* Ignore white space, get first nonwhite character. */
2590 while ((c = getchar ()) == ' ' || c == '\t');
2591
2592 if (c == EOF)
2593 return 0;
2594 @end group
2595
2596 @group
2597 /* Char starts a number => parse the number. */
2598 if (c == '.' || isdigit (c))
2599 @{
2600 ungetc (c, stdin);
2601 scanf ("%lf", &yylval.val);
2602 return NUM;
2603 @}
2604 @end group
2605
2606 @group
2607 /* Char starts an identifier => read the name. */
2608 if (isalpha (c))
2609 @{
2610 symrec *s;
2611 static char *symbuf = 0;
2612 static int length = 0;
2613 int i;
2614 @end group
2615
2616 @group
2617 /* Initially make the buffer long enough
2618 for a 40-character symbol name. */
2619 if (length == 0)
2620 length = 40, symbuf = (char *)malloc (length + 1);
2621
2622 i = 0;
2623 do
2624 @end group
2625 @group
2626 @{
2627 /* If buffer is full, make it bigger. */
2628 if (i == length)
2629 @{
2630 length *= 2;
2631 symbuf = (char *) realloc (symbuf, length + 1);
2632 @}
2633 /* Add this character to the buffer. */
2634 symbuf[i++] = c;
2635 /* Get another character. */
2636 c = getchar ();
2637 @}
2638 @end group
2639 @group
2640 while (isalnum (c));
2641
2642 ungetc (c, stdin);
2643 symbuf[i] = '\0';
2644 @end group
2645
2646 @group
2647 s = getsym (symbuf);
2648 if (s == 0)
2649 s = putsym (symbuf, VAR);
2650 yylval.tptr = s;
2651 return s->type;
2652 @}
2653
2654 /* Any other character is a token by itself. */
2655 return c;
2656 @}
2657 @end group
2658 @end smallexample
2659
2660 This program is both powerful and flexible. You may easily add new
2661 functions, and it is a simple job to modify this code to install
2662 predefined variables such as @code{pi} or @code{e} as well.
2663
2664 @node Exercises
2665 @section Exercises
2666 @cindex exercises
2667
2668 @enumerate
2669 @item
2670 Add some new functions from @file{math.h} to the initialization list.
2671
2672 @item
2673 Add another array that contains constants and their values. Then
2674 modify @code{init_table} to add these constants to the symbol table.
2675 It will be easiest to give the constants type @code{VAR}.
2676
2677 @item
2678 Make the program report an error if the user refers to an
2679 uninitialized variable in any way except to store a value in it.
2680 @end enumerate
2681
2682 @node Grammar File
2683 @chapter Bison Grammar Files
2684
2685 Bison takes as input a context-free grammar specification and produces a
2686 C-language function that recognizes correct instances of the grammar.
2687
2688 The Bison grammar file conventionally has a name ending in @samp{.y}.
2689 @xref{Invocation, ,Invoking Bison}.
2690
2691 @menu
2692 * Grammar Outline:: Overall layout of the grammar file.
2693 * Symbols:: Terminal and nonterminal symbols.
2694 * Rules:: How to write grammar rules.
2695 * Recursion:: Writing recursive rules.
2696 * Semantics:: Semantic values and actions.
2697 * Locations:: Locations and actions.
2698 * Declarations:: All kinds of Bison declarations are described here.
2699 * Multiple Parsers:: Putting more than one Bison parser in one program.
2700 @end menu
2701
2702 @node Grammar Outline
2703 @section Outline of a Bison Grammar
2704
2705 A Bison grammar file has four main sections, shown here with the
2706 appropriate delimiters:
2707
2708 @example
2709 %@{
2710 @var{Prologue}
2711 %@}
2712
2713 @var{Bison declarations}
2714
2715 %%
2716 @var{Grammar rules}
2717 %%
2718
2719 @var{Epilogue}
2720 @end example
2721
2722 Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2723 As a GNU extension, @samp{//} introduces a comment that
2724 continues until end of line.
2725
2726 @menu
2727 * Prologue:: Syntax and usage of the prologue.
2728 * Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
2729 * Bison Declarations:: Syntax and usage of the Bison declarations section.
2730 * Grammar Rules:: Syntax and usage of the grammar rules section.
2731 * Epilogue:: Syntax and usage of the epilogue.
2732 @end menu
2733
2734 @node Prologue
2735 @subsection The prologue
2736 @cindex declarations section
2737 @cindex Prologue
2738 @cindex declarations
2739
2740 The @var{Prologue} section contains macro definitions and declarations
2741 of functions and variables that are used in the actions in the grammar
2742 rules. These are copied to the beginning of the parser implementation
2743 file so that they precede the definition of @code{yyparse}. You can
2744 use @samp{#include} to get the declarations from a header file. If
2745 you don't need any C declarations, you may omit the @samp{%@{} and
2746 @samp{%@}} delimiters that bracket this section.
2747
2748 The @var{Prologue} section is terminated by the first occurrence
2749 of @samp{%@}} that is outside a comment, a string literal, or a
2750 character constant.
2751
2752 You may have more than one @var{Prologue} section, intermixed with the
2753 @var{Bison declarations}. This allows you to have C and Bison
2754 declarations that refer to each other. For example, the @code{%union}
2755 declaration may use types defined in a header file, and you may wish to
2756 prototype functions that take arguments of type @code{YYSTYPE}. This
2757 can be done with two @var{Prologue} blocks, one before and one after the
2758 @code{%union} declaration.
2759
2760 @smallexample
2761 %@{
2762 #define _GNU_SOURCE
2763 #include <stdio.h>
2764 #include "ptypes.h"
2765 %@}
2766
2767 %union @{
2768 long int n;
2769 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2770 @}
2771
2772 %@{
2773 static void print_token_value (FILE *, int, YYSTYPE);
2774 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2775 %@}
2776
2777 @dots{}
2778 @end smallexample
2779
2780 When in doubt, it is usually safer to put prologue code before all
2781 Bison declarations, rather than after. For example, any definitions
2782 of feature test macros like @code{_GNU_SOURCE} or
2783 @code{_POSIX_C_SOURCE} should appear before all Bison declarations, as
2784 feature test macros can affect the behavior of Bison-generated
2785 @code{#include} directives.
2786
2787 @node Prologue Alternatives
2788 @subsection Prologue Alternatives
2789 @cindex Prologue Alternatives
2790
2791 @findex %code
2792 @findex %code requires
2793 @findex %code provides
2794 @findex %code top
2795
2796 The functionality of @var{Prologue} sections can often be subtle and
2797 inflexible. As an alternative, Bison provides a @code{%code}
2798 directive with an explicit qualifier field, which identifies the
2799 purpose of the code and thus the location(s) where Bison should
2800 generate it. For C/C++, the qualifier can be omitted for the default
2801 location, or it can be one of @code{requires}, @code{provides},
2802 @code{top}. @xref{%code Summary}.
2803
2804 Look again at the example of the previous section:
2805
2806 @smallexample
2807 %@{
2808 #define _GNU_SOURCE
2809 #include <stdio.h>
2810 #include "ptypes.h"
2811 %@}
2812
2813 %union @{
2814 long int n;
2815 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2816 @}
2817
2818 %@{
2819 static void print_token_value (FILE *, int, YYSTYPE);
2820 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2821 %@}
2822
2823 @dots{}
2824 @end smallexample
2825
2826 @noindent
2827 Notice that there are two @var{Prologue} sections here, but there's a
2828 subtle distinction between their functionality. For example, if you
2829 decide to override Bison's default definition for @code{YYLTYPE}, in
2830 which @var{Prologue} section should you write your new definition?
2831 You should write it in the first since Bison will insert that code
2832 into the parser implementation file @emph{before} the default
2833 @code{YYLTYPE} definition. In which @var{Prologue} section should you
2834 prototype an internal function, @code{trace_token}, that accepts
2835 @code{YYLTYPE} and @code{yytokentype} as arguments? You should
2836 prototype it in the second since Bison will insert that code
2837 @emph{after} the @code{YYLTYPE} and @code{yytokentype} definitions.
2838
2839 This distinction in functionality between the two @var{Prologue} sections is
2840 established by the appearance of the @code{%union} between them.
2841 This behavior raises a few questions.
2842 First, why should the position of a @code{%union} affect definitions related to
2843 @code{YYLTYPE} and @code{yytokentype}?
2844 Second, what if there is no @code{%union}?
2845 In that case, the second kind of @var{Prologue} section is not available.
2846 This behavior is not intuitive.
2847
2848 To avoid this subtle @code{%union} dependency, rewrite the example using a
2849 @code{%code top} and an unqualified @code{%code}.
2850 Let's go ahead and add the new @code{YYLTYPE} definition and the
2851 @code{trace_token} prototype at the same time:
2852
2853 @smallexample
2854 %code top @{
2855 #define _GNU_SOURCE
2856 #include <stdio.h>
2857
2858 /* WARNING: The following code really belongs
2859 * in a `%code requires'; see below. */
2860
2861 #include "ptypes.h"
2862 #define YYLTYPE YYLTYPE
2863 typedef struct YYLTYPE
2864 @{
2865 int first_line;
2866 int first_column;
2867 int last_line;
2868 int last_column;
2869 char *filename;
2870 @} YYLTYPE;
2871 @}
2872
2873 %union @{
2874 long int n;
2875 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2876 @}
2877
2878 %code @{
2879 static void print_token_value (FILE *, int, YYSTYPE);
2880 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2881 static void trace_token (enum yytokentype token, YYLTYPE loc);
2882 @}
2883
2884 @dots{}
2885 @end smallexample
2886
2887 @noindent
2888 In this way, @code{%code top} and the unqualified @code{%code} achieve the same
2889 functionality as the two kinds of @var{Prologue} sections, but it's always
2890 explicit which kind you intend.
2891 Moreover, both kinds are always available even in the absence of @code{%union}.
2892
2893 The @code{%code top} block above logically contains two parts. The
2894 first two lines before the warning need to appear near the top of the
2895 parser implementation file. The first line after the warning is
2896 required by @code{YYSTYPE} and thus also needs to appear in the parser
2897 implementation file. However, if you've instructed Bison to generate
2898 a parser header file (@pxref{Decl Summary, ,%defines}), you probably
2899 want that line to appear before the @code{YYSTYPE} definition in that
2900 header file as well. The @code{YYLTYPE} definition should also appear
2901 in the parser header file to override the default @code{YYLTYPE}
2902 definition there.
2903
2904 In other words, in the @code{%code top} block above, all but the first two
2905 lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
2906 definitions.
2907 Thus, they belong in one or more @code{%code requires}:
2908
2909 @smallexample
2910 %code top @{
2911 #define _GNU_SOURCE
2912 #include <stdio.h>
2913 @}
2914
2915 %code requires @{
2916 #include "ptypes.h"
2917 @}
2918 %union @{
2919 long int n;
2920 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2921 @}
2922
2923 %code requires @{
2924 #define YYLTYPE YYLTYPE
2925 typedef struct YYLTYPE
2926 @{
2927 int first_line;
2928 int first_column;
2929 int last_line;
2930 int last_column;
2931 char *filename;
2932 @} YYLTYPE;
2933 @}
2934
2935 %code @{
2936 static void print_token_value (FILE *, int, YYSTYPE);
2937 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2938 static void trace_token (enum yytokentype token, YYLTYPE loc);
2939 @}
2940
2941 @dots{}
2942 @end smallexample
2943
2944 @noindent
2945 Now Bison will insert @code{#include "ptypes.h"} and the new
2946 @code{YYLTYPE} definition before the Bison-generated @code{YYSTYPE}
2947 and @code{YYLTYPE} definitions in both the parser implementation file
2948 and the parser header file. (By the same reasoning, @code{%code
2949 requires} would also be the appropriate place to write your own
2950 definition for @code{YYSTYPE}.)
2951
2952 When you are writing dependency code for @code{YYSTYPE} and
2953 @code{YYLTYPE}, you should prefer @code{%code requires} over
2954 @code{%code top} regardless of whether you instruct Bison to generate
2955 a parser header file. When you are writing code that you need Bison
2956 to insert only into the parser implementation file and that has no
2957 special need to appear at the top of that file, you should prefer the
2958 unqualified @code{%code} over @code{%code top}. These practices will
2959 make the purpose of each block of your code explicit to Bison and to
2960 other developers reading your grammar file. Following these
2961 practices, we expect the unqualified @code{%code} and @code{%code
2962 requires} to be the most important of the four @var{Prologue}
2963 alternatives.
2964
2965 At some point while developing your parser, you might decide to
2966 provide @code{trace_token} to modules that are external to your
2967 parser. Thus, you might wish for Bison to insert the prototype into
2968 both the parser header file and the parser implementation file. Since
2969 this function is not a dependency required by @code{YYSTYPE} or
2970 @code{YYLTYPE}, it doesn't make sense to move its prototype to a
2971 @code{%code requires}. More importantly, since it depends upon
2972 @code{YYLTYPE} and @code{yytokentype}, @code{%code requires} is not
2973 sufficient. Instead, move its prototype from the unqualified
2974 @code{%code} to a @code{%code provides}:
2975
2976 @smallexample
2977 %code top @{
2978 #define _GNU_SOURCE
2979 #include <stdio.h>
2980 @}
2981
2982 %code requires @{
2983 #include "ptypes.h"
2984 @}
2985 %union @{
2986 long int n;
2987 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2988 @}
2989
2990 %code requires @{
2991 #define YYLTYPE YYLTYPE
2992 typedef struct YYLTYPE
2993 @{
2994 int first_line;
2995 int first_column;
2996 int last_line;
2997 int last_column;
2998 char *filename;
2999 @} YYLTYPE;
3000 @}
3001
3002 %code provides @{
3003 void trace_token (enum yytokentype token, YYLTYPE loc);
3004 @}
3005
3006 %code @{
3007 static void print_token_value (FILE *, int, YYSTYPE);
3008 #define YYPRINT(F, N, L) print_token_value (F, N, L)
3009 @}
3010
3011 @dots{}
3012 @end smallexample
3013
3014 @noindent
3015 Bison will insert the @code{trace_token} prototype into both the
3016 parser header file and the parser implementation file after the
3017 definitions for @code{yytokentype}, @code{YYLTYPE}, and
3018 @code{YYSTYPE}.
3019
3020 The above examples are careful to write directives in an order that
3021 reflects the layout of the generated parser implementation and header
3022 files: @code{%code top}, @code{%code requires}, @code{%code provides},
3023 and then @code{%code}. While your grammar files may generally be
3024 easier to read if you also follow this order, Bison does not require
3025 it. Instead, Bison lets you choose an organization that makes sense
3026 to you.
3027
3028 You may declare any of these directives multiple times in the grammar file.
3029 In that case, Bison concatenates the contained code in declaration order.
3030 This is the only way in which the position of one of these directives within
3031 the grammar file affects its functionality.
3032
3033 The result of the previous two properties is greater flexibility in how you may
3034 organize your grammar file.
3035 For example, you may organize semantic-type-related directives by semantic
3036 type:
3037
3038 @smallexample
3039 %code requires @{ #include "type1.h" @}
3040 %union @{ type1 field1; @}
3041 %destructor @{ type1_free ($$); @} <field1>
3042 %printer @{ type1_print ($$); @} <field1>
3043
3044 %code requires @{ #include "type2.h" @}
3045 %union @{ type2 field2; @}
3046 %destructor @{ type2_free ($$); @} <field2>
3047 %printer @{ type2_print ($$); @} <field2>
3048 @end smallexample
3049
3050 @noindent
3051 You could even place each of the above directive groups in the rules section of
3052 the grammar file next to the set of rules that uses the associated semantic
3053 type.
3054 (In the rules section, you must terminate each of those directives with a
3055 semicolon.)
3056 And you don't have to worry that some directive (like a @code{%union}) in the
3057 definitions section is going to adversely affect their functionality in some
3058 counter-intuitive manner just because it comes first.
3059 Such an organization is not possible using @var{Prologue} sections.
3060
3061 This section has been concerned with explaining the advantages of the four
3062 @var{Prologue} alternatives over the original Yacc @var{Prologue}.
3063 However, in most cases when using these directives, you shouldn't need to
3064 think about all the low-level ordering issues discussed here.
3065 Instead, you should simply use these directives to label each block of your
3066 code according to its purpose and let Bison handle the ordering.
3067 @code{%code} is the most generic label.
3068 Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
3069 as needed.
3070
3071 @node Bison Declarations
3072 @subsection The Bison Declarations Section
3073 @cindex Bison declarations (introduction)
3074 @cindex declarations, Bison (introduction)
3075
3076 The @var{Bison declarations} section contains declarations that define
3077 terminal and nonterminal symbols, specify precedence, and so on.
3078 In some simple grammars you may not need any declarations.
3079 @xref{Declarations, ,Bison Declarations}.
3080
3081 @node Grammar Rules
3082 @subsection The Grammar Rules Section
3083 @cindex grammar rules section
3084 @cindex rules section for grammar
3085
3086 The @dfn{grammar rules} section contains one or more Bison grammar
3087 rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
3088
3089 There must always be at least one grammar rule, and the first
3090 @samp{%%} (which precedes the grammar rules) may never be omitted even
3091 if it is the first thing in the file.
3092
3093 @node Epilogue
3094 @subsection The epilogue
3095 @cindex additional C code section
3096 @cindex epilogue
3097 @cindex C code, section for additional
3098
3099 The @var{Epilogue} is copied verbatim to the end of the parser
3100 implementation file, just as the @var{Prologue} is copied to the
3101 beginning. This is the most convenient place to put anything that you
3102 want to have in the parser implementation file but which need not come
3103 before the definition of @code{yyparse}. For example, the definitions
3104 of @code{yylex} and @code{yyerror} often go here. Because C requires
3105 functions to be declared before being used, you often need to declare
3106 functions like @code{yylex} and @code{yyerror} in the Prologue, even
3107 if you define them in the Epilogue. @xref{Interface, ,Parser
3108 C-Language Interface}.
3109
3110 If the last section is empty, you may omit the @samp{%%} that separates it
3111 from the grammar rules.
3112
3113 The Bison parser itself contains many macros and identifiers whose names
3114 start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3115 any such names (except those documented in this manual) in the epilogue
3116 of the grammar file.
3117
3118 @node Symbols
3119 @section Symbols, Terminal and Nonterminal
3120 @cindex nonterminal symbol
3121 @cindex terminal symbol
3122 @cindex token type
3123 @cindex symbol
3124
3125 @dfn{Symbols} in Bison grammars represent the grammatical classifications
3126 of the language.
3127
3128 A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
3129 class of syntactically equivalent tokens. You use the symbol in grammar
3130 rules to mean that a token in that class is allowed. The symbol is
3131 represented in the Bison parser by a numeric code, and the @code{yylex}
3132 function returns a token type code to indicate what kind of token has
3133 been read. You don't need to know what the code value is; you can use
3134 the symbol to stand for it.
3135
3136 A @dfn{nonterminal symbol} stands for a class of syntactically
3137 equivalent groupings. The symbol name is used in writing grammar rules.
3138 By convention, it should be all lower case.
3139
3140 Symbol names can contain letters, underscores, periods, and non-initial
3141 digits and dashes. Dashes in symbol names are a GNU extension, incompatible
3142 with POSIX Yacc. Periods and dashes make symbol names less convenient to
3143 use with named references, which require brackets around such names
3144 (@pxref{Named References}). Terminal symbols that contain periods or dashes
3145 make little sense: since they are not valid symbols (in most programming
3146 languages) they are not exported as token names.
3147
3148 There are three ways of writing terminal symbols in the grammar:
3149
3150 @itemize @bullet
3151 @item
3152 A @dfn{named token type} is written with an identifier, like an
3153 identifier in C@. By convention, it should be all upper case. Each
3154 such name must be defined with a Bison declaration such as
3155 @code{%token}. @xref{Token Decl, ,Token Type Names}.
3156
3157 @item
3158 @cindex character token
3159 @cindex literal token
3160 @cindex single-character literal
3161 A @dfn{character token type} (or @dfn{literal character token}) is
3162 written in the grammar using the same syntax used in C for character
3163 constants; for example, @code{'+'} is a character token type. A
3164 character token type doesn't need to be declared unless you need to
3165 specify its semantic value data type (@pxref{Value Type, ,Data Types of
3166 Semantic Values}), associativity, or precedence (@pxref{Precedence,
3167 ,Operator Precedence}).
3168
3169 By convention, a character token type is used only to represent a
3170 token that consists of that particular character. Thus, the token
3171 type @code{'+'} is used to represent the character @samp{+} as a
3172 token. Nothing enforces this convention, but if you depart from it,
3173 your program will confuse other readers.
3174
3175 All the usual escape sequences used in character literals in C can be
3176 used in Bison as well, but you must not use the null character as a
3177 character literal because its numeric code, zero, signifies
3178 end-of-input (@pxref{Calling Convention, ,Calling Convention
3179 for @code{yylex}}). Also, unlike standard C, trigraphs have no
3180 special meaning in Bison character literals, nor is backslash-newline
3181 allowed.
3182
3183 @item
3184 @cindex string token
3185 @cindex literal string token
3186 @cindex multicharacter literal
3187 A @dfn{literal string token} is written like a C string constant; for
3188 example, @code{"<="} is a literal string token. A literal string token
3189 doesn't need to be declared unless you need to specify its semantic
3190 value data type (@pxref{Value Type}), associativity, or precedence
3191 (@pxref{Precedence}).
3192
3193 You can associate the literal string token with a symbolic name as an
3194 alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
3195 Declarations}). If you don't do that, the lexical analyzer has to
3196 retrieve the token number for the literal string token from the
3197 @code{yytname} table (@pxref{Calling Convention}).
3198
3199 @strong{Warning}: literal string tokens do not work in Yacc.
3200
3201 By convention, a literal string token is used only to represent a token
3202 that consists of that particular string. Thus, you should use the token
3203 type @code{"<="} to represent the string @samp{<=} as a token. Bison
3204 does not enforce this convention, but if you depart from it, people who
3205 read your program will be confused.
3206
3207 All the escape sequences used in string literals in C can be used in
3208 Bison as well, except that you must not use a null character within a
3209 string literal. Also, unlike Standard C, trigraphs have no special
3210 meaning in Bison string literals, nor is backslash-newline allowed. A
3211 literal string token must contain two or more characters; for a token
3212 containing just one character, use a character token (see above).
3213 @end itemize
3214
3215 How you choose to write a terminal symbol has no effect on its
3216 grammatical meaning. That depends only on where it appears in rules and
3217 on when the parser function returns that symbol.
3218
3219 The value returned by @code{yylex} is always one of the terminal
3220 symbols, except that a zero or negative value signifies end-of-input.
3221 Whichever way you write the token type in the grammar rules, you write
3222 it the same way in the definition of @code{yylex}. The numeric code
3223 for a character token type is simply the positive numeric code of the
3224 character, so @code{yylex} can use the identical value to generate the
3225 requisite code, though you may need to convert it to @code{unsigned
3226 char} to avoid sign-extension on hosts where @code{char} is signed.
3227 Each named token type becomes a C macro in the parser implementation
3228 file, so @code{yylex} can use the name to stand for the code. (This
3229 is why periods don't make sense in terminal symbols.) @xref{Calling
3230 Convention, ,Calling Convention for @code{yylex}}.
3231
3232 If @code{yylex} is defined in a separate file, you need to arrange for the
3233 token-type macro definitions to be available there. Use the @samp{-d}
3234 option when you run Bison, so that it will write these macro definitions
3235 into a separate header file @file{@var{name}.tab.h} which you can include
3236 in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
3237
3238 If you want to write a grammar that is portable to any Standard C
3239 host, you must use only nonnull character tokens taken from the basic
3240 execution character set of Standard C@. This set consists of the ten
3241 digits, the 52 lower- and upper-case English letters, and the
3242 characters in the following C-language string:
3243
3244 @example
3245 "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3246 @end example
3247
3248 The @code{yylex} function and Bison must use a consistent character set
3249 and encoding for character tokens. For example, if you run Bison in an
3250 ASCII environment, but then compile and run the resulting
3251 program in an environment that uses an incompatible character set like
3252 EBCDIC, the resulting program may not work because the tables
3253 generated by Bison will assume ASCII numeric values for
3254 character tokens. It is standard practice for software distributions to
3255 contain C source files that were generated by Bison in an
3256 ASCII environment, so installers on platforms that are
3257 incompatible with ASCII must rebuild those files before
3258 compiling them.
3259
3260 The symbol @code{error} is a terminal symbol reserved for error recovery
3261 (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
3262 In particular, @code{yylex} should never return this value. The default
3263 value of the error token is 256, unless you explicitly assigned 256 to
3264 one of your tokens with a @code{%token} declaration.
3265
3266 @node Rules
3267 @section Syntax of Grammar Rules
3268 @cindex rule syntax
3269 @cindex grammar rule syntax
3270 @cindex syntax of grammar rules
3271
3272 A Bison grammar rule has the following general form:
3273
3274 @example
3275 @group
3276 @var{result}: @var{components}@dots{}
3277 ;
3278 @end group
3279 @end example
3280
3281 @noindent
3282 where @var{result} is the nonterminal symbol that this rule describes,
3283 and @var{components} are various terminal and nonterminal symbols that
3284 are put together by this rule (@pxref{Symbols}).
3285
3286 For example,
3287
3288 @example
3289 @group
3290 exp: exp '+' exp
3291 ;
3292 @end group
3293 @end example
3294
3295 @noindent
3296 says that two groupings of type @code{exp}, with a @samp{+} token in between,
3297 can be combined into a larger grouping of type @code{exp}.
3298
3299 White space in rules is significant only to separate symbols. You can add
3300 extra white space as you wish.
3301
3302 Scattered among the components can be @var{actions} that determine
3303 the semantics of the rule. An action looks like this:
3304
3305 @example
3306 @{@var{C statements}@}
3307 @end example
3308
3309 @noindent
3310 @cindex braced code
3311 This is an example of @dfn{braced code}, that is, C code surrounded by
3312 braces, much like a compound statement in C@. Braced code can contain
3313 any sequence of C tokens, so long as its braces are balanced. Bison
3314 does not check the braced code for correctness directly; it merely
3315 copies the code to the parser implementation file, where the C
3316 compiler can check it.
3317
3318 Within braced code, the balanced-brace count is not affected by braces
3319 within comments, string literals, or character constants, but it is
3320 affected by the C digraphs @samp{<%} and @samp{%>} that represent
3321 braces. At the top level braced code must be terminated by @samp{@}}
3322 and not by a digraph. Bison does not look for trigraphs, so if braced
3323 code uses trigraphs you should ensure that they do not affect the
3324 nesting of braces or the boundaries of comments, string literals, or
3325 character constants.
3326
3327 Usually there is only one action and it follows the components.
3328 @xref{Actions}.
3329
3330 @findex |
3331 Multiple rules for the same @var{result} can be written separately or can
3332 be joined with the vertical-bar character @samp{|} as follows:
3333
3334 @example
3335 @group
3336 @var{result}: @var{rule1-components}@dots{}
3337 | @var{rule2-components}@dots{}
3338 @dots{}
3339 ;
3340 @end group
3341 @end example
3342
3343 @noindent
3344 They are still considered distinct rules even when joined in this way.
3345
3346 If @var{components} in a rule is empty, it means that @var{result} can
3347 match the empty string. For example, here is how to define a
3348 comma-separated sequence of zero or more @code{exp} groupings:
3349
3350 @example
3351 @group
3352 expseq: /* empty */
3353 | expseq1
3354 ;
3355 @end group
3356
3357 @group
3358 expseq1: exp
3359 | expseq1 ',' exp
3360 ;
3361 @end group
3362 @end example
3363
3364 @noindent
3365 It is customary to write a comment @samp{/* empty */} in each rule
3366 with no components.
3367
3368 @node Recursion
3369 @section Recursive Rules
3370 @cindex recursive rule
3371
3372 A rule is called @dfn{recursive} when its @var{result} nonterminal
3373 appears also on its right hand side. Nearly all Bison grammars need to
3374 use recursion, because that is the only way to define a sequence of any
3375 number of a particular thing. Consider this recursive definition of a
3376 comma-separated sequence of one or more expressions:
3377
3378 @example
3379 @group
3380 expseq1: exp
3381 | expseq1 ',' exp
3382 ;
3383 @end group
3384 @end example
3385
3386 @cindex left recursion
3387 @cindex right recursion
3388 @noindent
3389 Since the recursive use of @code{expseq1} is the leftmost symbol in the
3390 right hand side, we call this @dfn{left recursion}. By contrast, here
3391 the same construct is defined using @dfn{right recursion}:
3392
3393 @example
3394 @group
3395 expseq1: exp
3396 | exp ',' expseq1
3397 ;
3398 @end group
3399 @end example
3400
3401 @noindent
3402 Any kind of sequence can be defined using either left recursion or right
3403 recursion, but you should always use left recursion, because it can
3404 parse a sequence of any number of elements with bounded stack space.
3405 Right recursion uses up space on the Bison stack in proportion to the
3406 number of elements in the sequence, because all the elements must be
3407 shifted onto the stack before the rule can be applied even once.
3408 @xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
3409 of this.
3410
3411 @cindex mutual recursion
3412 @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3413 rule does not appear directly on its right hand side, but does appear
3414 in rules for other nonterminals which do appear on its right hand
3415 side.
3416
3417 For example:
3418
3419 @example
3420 @group
3421 expr: primary
3422 | primary '+' primary
3423 ;
3424 @end group
3425
3426 @group
3427 primary: constant
3428 | '(' expr ')'
3429 ;
3430 @end group
3431 @end example
3432
3433 @noindent
3434 defines two mutually-recursive nonterminals, since each refers to the
3435 other.
3436
3437 @node Semantics
3438 @section Defining Language Semantics
3439 @cindex defining language semantics
3440 @cindex language semantics, defining
3441
3442 The grammar rules for a language determine only the syntax. The semantics
3443 are determined by the semantic values associated with various tokens and
3444 groupings, and by the actions taken when various groupings are recognized.
3445
3446 For example, the calculator calculates properly because the value
3447 associated with each expression is the proper number; it adds properly
3448 because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3449 the numbers associated with @var{x} and @var{y}.
3450
3451 @menu
3452 * Value Type:: Specifying one data type for all semantic values.
3453 * Multiple Types:: Specifying several alternative data types.
3454 * Actions:: An action is the semantic definition of a grammar rule.
3455 * Action Types:: Specifying data types for actions to operate on.
3456 * Mid-Rule Actions:: Most actions go at the end of a rule.
3457 This says when, why and how to use the exceptional
3458 action in the middle of a rule.
3459 * Named References:: Using named references in actions.
3460 @end menu
3461
3462 @node Value Type
3463 @subsection Data Types of Semantic Values
3464 @cindex semantic value type
3465 @cindex value type, semantic
3466 @cindex data types of semantic values
3467 @cindex default data type
3468
3469 In a simple program it may be sufficient to use the same data type for
3470 the semantic values of all language constructs. This was true in the
3471 RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
3472 Notation Calculator}).
3473
3474 Bison normally uses the type @code{int} for semantic values if your
3475 program uses the same data type for all language constructs. To
3476 specify some other type, define @code{YYSTYPE} as a macro, like this:
3477
3478 @example
3479 #define YYSTYPE double
3480 @end example
3481
3482 @noindent
3483 @code{YYSTYPE}'s replacement list should be a type name
3484 that does not contain parentheses or square brackets.
3485 This macro definition must go in the prologue of the grammar file
3486 (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
3487
3488 @node Multiple Types
3489 @subsection More Than One Value Type
3490
3491 In most programs, you will need different data types for different kinds
3492 of tokens and groupings. For example, a numeric constant may need type
3493 @code{int} or @code{long int}, while a string constant needs type
3494 @code{char *}, and an identifier might need a pointer to an entry in the
3495 symbol table.
3496
3497 To use more than one data type for semantic values in one parser, Bison
3498 requires you to do two things:
3499
3500 @itemize @bullet
3501 @item
3502 Specify the entire collection of possible data types, either by using the
3503 @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
3504 Value Types}), or by using a @code{typedef} or a @code{#define} to
3505 define @code{YYSTYPE} to be a union type whose member names are
3506 the type tags.
3507
3508 @item
3509 Choose one of those types for each symbol (terminal or nonterminal) for
3510 which semantic values are used. This is done for tokens with the
3511 @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
3512 and for groupings with the @code{%type} Bison declaration (@pxref{Type
3513 Decl, ,Nonterminal Symbols}).
3514 @end itemize
3515
3516 @node Actions
3517 @subsection Actions
3518 @cindex action
3519 @vindex $$
3520 @vindex $@var{n}
3521 @vindex $@var{name}
3522 @vindex $[@var{name}]
3523
3524 An action accompanies a syntactic rule and contains C code to be executed
3525 each time an instance of that rule is recognized. The task of most actions
3526 is to compute a semantic value for the grouping built by the rule from the
3527 semantic values associated with tokens or smaller groupings.
3528
3529 An action consists of braced code containing C statements, and can be
3530 placed at any position in the rule;
3531 it is executed at that position. Most rules have just one action at the
3532 end of the rule, following all the components. Actions in the middle of
3533 a rule are tricky and used only for special purposes (@pxref{Mid-Rule
3534 Actions, ,Actions in Mid-Rule}).
3535
3536 The C code in an action can refer to the semantic values of the
3537 components matched by the rule with the construct @code{$@var{n}},
3538 which stands for the value of the @var{n}th component. The semantic
3539 value for the grouping being constructed is @code{$$}. In addition,
3540 the semantic values of symbols can be accessed with the named
3541 references construct @code{$@var{name}} or @code{$[@var{name}]}.
3542 Bison translates both of these constructs into expressions of the
3543 appropriate type when it copies the actions into the parser
3544 implementation file. @code{$$} (or @code{$@var{name}}, when it stands
3545 for the current grouping) is translated to a modifiable lvalue, so it
3546 can be assigned to.
3547
3548 Here is a typical example:
3549
3550 @example
3551 @group
3552 exp: @dots{}
3553 | exp '+' exp
3554 @{ $$ = $1 + $3; @}
3555 @end group
3556 @end example
3557
3558 Or, in terms of named references:
3559
3560 @example
3561 @group
3562 exp[result]: @dots{}
3563 | exp[left] '+' exp[right]
3564 @{ $result = $left + $right; @}
3565 @end group
3566 @end example
3567
3568 @noindent
3569 This rule constructs an @code{exp} from two smaller @code{exp} groupings
3570 connected by a plus-sign token. In the action, @code{$1} and @code{$3}
3571 (@code{$left} and @code{$right})
3572 refer to the semantic values of the two component @code{exp} groupings,
3573 which are the first and third symbols on the right hand side of the rule.
3574 The sum is stored into @code{$$} (@code{$result}) so that it becomes the
3575 semantic value of
3576 the addition-expression just recognized by the rule. If there were a
3577 useful semantic value associated with the @samp{+} token, it could be
3578 referred to as @code{$2}.
3579
3580 @xref{Named References,,Using Named References}, for more information
3581 about using the named references construct.
3582
3583 Note that the vertical-bar character @samp{|} is really a rule
3584 separator, and actions are attached to a single rule. This is a
3585 difference with tools like Flex, for which @samp{|} stands for either
3586 ``or'', or ``the same action as that of the next rule''. In the
3587 following example, the action is triggered only when @samp{b} is found:
3588
3589 @example
3590 @group
3591 a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
3592 @end group
3593 @end example
3594
3595 @cindex default action
3596 If you don't specify an action for a rule, Bison supplies a default:
3597 @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule
3598 becomes the value of the whole rule. Of course, the default action is
3599 valid only if the two data types match. There is no meaningful default
3600 action for an empty rule; every empty rule must have an explicit action
3601 unless the rule's value does not matter.
3602
3603 @code{$@var{n}} with @var{n} zero or negative is allowed for reference
3604 to tokens and groupings on the stack @emph{before} those that match the
3605 current rule. This is a very risky practice, and to use it reliably
3606 you must be certain of the context in which the rule is applied. Here
3607 is a case in which you can use this reliably:
3608
3609 @example
3610 @group
3611 foo: expr bar '+' expr @{ @dots{} @}
3612 | expr bar '-' expr @{ @dots{} @}
3613 ;
3614 @end group
3615
3616 @group
3617 bar: /* empty */
3618 @{ previous_expr = $0; @}
3619 ;
3620 @end group
3621 @end example
3622
3623 As long as @code{bar} is used only in the fashion shown here, @code{$0}
3624 always refers to the @code{expr} which precedes @code{bar} in the
3625 definition of @code{foo}.
3626
3627 @vindex yylval
3628 It is also possible to access the semantic value of the lookahead token, if
3629 any, from a semantic action.
3630 This semantic value is stored in @code{yylval}.
3631 @xref{Action Features, ,Special Features for Use in Actions}.
3632
3633 @node Action Types
3634 @subsection Data Types of Values in Actions
3635 @cindex action data types
3636 @cindex data types in actions
3637
3638 If you have chosen a single data type for semantic values, the @code{$$}
3639 and @code{$@var{n}} constructs always have that data type.
3640
3641 If you have used @code{%union} to specify a variety of data types, then you
3642 must declare a choice among these types for each terminal or nonterminal
3643 symbol that can have a semantic value. Then each time you use @code{$$} or
3644 @code{$@var{n}}, its data type is determined by which symbol it refers to
3645 in the rule. In this example,
3646
3647 @example
3648 @group
3649 exp: @dots{}
3650 | exp '+' exp
3651 @{ $$ = $1 + $3; @}
3652 @end group
3653 @end example
3654
3655 @noindent
3656 @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
3657 have the data type declared for the nonterminal symbol @code{exp}. If
3658 @code{$2} were used, it would have the data type declared for the
3659 terminal symbol @code{'+'}, whatever that might be.
3660
3661 Alternatively, you can specify the data type when you refer to the value,
3662 by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
3663 reference. For example, if you have defined types as shown here:
3664
3665 @example
3666 @group
3667 %union @{
3668 int itype;
3669 double dtype;
3670 @}
3671 @end group
3672 @end example
3673
3674 @noindent
3675 then you can write @code{$<itype>1} to refer to the first subunit of the
3676 rule as an integer, or @code{$<dtype>1} to refer to it as a double.
3677
3678 @node Mid-Rule Actions
3679 @subsection Actions in Mid-Rule
3680 @cindex actions in mid-rule
3681 @cindex mid-rule actions
3682
3683 Occasionally it is useful to put an action in the middle of a rule.
3684 These actions are written just like usual end-of-rule actions, but they
3685 are executed before the parser even recognizes the following components.
3686
3687 A mid-rule action may refer to the components preceding it using
3688 @code{$@var{n}}, but it may not refer to subsequent components because
3689 it is run before they are parsed.
3690
3691 The mid-rule action itself counts as one of the components of the rule.
3692 This makes a difference when there is another action later in the same rule
3693 (and usually there is another at the end): you have to count the actions
3694 along with the symbols when working out which number @var{n} to use in
3695 @code{$@var{n}}.
3696
3697 The mid-rule action can also have a semantic value. The action can set
3698 its value with an assignment to @code{$$}, and actions later in the rule
3699 can refer to the value using @code{$@var{n}}. Since there is no symbol
3700 to name the action, there is no way to declare a data type for the value
3701 in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
3702 specify a data type each time you refer to this value.
3703
3704 There is no way to set the value of the entire rule with a mid-rule
3705 action, because assignments to @code{$$} do not have that effect. The
3706 only way to set the value for the entire rule is with an ordinary action
3707 at the end of the rule.
3708
3709 Here is an example from a hypothetical compiler, handling a @code{let}
3710 statement that looks like @samp{let (@var{variable}) @var{statement}} and
3711 serves to create a variable named @var{variable} temporarily for the
3712 duration of @var{statement}. To parse this construct, we must put
3713 @var{variable} into the symbol table while @var{statement} is parsed, then
3714 remove it afterward. Here is how it is done:
3715
3716 @example
3717 @group
3718 stmt: LET '(' var ')'
3719 @{ $<context>$ = push_context ();
3720 declare_variable ($3); @}
3721 stmt @{ $$ = $6;
3722 pop_context ($<context>5); @}
3723 @end group
3724 @end example
3725
3726 @noindent
3727 As soon as @samp{let (@var{variable})} has been recognized, the first
3728 action is run. It saves a copy of the current semantic context (the
3729 list of accessible variables) as its semantic value, using alternative
3730 @code{context} in the data-type union. Then it calls
3731 @code{declare_variable} to add the new variable to that list. Once the
3732 first action is finished, the embedded statement @code{stmt} can be
3733 parsed. Note that the mid-rule action is component number 5, so the
3734 @samp{stmt} is component number 6.
3735
3736 After the embedded statement is parsed, its semantic value becomes the
3737 value of the entire @code{let}-statement. Then the semantic value from the
3738 earlier action is used to restore the prior list of variables. This
3739 removes the temporary @code{let}-variable from the list so that it won't
3740 appear to exist while the rest of the program is parsed.
3741
3742 @findex %destructor
3743 @cindex discarded symbols, mid-rule actions
3744 @cindex error recovery, mid-rule actions
3745 In the above example, if the parser initiates error recovery (@pxref{Error
3746 Recovery}) while parsing the tokens in the embedded statement @code{stmt},
3747 it might discard the previous semantic context @code{$<context>5} without
3748 restoring it.
3749 Thus, @code{$<context>5} needs a destructor (@pxref{Destructor Decl, , Freeing
3750 Discarded Symbols}).
3751 However, Bison currently provides no means to declare a destructor specific to
3752 a particular mid-rule action's semantic value.
3753
3754 One solution is to bury the mid-rule action inside a nonterminal symbol and to
3755 declare a destructor for that symbol:
3756
3757 @example
3758 @group
3759 %type <context> let
3760 %destructor @{ pop_context ($$); @} let
3761
3762 %%
3763
3764 stmt: let stmt
3765 @{ $$ = $2;
3766 pop_context ($1); @}
3767 ;
3768
3769 let: LET '(' var ')'
3770 @{ $$ = push_context ();
3771 declare_variable ($3); @}
3772 ;
3773
3774 @end group
3775 @end example
3776
3777 @noindent
3778 Note that the action is now at the end of its rule.
3779 Any mid-rule action can be converted to an end-of-rule action in this way, and
3780 this is what Bison actually does to implement mid-rule actions.
3781
3782 Taking action before a rule is completely recognized often leads to
3783 conflicts since the parser must commit to a parse in order to execute the
3784 action. For example, the following two rules, without mid-rule actions,
3785 can coexist in a working parser because the parser can shift the open-brace
3786 token and look at what follows before deciding whether there is a
3787 declaration or not:
3788
3789 @example
3790 @group
3791 compound: '@{' declarations statements '@}'
3792 | '@{' statements '@}'
3793 ;
3794 @end group
3795 @end example
3796
3797 @noindent
3798 But when we add a mid-rule action as follows, the rules become nonfunctional:
3799
3800 @example
3801 @group
3802 compound: @{ prepare_for_local_variables (); @}
3803 '@{' declarations statements '@}'
3804 @end group
3805 @group
3806 | '@{' statements '@}'
3807 ;
3808 @end group
3809 @end example
3810
3811 @noindent
3812 Now the parser is forced to decide whether to run the mid-rule action
3813 when it has read no farther than the open-brace. In other words, it
3814 must commit to using one rule or the other, without sufficient
3815 information to do it correctly. (The open-brace token is what is called
3816 the @dfn{lookahead} token at this time, since the parser is still
3817 deciding what to do about it. @xref{Lookahead, ,Lookahead Tokens}.)
3818
3819 You might think that you could correct the problem by putting identical
3820 actions into the two rules, like this:
3821
3822 @example
3823 @group
3824 compound: @{ prepare_for_local_variables (); @}
3825 '@{' declarations statements '@}'
3826 | @{ prepare_for_local_variables (); @}
3827 '@{' statements '@}'
3828 ;
3829 @end group
3830 @end example
3831
3832 @noindent
3833 But this does not help, because Bison does not realize that the two actions
3834 are identical. (Bison never tries to understand the C code in an action.)
3835
3836 If the grammar is such that a declaration can be distinguished from a
3837 statement by the first token (which is true in C), then one solution which
3838 does work is to put the action after the open-brace, like this:
3839
3840 @example
3841 @group
3842 compound: '@{' @{ prepare_for_local_variables (); @}
3843 declarations statements '@}'
3844 | '@{' statements '@}'
3845 ;
3846 @end group
3847 @end example
3848
3849 @noindent
3850 Now the first token of the following declaration or statement,
3851 which would in any case tell Bison which rule to use, can still do so.
3852
3853 Another solution is to bury the action inside a nonterminal symbol which
3854 serves as a subroutine:
3855
3856 @example
3857 @group
3858 subroutine: /* empty */
3859 @{ prepare_for_local_variables (); @}
3860 ;
3861
3862 @end group
3863
3864 @group
3865 compound: subroutine
3866 '@{' declarations statements '@}'
3867 | subroutine
3868 '@{' statements '@}'
3869 ;
3870 @end group
3871 @end example
3872
3873 @noindent
3874 Now Bison can execute the action in the rule for @code{subroutine} without
3875 deciding which rule for @code{compound} it will eventually use.
3876
3877 @node Named References
3878 @subsection Using Named References
3879 @cindex named references
3880
3881 While every semantic value can be accessed with positional references
3882 @code{$@var{n}} and @code{$$}, it's often much more convenient to refer to
3883 them by name. First of all, original symbol names may be used as named
3884 references. For example:
3885
3886 @example
3887 @group
3888 invocation: op '(' args ')'
3889 @{ $invocation = new_invocation ($op, $args, @@invocation); @}
3890 @end group
3891 @end example
3892
3893 @noindent
3894 The positional @code{$$}, @code{@@$}, @code{$n}, and @code{@@n} can be
3895 mixed with @code{$name} and @code{@@name} arbitrarily. For example:
3896
3897 @example
3898 @group
3899 invocation: op '(' args ')'
3900 @{ $$ = new_invocation ($op, $args, @@$); @}
3901 @end group
3902 @end example
3903
3904 @noindent
3905 However, sometimes regular symbol names are not sufficient due to
3906 ambiguities:
3907
3908 @example
3909 @group
3910 exp: exp '/' exp
3911 @{ $exp = $exp / $exp; @} // $exp is ambiguous.
3912
3913 exp: exp '/' exp
3914 @{ $$ = $1 / $exp; @} // One usage is ambiguous.
3915
3916 exp: exp '/' exp
3917 @{ $$ = $1 / $3; @} // No error.
3918 @end group
3919 @end example
3920
3921 @noindent
3922 When ambiguity occurs, explicitly declared names may be used for values and
3923 locations. Explicit names are declared as a bracketed name after a symbol
3924 appearance in rule definitions. For example:
3925 @example
3926 @group
3927 exp[result]: exp[left] '/' exp[right]
3928 @{ $result = $left / $right; @}
3929 @end group
3930 @end example
3931
3932 @noindent
3933 Explicit names may be declared for RHS and for LHS symbols as well. In order
3934 to access a semantic value generated by a mid-rule action, an explicit name
3935 may also be declared by putting a bracketed name after the closing brace of
3936 the mid-rule action code:
3937 @example
3938 @group
3939 exp[res]: exp[x] '+' @{$left = $x;@}[left] exp[right]
3940 @{ $res = $left + $right; @}
3941 @end group
3942 @end example
3943
3944 @noindent
3945
3946 In references, in order to specify names containing dots and dashes, an explicit
3947 bracketed syntax @code{$[name]} and @code{@@[name]} must be used:
3948 @example
3949 @group
3950 if-stmt: IF '(' expr ')' THEN then.stmt ';'
3951 @{ $[if-stmt] = new_if_stmt ($expr, $[then.stmt]); @}
3952 @end group
3953 @end example
3954
3955 It often happens that named references are followed by a dot, dash or other
3956 C punctuation marks and operators. By default, Bison will read
3957 @code{$name.suffix} as a reference to symbol value @code{$name} followed by
3958 @samp{.suffix}, i.e., an access to the @samp{suffix} field of the semantic
3959 value. In order to force Bison to recognize @code{name.suffix} in its entirety
3960 as the name of a semantic value, bracketed syntax @code{$[name.suffix]}
3961 must be used.
3962
3963
3964 @node Locations
3965 @section Tracking Locations
3966 @cindex location
3967 @cindex textual location
3968 @cindex location, textual
3969
3970 Though grammar rules and semantic actions are enough to write a fully
3971 functional parser, it can be useful to process some additional information,
3972 especially symbol locations.
3973
3974 The way locations are handled is defined by providing a data type, and
3975 actions to take when rules are matched.
3976
3977 @menu
3978 * Location Type:: Specifying a data type for locations.
3979 * Actions and Locations:: Using locations in actions.
3980 * Location Default Action:: Defining a general way to compute locations.
3981 @end menu
3982
3983 @node Location Type
3984 @subsection Data Type of Locations
3985 @cindex data type of locations
3986 @cindex default location type
3987
3988 Defining a data type for locations is much simpler than for semantic values,
3989 since all tokens and groupings always use the same type.
3990
3991 You can specify the type of locations by defining a macro called
3992 @code{YYLTYPE}, just as you can specify the semantic value type by
3993 defining a @code{YYSTYPE} macro (@pxref{Value Type}).
3994 When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3995 four members:
3996
3997 @example
3998 typedef struct YYLTYPE
3999 @{
4000 int first_line;
4001 int first_column;
4002 int last_line;
4003 int last_column;
4004 @} YYLTYPE;
4005 @end example
4006
4007 When @code{YYLTYPE} is not defined, at the beginning of the parsing, Bison
4008 initializes all these fields to 1 for @code{yylloc}. To initialize
4009 @code{yylloc} with a custom location type (or to chose a different
4010 initialization), use the @code{%initial-action} directive. @xref{Initial
4011 Action Decl, , Performing Actions before Parsing}.
4012
4013 @node Actions and Locations
4014 @subsection Actions and Locations
4015 @cindex location actions
4016 @cindex actions, location
4017 @vindex @@$
4018 @vindex @@@var{n}
4019 @vindex @@@var{name}
4020 @vindex @@[@var{name}]
4021
4022 Actions are not only useful for defining language semantics, but also for
4023 describing the behavior of the output parser with locations.
4024
4025 The most obvious way for building locations of syntactic groupings is very
4026 similar to the way semantic values are computed. In a given rule, several
4027 constructs can be used to access the locations of the elements being matched.
4028 The location of the @var{n}th component of the right hand side is
4029 @code{@@@var{n}}, while the location of the left hand side grouping is
4030 @code{@@$}.
4031
4032 In addition, the named references construct @code{@@@var{name}} and
4033 @code{@@[@var{name}]} may also be used to address the symbol locations.
4034 @xref{Named References,,Using Named References}, for more information
4035 about using the named references construct.
4036
4037 Here is a basic example using the default data type for locations:
4038
4039 @example
4040 @group
4041 exp: @dots{}
4042 | exp '/' exp
4043 @{
4044 @@$.first_column = @@1.first_column;
4045 @@$.first_line = @@1.first_line;
4046 @@$.last_column = @@3.last_column;
4047 @@$.last_line = @@3.last_line;
4048 if ($3)
4049 $$ = $1 / $3;
4050 else
4051 @{
4052 $$ = 1;
4053 fprintf (stderr,
4054 "Division by zero, l%d,c%d-l%d,c%d",
4055 @@3.first_line, @@3.first_column,
4056 @@3.last_line, @@3.last_column);
4057 @}
4058 @}
4059 @end group
4060 @end example
4061
4062 As for semantic values, there is a default action for locations that is
4063 run each time a rule is matched. It sets the beginning of @code{@@$} to the
4064 beginning of the first symbol, and the end of @code{@@$} to the end of the
4065 last symbol.
4066
4067 With this default action, the location tracking can be fully automatic. The
4068 example above simply rewrites this way:
4069
4070 @example
4071 @group
4072 exp: @dots{}
4073 | exp '/' exp
4074 @{
4075 if ($3)
4076 $$ = $1 / $3;
4077 else
4078 @{
4079 $$ = 1;
4080 fprintf (stderr,
4081 "Division by zero, l%d,c%d-l%d,c%d",
4082 @@3.first_line, @@3.first_column,
4083 @@3.last_line, @@3.last_column);
4084 @}
4085 @}
4086 @end group
4087 @end example
4088
4089 @vindex yylloc
4090 It is also possible to access the location of the lookahead token, if any,
4091 from a semantic action.
4092 This location is stored in @code{yylloc}.
4093 @xref{Action Features, ,Special Features for Use in Actions}.
4094
4095 @node Location Default Action
4096 @subsection Default Action for Locations
4097 @vindex YYLLOC_DEFAULT
4098 @cindex GLR parsers and @code{YYLLOC_DEFAULT}
4099
4100 Actually, actions are not the best place to compute locations. Since
4101 locations are much more general than semantic values, there is room in
4102 the output parser to redefine the default action to take for each
4103 rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
4104 matched, before the associated action is run. It is also invoked
4105 while processing a syntax error, to compute the error's location.
4106 Before reporting an unresolvable syntactic ambiguity, a GLR
4107 parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
4108 of that ambiguity.
4109
4110 Most of the time, this macro is general enough to suppress location
4111 dedicated code from semantic actions.
4112
4113 The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
4114 the location of the grouping (the result of the computation). When a
4115 rule is matched, the second parameter identifies locations of
4116 all right hand side elements of the rule being matched, and the third
4117 parameter is the size of the rule's right hand side.
4118 When a GLR parser reports an ambiguity, which of multiple candidate
4119 right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
4120 When processing a syntax error, the second parameter identifies locations
4121 of the symbols that were discarded during error processing, and the third
4122 parameter is the number of discarded symbols.
4123
4124 By default, @code{YYLLOC_DEFAULT} is defined this way:
4125
4126 @smallexample
4127 @group
4128 # define YYLLOC_DEFAULT(Current, Rhs, N) \
4129 do \
4130 if (N) \
4131 @{ \
4132 (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
4133 (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
4134 (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
4135 (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
4136 @} \
4137 else \
4138 @{ \
4139 (Current).first_line = (Current).last_line = \
4140 YYRHSLOC(Rhs, 0).last_line; \
4141 (Current).first_column = (Current).last_column = \
4142 YYRHSLOC(Rhs, 0).last_column; \
4143 @} \
4144 while (0)
4145 @end group
4146 @end smallexample
4147
4148 where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
4149 in @var{rhs} when @var{k} is positive, and the location of the symbol
4150 just before the reduction when @var{k} and @var{n} are both zero.
4151
4152 When defining @code{YYLLOC_DEFAULT}, you should consider that:
4153
4154 @itemize @bullet
4155 @item
4156 All arguments are free of side-effects. However, only the first one (the
4157 result) should be modified by @code{YYLLOC_DEFAULT}.
4158
4159 @item
4160 For consistency with semantic actions, valid indexes within the
4161 right hand side range from 1 to @var{n}. When @var{n} is zero, only 0 is a
4162 valid index, and it refers to the symbol just before the reduction.
4163 During error processing @var{n} is always positive.
4164
4165 @item
4166 Your macro should parenthesize its arguments, if need be, since the
4167 actual arguments may not be surrounded by parentheses. Also, your
4168 macro should expand to something that can be used as a single
4169 statement when it is followed by a semicolon.
4170 @end itemize
4171
4172 @node Declarations
4173 @section Bison Declarations
4174 @cindex declarations, Bison
4175 @cindex Bison declarations
4176
4177 The @dfn{Bison declarations} section of a Bison grammar defines the symbols
4178 used in formulating the grammar and the data types of semantic values.
4179 @xref{Symbols}.
4180
4181 All token type names (but not single-character literal tokens such as
4182 @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
4183 declared if you need to specify which data type to use for the semantic
4184 value (@pxref{Multiple Types, ,More Than One Value Type}).
4185
4186 The first rule in the grammar file also specifies the start symbol, by
4187 default. If you want some other symbol to be the start symbol, you
4188 must declare it explicitly (@pxref{Language and Grammar, ,Languages
4189 and Context-Free Grammars}).
4190
4191 @menu
4192 * Require Decl:: Requiring a Bison version.
4193 * Token Decl:: Declaring terminal symbols.
4194 * Precedence Decl:: Declaring terminals with precedence and associativity.
4195 * Union Decl:: Declaring the set of all semantic value types.
4196 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
4197 * Initial Action Decl:: Code run before parsing starts.
4198 * Destructor Decl:: Declaring how symbols are freed.
4199 * Expect Decl:: Suppressing warnings about parsing conflicts.
4200 * Start Decl:: Specifying the start symbol.
4201 * Pure Decl:: Requesting a reentrant parser.
4202 * Push Decl:: Requesting a push parser.
4203 * Decl Summary:: Table of all Bison declarations.
4204 * %define Summary:: Defining variables to adjust Bison's behavior.
4205 * %code Summary:: Inserting code into the parser source.
4206 @end menu
4207
4208 @node Require Decl
4209 @subsection Require a Version of Bison
4210 @cindex version requirement
4211 @cindex requiring a version of Bison
4212 @findex %require
4213
4214 You may require the minimum version of Bison to process the grammar. If
4215 the requirement is not met, @command{bison} exits with an error (exit
4216 status 63).
4217
4218 @example
4219 %require "@var{version}"
4220 @end example
4221
4222 @node Token Decl
4223 @subsection Token Type Names
4224 @cindex declaring token type names
4225 @cindex token type names, declaring
4226 @cindex declaring literal string tokens
4227 @findex %token
4228
4229 The basic way to declare a token type name (terminal symbol) is as follows:
4230
4231 @example
4232 %token @var{name}
4233 @end example
4234
4235 Bison will convert this into a @code{#define} directive in
4236 the parser, so that the function @code{yylex} (if it is in this file)
4237 can use the name @var{name} to stand for this token type's code.
4238
4239 Alternatively, you can use @code{%left}, @code{%right},
4240 @code{%precedence}, or
4241 @code{%nonassoc} instead of @code{%token}, if you wish to specify
4242 associativity and precedence. @xref{Precedence Decl, ,Operator
4243 Precedence}.
4244
4245 You can explicitly specify the numeric code for a token type by appending
4246 a nonnegative decimal or hexadecimal integer value in the field immediately
4247 following the token name:
4248
4249 @example
4250 %token NUM 300
4251 %token XNUM 0x12d // a GNU extension
4252 @end example
4253
4254 @noindent
4255 It is generally best, however, to let Bison choose the numeric codes for
4256 all token types. Bison will automatically select codes that don't conflict
4257 with each other or with normal characters.
4258
4259 In the event that the stack type is a union, you must augment the
4260 @code{%token} or other token declaration to include the data type
4261 alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
4262 Than One Value Type}).
4263
4264 For example:
4265
4266 @example
4267 @group
4268 %union @{ /* define stack type */
4269 double val;
4270 symrec *tptr;
4271 @}
4272 %token <val> NUM /* define token NUM and its type */
4273 @end group
4274 @end example
4275
4276 You can associate a literal string token with a token type name by
4277 writing the literal string at the end of a @code{%token}
4278 declaration which declares the name. For example:
4279
4280 @example
4281 %token arrow "=>"
4282 @end example
4283
4284 @noindent
4285 For example, a grammar for the C language might specify these names with
4286 equivalent literal string tokens:
4287
4288 @example
4289 %token <operator> OR "||"
4290 %token <operator> LE 134 "<="
4291 %left OR "<="
4292 @end example
4293
4294 @noindent
4295 Once you equate the literal string and the token name, you can use them
4296 interchangeably in further declarations or the grammar rules. The
4297 @code{yylex} function can use the token name or the literal string to
4298 obtain the token type code number (@pxref{Calling Convention}).
4299 Syntax error messages passed to @code{yyerror} from the parser will reference
4300 the literal string instead of the token name.
4301
4302 The token numbered as 0 corresponds to end of file; the following line
4303 allows for nicer error messages referring to ``end of file'' instead
4304 of ``$end'':
4305
4306 @example
4307 %token END 0 "end of file"
4308 @end example
4309
4310 @node Precedence Decl
4311 @subsection Operator Precedence
4312 @cindex precedence declarations
4313 @cindex declaring operator precedence
4314 @cindex operator precedence, declaring
4315
4316 Use the @code{%left}, @code{%right}, @code{%nonassoc}, or
4317 @code{%precedence} declaration to
4318 declare a token and specify its precedence and associativity, all at
4319 once. These are called @dfn{precedence declarations}.
4320 @xref{Precedence, ,Operator Precedence}, for general information on
4321 operator precedence.
4322
4323 The syntax of a precedence declaration is nearly the same as that of
4324 @code{%token}: either
4325
4326 @example
4327 %left @var{symbols}@dots{}
4328 @end example
4329
4330 @noindent
4331 or
4332
4333 @example
4334 %left <@var{type}> @var{symbols}@dots{}
4335 @end example
4336
4337 And indeed any of these declarations serves the purposes of @code{%token}.
4338 But in addition, they specify the associativity and relative precedence for
4339 all the @var{symbols}:
4340
4341 @itemize @bullet
4342 @item
4343 The associativity of an operator @var{op} determines how repeated uses
4344 of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
4345 @var{z}} is parsed by grouping @var{x} with @var{y} first or by
4346 grouping @var{y} with @var{z} first. @code{%left} specifies
4347 left-associativity (grouping @var{x} with @var{y} first) and
4348 @code{%right} specifies right-associativity (grouping @var{y} with
4349 @var{z} first). @code{%nonassoc} specifies no associativity, which
4350 means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
4351 considered a syntax error.
4352
4353 @code{%precedence} gives only precedence to the @var{symbols}, and
4354 defines no associativity at all. Use this to define precedence only,
4355 and leave any potential conflict due to associativity enabled.
4356
4357 @item
4358 The precedence of an operator determines how it nests with other operators.
4359 All the tokens declared in a single precedence declaration have equal
4360 precedence and nest together according to their associativity.
4361 When two tokens declared in different precedence declarations associate,
4362 the one declared later has the higher precedence and is grouped first.
4363 @end itemize
4364
4365 For backward compatibility, there is a confusing difference between the
4366 argument lists of @code{%token} and precedence declarations.
4367 Only a @code{%token} can associate a literal string with a token type name.
4368 A precedence declaration always interprets a literal string as a reference to a
4369 separate token.
4370 For example:
4371
4372 @example
4373 %left OR "<=" // Does not declare an alias.
4374 %left OR 134 "<=" 135 // Declares 134 for OR and 135 for "<=".
4375 @end example
4376
4377 @node Union Decl
4378 @subsection The Collection of Value Types
4379 @cindex declaring value types
4380 @cindex value types, declaring
4381 @findex %union
4382
4383 The @code{%union} declaration specifies the entire collection of
4384 possible data types for semantic values. The keyword @code{%union} is
4385 followed by braced code containing the same thing that goes inside a
4386 @code{union} in C@.
4387
4388 For example:
4389
4390 @example
4391 @group
4392 %union @{
4393 double val;
4394 symrec *tptr;
4395 @}
4396 @end group
4397 @end example
4398
4399 @noindent
4400 This says that the two alternative types are @code{double} and @code{symrec
4401 *}. They are given names @code{val} and @code{tptr}; these names are used
4402 in the @code{%token} and @code{%type} declarations to pick one of the types
4403 for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
4404
4405 As an extension to POSIX, a tag is allowed after the
4406 @code{union}. For example:
4407
4408 @example
4409 @group
4410 %union value @{
4411 double val;
4412 symrec *tptr;
4413 @}
4414 @end group
4415 @end example
4416
4417 @noindent
4418 specifies the union tag @code{value}, so the corresponding C type is
4419 @code{union value}. If you do not specify a tag, it defaults to
4420 @code{YYSTYPE}.
4421
4422 As another extension to POSIX, you may specify multiple
4423 @code{%union} declarations; their contents are concatenated. However,
4424 only the first @code{%union} declaration can specify a tag.
4425
4426 Note that, unlike making a @code{union} declaration in C, you need not write
4427 a semicolon after the closing brace.
4428
4429 Instead of @code{%union}, you can define and use your own union type
4430 @code{YYSTYPE} if your grammar contains at least one
4431 @samp{<@var{type}>} tag. For example, you can put the following into
4432 a header file @file{parser.h}:
4433
4434 @example
4435 @group
4436 union YYSTYPE @{
4437 double val;
4438 symrec *tptr;
4439 @};
4440 typedef union YYSTYPE YYSTYPE;
4441 @end group
4442 @end example
4443
4444 @noindent
4445 and then your grammar can use the following
4446 instead of @code{%union}:
4447
4448 @example
4449 @group
4450 %@{
4451 #include "parser.h"
4452 %@}
4453 %type <val> expr
4454 %token <tptr> ID
4455 @end group
4456 @end example
4457
4458 @node Type Decl
4459 @subsection Nonterminal Symbols
4460 @cindex declaring value types, nonterminals
4461 @cindex value types, nonterminals, declaring
4462 @findex %type
4463
4464 @noindent
4465 When you use @code{%union} to specify multiple value types, you must
4466 declare the value type of each nonterminal symbol for which values are
4467 used. This is done with a @code{%type} declaration, like this:
4468
4469 @example
4470 %type <@var{type}> @var{nonterminal}@dots{}
4471 @end example
4472
4473 @noindent
4474 Here @var{nonterminal} is the name of a nonterminal symbol, and
4475 @var{type} is the name given in the @code{%union} to the alternative
4476 that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
4477 can give any number of nonterminal symbols in the same @code{%type}
4478 declaration, if they have the same value type. Use spaces to separate
4479 the symbol names.
4480
4481 You can also declare the value type of a terminal symbol. To do this,
4482 use the same @code{<@var{type}>} construction in a declaration for the
4483 terminal symbol. All kinds of token declarations allow
4484 @code{<@var{type}>}.
4485
4486 @node Initial Action Decl
4487 @subsection Performing Actions before Parsing
4488 @findex %initial-action
4489
4490 Sometimes your parser needs to perform some initializations before
4491 parsing. The @code{%initial-action} directive allows for such arbitrary
4492 code.
4493
4494 @deffn {Directive} %initial-action @{ @var{code} @}
4495 @findex %initial-action
4496 Declare that the braced @var{code} must be invoked before parsing each time
4497 @code{yyparse} is called. The @var{code} may use @code{$$} and
4498 @code{@@$} --- initial value and location of the lookahead --- and the
4499 @code{%parse-param}.
4500 @end deffn
4501
4502 For instance, if your locations use a file name, you may use
4503
4504 @example
4505 %parse-param @{ char const *file_name @};
4506 %initial-action
4507 @{
4508 @@$.initialize (file_name);
4509 @};
4510 @end example
4511
4512
4513 @node Destructor Decl
4514 @subsection Freeing Discarded Symbols
4515 @cindex freeing discarded symbols
4516 @findex %destructor
4517 @findex <*>
4518 @findex <>
4519 During error recovery (@pxref{Error Recovery}), symbols already pushed
4520 on the stack and tokens coming from the rest of the file are discarded
4521 until the parser falls on its feet. If the parser runs out of memory,
4522 or if it returns via @code{YYABORT} or @code{YYACCEPT}, all the
4523 symbols on the stack must be discarded. Even if the parser succeeds, it
4524 must discard the start symbol.
4525
4526 When discarded symbols convey heap based information, this memory is
4527 lost. While this behavior can be tolerable for batch parsers, such as
4528 in traditional compilers, it is unacceptable for programs like shells or
4529 protocol implementations that may parse and execute indefinitely.
4530
4531 The @code{%destructor} directive defines code that is called when a
4532 symbol is automatically discarded.
4533
4534 @deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
4535 @findex %destructor
4536 Invoke the braced @var{code} whenever the parser discards one of the
4537 @var{symbols}.
4538 Within @var{code}, @code{$$} designates the semantic value associated
4539 with the discarded symbol, and @code{@@$} designates its location.
4540 The additional parser parameters are also available (@pxref{Parser Function, ,
4541 The Parser Function @code{yyparse}}).
4542
4543 When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
4544 per-symbol @code{%destructor}.
4545 You may also define a per-type @code{%destructor} by listing a semantic type
4546 tag among @var{symbols}.
4547 In that case, the parser will invoke this @var{code} whenever it discards any
4548 grammar symbol that has that semantic type tag unless that symbol has its own
4549 per-symbol @code{%destructor}.
4550
4551 Finally, you can define two different kinds of default @code{%destructor}s.
4552 (These default forms are experimental.
4553 More user feedback will help to determine whether they should become permanent
4554 features.)
4555 You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
4556 exactly one @code{%destructor} declaration in your grammar file.
4557 The parser will invoke the @var{code} associated with one of these whenever it
4558 discards any user-defined grammar symbol that has no per-symbol and no per-type
4559 @code{%destructor}.
4560 The parser uses the @var{code} for @code{<*>} in the case of such a grammar
4561 symbol for which you have formally declared a semantic type tag (@code{%type}
4562 counts as such a declaration, but @code{$<tag>$} does not).
4563 The parser uses the @var{code} for @code{<>} in the case of such a grammar
4564 symbol that has no declared semantic type tag.
4565 @end deffn
4566
4567 @noindent
4568 For example:
4569
4570 @smallexample
4571 %union @{ char *string; @}
4572 %token <string> STRING1
4573 %token <string> STRING2
4574 %type <string> string1
4575 %type <string> string2
4576 %union @{ char character; @}
4577 %token <character> CHR
4578 %type <character> chr
4579 %token TAGLESS
4580
4581 %destructor @{ @} <character>
4582 %destructor @{ free ($$); @} <*>
4583 %destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
4584 %destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
4585 @end smallexample
4586
4587 @noindent
4588 guarantees that, when the parser discards any user-defined symbol that has a
4589 semantic type tag other than @code{<character>}, it passes its semantic value
4590 to @code{free} by default.
4591 However, when the parser discards a @code{STRING1} or a @code{string1}, it also
4592 prints its line number to @code{stdout}.
4593 It performs only the second @code{%destructor} in this case, so it invokes
4594 @code{free} only once.
4595 Finally, the parser merely prints a message whenever it discards any symbol,
4596 such as @code{TAGLESS}, that has no semantic type tag.
4597
4598 A Bison-generated parser invokes the default @code{%destructor}s only for
4599 user-defined as opposed to Bison-defined symbols.
4600 For example, the parser will not invoke either kind of default
4601 @code{%destructor} for the special Bison-defined symbols @code{$accept},
4602 @code{$undefined}, or @code{$end} (@pxref{Table of Symbols, ,Bison Symbols}),
4603 none of which you can reference in your grammar.
4604 It also will not invoke either for the @code{error} token (@pxref{Table of
4605 Symbols, ,error}), which is always defined by Bison regardless of whether you
4606 reference it in your grammar.
4607 However, it may invoke one of them for the end token (token 0) if you
4608 redefine it from @code{$end} to, for example, @code{END}:
4609
4610 @smallexample
4611 %token END 0
4612 @end smallexample
4613
4614 @cindex actions in mid-rule
4615 @cindex mid-rule actions
4616 Finally, Bison will never invoke a @code{%destructor} for an unreferenced
4617 mid-rule semantic value (@pxref{Mid-Rule Actions,,Actions in Mid-Rule}).
4618 That is, Bison does not consider a mid-rule to have a semantic value if you do
4619 not reference @code{$$} in the mid-rule's action or @code{$@var{n}} (where
4620 @var{n} is the RHS symbol position of the mid-rule) in any later action in that
4621 rule.
4622 However, if you do reference either, the Bison-generated parser will invoke the
4623 @code{<>} @code{%destructor} whenever it discards the mid-rule symbol.
4624
4625 @ignore
4626 @noindent
4627 In the future, it may be possible to redefine the @code{error} token as a
4628 nonterminal that captures the discarded symbols.
4629 In that case, the parser will invoke the default destructor for it as well.
4630 @end ignore
4631
4632 @sp 1
4633
4634 @cindex discarded symbols
4635 @dfn{Discarded symbols} are the following:
4636
4637 @itemize
4638 @item
4639 stacked symbols popped during the first phase of error recovery,
4640 @item
4641 incoming terminals during the second phase of error recovery,
4642 @item
4643 the current lookahead and the entire stack (except the current
4644 right-hand side symbols) when the parser returns immediately, and
4645 @item
4646 the start symbol, when the parser succeeds.
4647 @end itemize
4648
4649 The parser can @dfn{return immediately} because of an explicit call to
4650 @code{YYABORT} or @code{YYACCEPT}, or failed error recovery, or memory
4651 exhaustion.
4652
4653 Right-hand side symbols of a rule that explicitly triggers a syntax
4654 error via @code{YYERROR} are not discarded automatically. As a rule
4655 of thumb, destructors are invoked only when user actions cannot manage
4656 the memory.
4657
4658 @node Expect Decl
4659 @subsection Suppressing Conflict Warnings
4660 @cindex suppressing conflict warnings
4661 @cindex preventing warnings about conflicts
4662 @cindex warnings, preventing
4663 @cindex conflicts, suppressing warnings of
4664 @findex %expect
4665 @findex %expect-rr
4666
4667 Bison normally warns if there are any conflicts in the grammar
4668 (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
4669 have harmless shift/reduce conflicts which are resolved in a predictable
4670 way and would be difficult to eliminate. It is desirable to suppress
4671 the warning about these conflicts unless the number of conflicts
4672 changes. You can do this with the @code{%expect} declaration.
4673
4674 The declaration looks like this:
4675
4676 @example
4677 %expect @var{n}
4678 @end example
4679
4680 Here @var{n} is a decimal integer. The declaration says there should
4681 be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
4682 Bison reports an error if the number of shift/reduce conflicts differs
4683 from @var{n}, or if there are any reduce/reduce conflicts.
4684
4685 For deterministic parsers, reduce/reduce conflicts are more
4686 serious, and should be eliminated entirely. Bison will always report
4687 reduce/reduce conflicts for these parsers. With GLR
4688 parsers, however, both kinds of conflicts are routine; otherwise,
4689 there would be no need to use GLR parsing. Therefore, it is
4690 also possible to specify an expected number of reduce/reduce conflicts
4691 in GLR parsers, using the declaration:
4692
4693 @example
4694 %expect-rr @var{n}
4695 @end example
4696
4697 In general, using @code{%expect} involves these steps:
4698
4699 @itemize @bullet
4700 @item
4701 Compile your grammar without @code{%expect}. Use the @samp{-v} option
4702 to get a verbose list of where the conflicts occur. Bison will also
4703 print the number of conflicts.
4704
4705 @item
4706 Check each of the conflicts to make sure that Bison's default
4707 resolution is what you really want. If not, rewrite the grammar and
4708 go back to the beginning.
4709
4710 @item
4711 Add an @code{%expect} declaration, copying the number @var{n} from the
4712 number which Bison printed. With GLR parsers, add an
4713 @code{%expect-rr} declaration as well.
4714 @end itemize
4715
4716 Now Bison will report an error if you introduce an unexpected conflict,
4717 but will keep silent otherwise.
4718
4719 @node Start Decl
4720 @subsection The Start-Symbol
4721 @cindex declaring the start symbol
4722 @cindex start symbol, declaring
4723 @cindex default start symbol
4724 @findex %start
4725
4726 Bison assumes by default that the start symbol for the grammar is the first
4727 nonterminal specified in the grammar specification section. The programmer
4728 may override this restriction with the @code{%start} declaration as follows:
4729
4730 @example
4731 %start @var{symbol}
4732 @end example
4733
4734 @node Pure Decl
4735 @subsection A Pure (Reentrant) Parser
4736 @cindex reentrant parser
4737 @cindex pure parser
4738 @findex %define api.pure
4739
4740 A @dfn{reentrant} program is one which does not alter in the course of
4741 execution; in other words, it consists entirely of @dfn{pure} (read-only)
4742 code. Reentrancy is important whenever asynchronous execution is possible;
4743 for example, a nonreentrant program may not be safe to call from a signal
4744 handler. In systems with multiple threads of control, a nonreentrant
4745 program must be called only within interlocks.
4746
4747 Normally, Bison generates a parser which is not reentrant. This is
4748 suitable for most uses, and it permits compatibility with Yacc. (The
4749 standard Yacc interfaces are inherently nonreentrant, because they use
4750 statically allocated variables for communication with @code{yylex},
4751 including @code{yylval} and @code{yylloc}.)
4752
4753 Alternatively, you can generate a pure, reentrant parser. The Bison
4754 declaration @samp{%define api.pure} says that you want the parser to be
4755 reentrant. It looks like this:
4756
4757 @example
4758 %define api.pure
4759 @end example
4760
4761 The result is that the communication variables @code{yylval} and
4762 @code{yylloc} become local variables in @code{yyparse}, and a different
4763 calling convention is used for the lexical analyzer function
4764 @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
4765 Parsers}, for the details of this. The variable @code{yynerrs}
4766 becomes local in @code{yyparse} in pull mode but it becomes a member
4767 of yypstate in push mode. (@pxref{Error Reporting, ,The Error
4768 Reporting Function @code{yyerror}}). The convention for calling
4769 @code{yyparse} itself is unchanged.
4770
4771 Whether the parser is pure has nothing to do with the grammar rules.
4772 You can generate either a pure parser or a nonreentrant parser from any
4773 valid grammar.
4774
4775 @node Push Decl
4776 @subsection A Push Parser
4777 @cindex push parser
4778 @cindex push parser
4779 @findex %define api.push-pull
4780
4781 (The current push parsing interface is experimental and may evolve.
4782 More user feedback will help to stabilize it.)
4783
4784 A pull parser is called once and it takes control until all its input
4785 is completely parsed. A push parser, on the other hand, is called
4786 each time a new token is made available.
4787
4788 A push parser is typically useful when the parser is part of a
4789 main event loop in the client's application. This is typically
4790 a requirement of a GUI, when the main event loop needs to be triggered
4791 within a certain time period.
4792
4793 Normally, Bison generates a pull parser.
4794 The following Bison declaration says that you want the parser to be a push
4795 parser (@pxref{%define Summary,,api.push-pull}):
4796
4797 @example
4798 %define api.push-pull push
4799 @end example
4800
4801 In almost all cases, you want to ensure that your push parser is also
4802 a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}). The only
4803 time you should create an impure push parser is to have backwards
4804 compatibility with the impure Yacc pull mode interface. Unless you know
4805 what you are doing, your declarations should look like this:
4806
4807 @example
4808 %define api.pure
4809 %define api.push-pull push
4810 @end example
4811
4812 There is a major notable functional difference between the pure push parser
4813 and the impure push parser. It is acceptable for a pure push parser to have
4814 many parser instances, of the same type of parser, in memory at the same time.
4815 An impure push parser should only use one parser at a time.
4816
4817 When a push parser is selected, Bison will generate some new symbols in
4818 the generated parser. @code{yypstate} is a structure that the generated
4819 parser uses to store the parser's state. @code{yypstate_new} is the
4820 function that will create a new parser instance. @code{yypstate_delete}
4821 will free the resources associated with the corresponding parser instance.
4822 Finally, @code{yypush_parse} is the function that should be called whenever a
4823 token is available to provide the parser. A trivial example
4824 of using a pure push parser would look like this:
4825
4826 @example
4827 int status;
4828 yypstate *ps = yypstate_new ();
4829 do @{
4830 status = yypush_parse (ps, yylex (), NULL);
4831 @} while (status == YYPUSH_MORE);
4832 yypstate_delete (ps);
4833 @end example
4834
4835 If the user decided to use an impure push parser, a few things about
4836 the generated parser will change. The @code{yychar} variable becomes
4837 a global variable instead of a variable in the @code{yypush_parse} function.
4838 For this reason, the signature of the @code{yypush_parse} function is
4839 changed to remove the token as a parameter. A nonreentrant push parser
4840 example would thus look like this:
4841
4842 @example
4843 extern int yychar;
4844 int status;
4845 yypstate *ps = yypstate_new ();
4846 do @{
4847 yychar = yylex ();
4848 status = yypush_parse (ps);
4849 @} while (status == YYPUSH_MORE);
4850 yypstate_delete (ps);
4851 @end example
4852
4853 That's it. Notice the next token is put into the global variable @code{yychar}
4854 for use by the next invocation of the @code{yypush_parse} function.
4855
4856 Bison also supports both the push parser interface along with the pull parser
4857 interface in the same generated parser. In order to get this functionality,
4858 you should replace the @samp{%define api.push-pull push} declaration with the
4859 @samp{%define api.push-pull both} declaration. Doing this will create all of
4860 the symbols mentioned earlier along with the two extra symbols, @code{yyparse}
4861 and @code{yypull_parse}. @code{yyparse} can be used exactly as it normally
4862 would be used. However, the user should note that it is implemented in the
4863 generated parser by calling @code{yypull_parse}.
4864 This makes the @code{yyparse} function that is generated with the
4865 @samp{%define api.push-pull both} declaration slower than the normal
4866 @code{yyparse} function. If the user
4867 calls the @code{yypull_parse} function it will parse the rest of the input
4868 stream. It is possible to @code{yypush_parse} tokens to select a subgrammar
4869 and then @code{yypull_parse} the rest of the input stream. If you would like
4870 to switch back and forth between between parsing styles, you would have to
4871 write your own @code{yypull_parse} function that knows when to quit looking
4872 for input. An example of using the @code{yypull_parse} function would look
4873 like this:
4874
4875 @example
4876 yypstate *ps = yypstate_new ();
4877 yypull_parse (ps); /* Will call the lexer */
4878 yypstate_delete (ps);
4879 @end example
4880
4881 Adding the @samp{%define api.pure} declaration does exactly the same thing to
4882 the generated parser with @samp{%define api.push-pull both} as it did for
4883 @samp{%define api.push-pull push}.
4884
4885 @node Decl Summary
4886 @subsection Bison Declaration Summary
4887 @cindex Bison declaration summary
4888 @cindex declaration summary
4889 @cindex summary, Bison declaration
4890
4891 Here is a summary of the declarations used to define a grammar:
4892
4893 @deffn {Directive} %union
4894 Declare the collection of data types that semantic values may have
4895 (@pxref{Union Decl, ,The Collection of Value Types}).
4896 @end deffn
4897
4898 @deffn {Directive} %token
4899 Declare a terminal symbol (token type name) with no precedence
4900 or associativity specified (@pxref{Token Decl, ,Token Type Names}).
4901 @end deffn
4902
4903 @deffn {Directive} %right
4904 Declare a terminal symbol (token type name) that is right-associative
4905 (@pxref{Precedence Decl, ,Operator Precedence}).
4906 @end deffn
4907
4908 @deffn {Directive} %left
4909 Declare a terminal symbol (token type name) that is left-associative
4910 (@pxref{Precedence Decl, ,Operator Precedence}).
4911 @end deffn
4912
4913 @deffn {Directive} %nonassoc
4914 Declare a terminal symbol (token type name) that is nonassociative
4915 (@pxref{Precedence Decl, ,Operator Precedence}).
4916 Using it in a way that would be associative is a syntax error.
4917 @end deffn
4918
4919 @ifset defaultprec
4920 @deffn {Directive} %default-prec
4921 Assign a precedence to rules lacking an explicit @code{%prec} modifier
4922 (@pxref{Contextual Precedence, ,Context-Dependent Precedence}).
4923 @end deffn
4924 @end ifset
4925
4926 @deffn {Directive} %type
4927 Declare the type of semantic values for a nonterminal symbol
4928 (@pxref{Type Decl, ,Nonterminal Symbols}).
4929 @end deffn
4930
4931 @deffn {Directive} %start
4932 Specify the grammar's start symbol (@pxref{Start Decl, ,The
4933 Start-Symbol}).
4934 @end deffn
4935
4936 @deffn {Directive} %expect
4937 Declare the expected number of shift-reduce conflicts
4938 (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
4939 @end deffn
4940
4941
4942 @sp 1
4943 @noindent
4944 In order to change the behavior of @command{bison}, use the following
4945 directives:
4946
4947 @deffn {Directive} %code @{@var{code}@}
4948 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
4949 @findex %code
4950 Insert @var{code} verbatim into the output parser source at the
4951 default location or at the location specified by @var{qualifier}.
4952 @xref{%code Summary}.
4953 @end deffn
4954
4955 @deffn {Directive} %debug
4956 Instrument the output parser for traces. Obsoleted by @samp{%define
4957 parse.trace}.
4958 @xref{Tracing, ,Tracing Your Parser}.
4959 @end deffn
4960
4961 @deffn {Directive} %define @var{variable}
4962 @deffnx {Directive} %define @var{variable} @var{value}
4963 @deffnx {Directive} %define @var{variable} "@var{value}"
4964 Define a variable to adjust Bison's behavior. @xref{%define Summary}.
4965 @end deffn
4966
4967 @deffn {Directive} %defines
4968 Write a parser header file containing macro definitions for the token
4969 type names defined in the grammar as well as a few other declarations.
4970 If the parser implementation file is named @file{@var{name}.c} then
4971 the parser header file is named @file{@var{name}.h}.
4972
4973 For C parsers, the parser header file declares @code{YYSTYPE} unless
4974 @code{YYSTYPE} is already defined as a macro or you have used a
4975 @code{<@var{type}>} tag without using @code{%union}. Therefore, if
4976 you are using a @code{%union} (@pxref{Multiple Types, ,More Than One
4977 Value Type}) with components that require other definitions, or if you
4978 have defined a @code{YYSTYPE} macro or type definition (@pxref{Value
4979 Type, ,Data Types of Semantic Values}), you need to arrange for these
4980 definitions to be propagated to all modules, e.g., by putting them in
4981 a prerequisite header that is included both by your parser and by any
4982 other module that needs @code{YYSTYPE}.
4983
4984 Unless your parser is pure, the parser header file declares
4985 @code{yylval} as an external variable. @xref{Pure Decl, ,A Pure
4986 (Reentrant) Parser}.
4987
4988 If you have also used locations, the parser header file declares
4989 @code{YYLTYPE} and @code{yylloc} using a protocol similar to that of
4990 the @code{YYSTYPE} macro and @code{yylval}. @xref{Locations,
4991 ,Tracking Locations}.
4992
4993 This parser header file is normally essential if you wish to put the
4994 definition of @code{yylex} in a separate source file, because
4995 @code{yylex} typically needs to be able to refer to the
4996 above-mentioned declarations and to the token type codes. @xref{Token
4997 Values, ,Semantic Values of Tokens}.
4998
4999 @findex %code requires
5000 @findex %code provides
5001 If you have declared @code{%code requires} or @code{%code provides}, the output
5002 header also contains their code.
5003 @xref{%code Summary}.
5004 @end deffn
5005
5006 @deffn {Directive} %defines @var{defines-file}
5007 Same as above, but save in the file @var{defines-file}.
5008 @end deffn
5009
5010 @deffn {Directive} %destructor
5011 Specify how the parser should reclaim the memory associated to
5012 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
5013 @end deffn
5014
5015 @deffn {Directive} %file-prefix "@var{prefix}"
5016 Specify a prefix to use for all Bison output file names. The names
5017 are chosen as if the grammar file were named @file{@var{prefix}.y}.
5018 @end deffn
5019
5020 @deffn {Directive} %language "@var{language}"
5021 Specify the programming language for the generated parser. Currently
5022 supported languages include C, C++, and Java.
5023 @var{language} is case-insensitive.
5024
5025 This directive is experimental and its effect may be modified in future
5026 releases.
5027 @end deffn
5028
5029 @deffn {Directive} %locations
5030 Generate the code processing the locations (@pxref{Action Features,
5031 ,Special Features for Use in Actions}). This mode is enabled as soon as
5032 the grammar uses the special @samp{@@@var{n}} tokens, but if your
5033 grammar does not use it, using @samp{%locations} allows for more
5034 accurate syntax error messages.
5035 @end deffn
5036
5037 @deffn {Directive} %name-prefix "@var{prefix}"
5038 Rename the external symbols used in the parser so that they start with
5039 @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
5040 in C parsers
5041 is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
5042 @code{yylval}, @code{yychar}, @code{yydebug}, and
5043 (if locations are used) @code{yylloc}. If you use a push parser,
5044 @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5045 @code{yypstate_new} and @code{yypstate_delete} will
5046 also be renamed. For example, if you use @samp{%name-prefix "c_"}, the
5047 names become @code{c_parse}, @code{c_lex}, and so on.
5048 For C++ parsers, see the @samp{%define api.namespace} documentation in this
5049 section.
5050 @xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
5051 @end deffn
5052
5053 @ifset defaultprec
5054 @deffn {Directive} %no-default-prec
5055 Do not assign a precedence to rules lacking an explicit @code{%prec}
5056 modifier (@pxref{Contextual Precedence, ,Context-Dependent
5057 Precedence}).
5058 @end deffn
5059 @end ifset
5060
5061 @deffn {Directive} %no-lines
5062 Don't generate any @code{#line} preprocessor commands in the parser
5063 implementation file. Ordinarily Bison writes these commands in the
5064 parser implementation file so that the C compiler and debuggers will
5065 associate errors and object code with your source file (the grammar
5066 file). This directive causes them to associate errors with the parser
5067 implementation file, treating it as an independent source file in its
5068 own right.
5069 @end deffn
5070
5071 @deffn {Directive} %output "@var{file}"
5072 Specify @var{file} for the parser implementation file.
5073 @end deffn
5074
5075 @deffn {Directive} %pure-parser
5076 Deprecated version of @samp{%define api.pure} (@pxref{%define
5077 Summary,,api.pure}), for which Bison is more careful to warn about
5078 unreasonable usage.
5079 @end deffn
5080
5081 @deffn {Directive} %require "@var{version}"
5082 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
5083 Require a Version of Bison}.
5084 @end deffn
5085
5086 @deffn {Directive} %skeleton "@var{file}"
5087 Specify the skeleton to use.
5088
5089 @c You probably don't need this option unless you are developing Bison.
5090 @c You should use @code{%language} if you want to specify the skeleton for a
5091 @c different language, because it is clearer and because it will always choose the
5092 @c correct skeleton for non-deterministic or push parsers.
5093
5094 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
5095 file in the Bison installation directory.
5096 If it does, @var{file} is an absolute file name or a file name relative to the
5097 directory of the grammar file.
5098 This is similar to how most shells resolve commands.
5099 @end deffn
5100
5101 @deffn {Directive} %token-table
5102 Generate an array of token names in the parser implementation file.
5103 The name of the array is @code{yytname}; @code{yytname[@var{i}]} is
5104 the name of the token whose internal Bison token code number is
5105 @var{i}. The first three elements of @code{yytname} correspond to the
5106 predefined tokens @code{"$end"}, @code{"error"}, and
5107 @code{"$undefined"}; after these come the symbols defined in the
5108 grammar file.
5109
5110 The name in the table includes all the characters needed to represent
5111 the token in Bison. For single-character literals and literal
5112 strings, this includes the surrounding quoting characters and any
5113 escape sequences. For example, the Bison single-character literal
5114 @code{'+'} corresponds to a three-character name, represented in C as
5115 @code{"'+'"}; and the Bison two-character literal string @code{"\\/"}
5116 corresponds to a five-character name, represented in C as
5117 @code{"\"\\\\/\""}.
5118
5119 When you specify @code{%token-table}, Bison also generates macro
5120 definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
5121 @code{YYNRULES}, and @code{YYNSTATES}:
5122
5123 @table @code
5124 @item YYNTOKENS
5125 The highest token number, plus one.
5126 @item YYNNTS
5127 The number of nonterminal symbols.
5128 @item YYNRULES
5129 The number of grammar rules,
5130 @item YYNSTATES
5131 The number of parser states (@pxref{Parser States}).
5132 @end table
5133 @end deffn
5134
5135 @deffn {Directive} %verbose
5136 Write an extra output file containing verbose descriptions of the
5137 parser states and what is done for each type of lookahead token in
5138 that state. @xref{Understanding, , Understanding Your Parser}, for more
5139 information.
5140 @end deffn
5141
5142 @deffn {Directive} %yacc
5143 Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
5144 including its naming conventions. @xref{Bison Options}, for more.
5145 @end deffn
5146
5147
5148 @node %define Summary
5149 @subsection %define Summary
5150
5151 There are many features of Bison's behavior that can be controlled by
5152 assigning the feature a single value. For historical reasons, some
5153 such features are assigned values by dedicated directives, such as
5154 @code{%start}, which assigns the start symbol. However, newer such
5155 features are associated with variables, which are assigned by the
5156 @code{%define} directive:
5157
5158 @deffn {Directive} %define @var{variable}
5159 @deffnx {Directive} %define @var{variable} @var{value}
5160 @deffnx {Directive} %define @var{variable} "@var{value}"
5161 Define @var{variable} to @var{value}.
5162
5163 @var{value} must be placed in quotation marks if it contains any
5164 character other than a letter, underscore, period, or non-initial dash
5165 or digit. Omitting @code{"@var{value}"} entirely is always equivalent
5166 to specifying @code{""}.
5167
5168 It is an error if a @var{variable} is defined by @code{%define}
5169 multiple times, but see @ref{Bison Options,,-D
5170 @var{name}[=@var{value}]}.
5171 @end deffn
5172
5173 The rest of this section summarizes variables and values that
5174 @code{%define} accepts.
5175
5176 Some @var{variable}s take Boolean values. In this case, Bison will
5177 complain if the variable definition does not meet one of the following
5178 four conditions:
5179
5180 @enumerate
5181 @item @code{@var{value}} is @code{true}
5182
5183 @item @code{@var{value}} is omitted (or @code{""} is specified).
5184 This is equivalent to @code{true}.
5185
5186 @item @code{@var{value}} is @code{false}.
5187
5188 @item @var{variable} is never defined.
5189 In this case, Bison selects a default value.
5190 @end enumerate
5191
5192 What @var{variable}s are accepted, as well as their meanings and default
5193 values, depend on the selected target language and/or the parser
5194 skeleton (@pxref{Decl Summary,,%language}, @pxref{Decl
5195 Summary,,%skeleton}).
5196 Unaccepted @var{variable}s produce an error.
5197 Some of the accepted @var{variable}s are:
5198
5199 @table @code
5200 @c ================================================== api.namespace
5201 @item api.namespace
5202 @findex %define api.namespace
5203 @itemize
5204 @item Languages(s): C++
5205
5206 @item Purpose: Specify the namespace for the parser class.
5207 For example, if you specify:
5208
5209 @smallexample
5210 %define api.namespace "foo::bar"
5211 @end smallexample
5212
5213 Bison uses @code{foo::bar} verbatim in references such as:
5214
5215 @smallexample
5216 foo::bar::parser::semantic_type
5217 @end smallexample
5218
5219 However, to open a namespace, Bison removes any leading @code{::} and then
5220 splits on any remaining occurrences:
5221
5222 @smallexample
5223 namespace foo @{ namespace bar @{
5224 class position;
5225 class location;
5226 @} @}
5227 @end smallexample
5228
5229 @item Accepted Values:
5230 Any absolute or relative C++ namespace reference without a trailing
5231 @code{"::"}. For example, @code{"foo"} or @code{"::foo::bar"}.
5232
5233 @item Default Value:
5234 The value specified by @code{%name-prefix}, which defaults to @code{yy}.
5235 This usage of @code{%name-prefix} is for backward compatibility and can
5236 be confusing since @code{%name-prefix} also specifies the textual prefix
5237 for the lexical analyzer function. Thus, if you specify
5238 @code{%name-prefix}, it is best to also specify @samp{%define
5239 api.namespace} so that @code{%name-prefix} @emph{only} affects the
5240 lexical analyzer function. For example, if you specify:
5241
5242 @smallexample
5243 %define api.namespace "foo"
5244 %name-prefix "bar::"
5245 @end smallexample
5246
5247 The parser namespace is @code{foo} and @code{yylex} is referenced as
5248 @code{bar::lex}.
5249 @end itemize
5250 @c namespace
5251
5252
5253
5254 @c ================================================== api.pure
5255 @item api.pure
5256 @findex %define api.pure
5257
5258 @itemize @bullet
5259 @item Language(s): C
5260
5261 @item Purpose: Request a pure (reentrant) parser program.
5262 @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
5263
5264 @item Accepted Values: Boolean
5265
5266 @item Default Value: @code{false}
5267 @end itemize
5268 @c api.pure
5269
5270
5271
5272 @c ================================================== api.push-pull
5273 @item api.push-pull
5274 @findex %define api.push-pull
5275
5276 @itemize @bullet
5277 @item Language(s): C (deterministic parsers only)
5278
5279 @item Purpose: Request a pull parser, a push parser, or both.
5280 @xref{Push Decl, ,A Push Parser}.
5281 (The current push parsing interface is experimental and may evolve.
5282 More user feedback will help to stabilize it.)
5283
5284 @item Accepted Values: @code{pull}, @code{push}, @code{both}
5285
5286 @item Default Value: @code{pull}
5287 @end itemize
5288 @c api.push-pull
5289
5290
5291
5292 @c ================================================== api.tokens.prefix
5293 @item api.tokens.prefix
5294 @findex %define api.tokens.prefix
5295
5296 @itemize
5297 @item Languages(s): all
5298
5299 @item Purpose:
5300 Add a prefix to the token names when generating their definition in the
5301 target language. For instance
5302
5303 @example
5304 %token FILE for ERROR
5305 %define api.tokens.prefix "TOK_"
5306 %%
5307 start: FILE for ERROR;
5308 @end example
5309
5310 @noindent
5311 generates the definition of the symbols @code{TOK_FILE}, @code{TOK_for},
5312 and @code{TOK_ERROR} in the generated source files. In particular, the
5313 scanner must use these prefixed token names, while the grammar itself
5314 may still use the short names (as in the sample rule given above). The
5315 generated informational files (@file{*.output}, @file{*.xml},
5316 @file{*.dot}) are not modified by this prefix. See @ref{Calc++ Parser}
5317 and @ref{Calc++ Scanner}, for a complete example.
5318
5319 @item Accepted Values:
5320 Any string. Should be a valid identifier prefix in the target language,
5321 in other words, it should typically be an identifier itself (sequence of
5322 letters, underscores, and ---not at the beginning--- digits).
5323
5324 @item Default Value:
5325 empty
5326 @end itemize
5327 @c api.tokens.prefix
5328
5329
5330 @c ================================================== lex_symbol
5331 @item lex_symbol
5332 @findex %define lex_symbol
5333
5334 @itemize @bullet
5335 @item Language(s):
5336 C++
5337
5338 @item Purpose:
5339 When variant-based semantic values are enabled (@pxref{C++ Variants}),
5340 request that symbols be handled as a whole (type, value, and possibly
5341 location) in the scanner. @xref{Complete Symbols}, for details.
5342
5343 @item Accepted Values:
5344 Boolean.
5345
5346 @item Default Value:
5347 @code{false}
5348 @end itemize
5349 @c lex_symbol
5350
5351
5352 @c ================================================== lr.default-reductions
5353
5354 @item lr.default-reductions
5355 @cindex default reductions
5356 @findex %define lr.default-reductions
5357 @cindex delayed syntax errors
5358 @cindex syntax errors delayed
5359 @cindex LAC
5360 @findex %nonassoc
5361
5362 @itemize @bullet
5363 @item Language(s): all
5364
5365 @item Purpose: Specify the kind of states that are permitted to
5366 contain default reductions.
5367 That is, in such a state, Bison selects the reduction with the largest
5368 lookahead set to be the default parser action and then removes that
5369 lookahead set.
5370 (The ability to specify where default reductions should be used is
5371 experimental.
5372 More user feedback will help to stabilize it.)
5373
5374 @item Accepted Values:
5375 @itemize
5376 @item @code{all}.
5377 This is the traditional Bison behavior. The main advantage is a
5378 significant decrease in the size of the parser tables. The
5379 disadvantage is that, when the generated parser encounters a
5380 syntactically unacceptable token, the parser might then perform
5381 unnecessary default reductions before it can detect the syntax error.
5382 Such delayed syntax error detection is usually inherent in LALR and
5383 IELR parser tables anyway due to LR state merging (@pxref{%define
5384 Summary,,lr.type}). Furthermore, the use of @code{%nonassoc} can
5385 contribute to delayed syntax error detection even in the case of
5386 canonical LR. As an experimental feature, delayed syntax error
5387 detection can be overcome in all cases by enabling LAC (@pxref{%define
5388 Summary,,parse.lac}, for details, including a discussion of the
5389 effects of delayed syntax error detection).
5390
5391 @item @code{consistent}.
5392 @cindex consistent states
5393 A consistent state is a state that has only one possible action.
5394 If that action is a reduction, then the parser does not need to request
5395 a lookahead token from the scanner before performing that action.
5396 However, the parser recognizes the ability to ignore the lookahead token
5397 in this way only when such a reduction is encoded as a default
5398 reduction.
5399 Thus, if default reductions are permitted only in consistent states,
5400 then a canonical LR parser that does not employ
5401 @code{%nonassoc} detects a syntax error as soon as it @emph{needs} the
5402 syntactically unacceptable token from the scanner.
5403
5404 @item @code{accepting}.
5405 @cindex accepting state
5406 In the accepting state, the default reduction is actually the accept
5407 action.
5408 In this case, a canonical LR parser that does not employ
5409 @code{%nonassoc} detects a syntax error as soon as it @emph{reaches} the
5410 syntactically unacceptable token in the input.
5411 That is, it does not perform any extra reductions.
5412 @end itemize
5413
5414 @item Default Value:
5415 @itemize
5416 @item @code{accepting} if @code{lr.type} is @code{canonical-lr}.
5417 @item @code{all} otherwise.
5418 @end itemize
5419 @end itemize
5420
5421 @c ============================================ lr.keep-unreachable-states
5422
5423 @item lr.keep-unreachable-states
5424 @findex %define lr.keep-unreachable-states
5425
5426 @itemize @bullet
5427 @item Language(s): all
5428
5429 @item Purpose: Request that Bison allow unreachable parser states to
5430 remain in the parser tables.
5431 Bison considers a state to be unreachable if there exists no sequence of
5432 transitions from the start state to that state.
5433 A state can become unreachable during conflict resolution if Bison disables a
5434 shift action leading to it from a predecessor state.
5435 Keeping unreachable states is sometimes useful for analysis purposes, but they
5436 are useless in the generated parser.
5437
5438 @item Accepted Values: Boolean
5439
5440 @item Default Value: @code{false}
5441
5442 @item Caveats:
5443
5444 @itemize @bullet
5445
5446 @item Unreachable states may contain conflicts and may use rules not used in
5447 any other state.
5448 Thus, keeping unreachable states may induce warnings that are irrelevant to
5449 your parser's behavior, and it may eliminate warnings that are relevant.
5450 Of course, the change in warnings may actually be relevant to a parser table
5451 analysis that wants to keep unreachable states, so this behavior will likely
5452 remain in future Bison releases.
5453
5454 @item While Bison is able to remove unreachable states, it is not guaranteed to
5455 remove other kinds of useless states.
5456 Specifically, when Bison disables reduce actions during conflict resolution,
5457 some goto actions may become useless, and thus some additional states may
5458 become useless.
5459 If Bison were to compute which goto actions were useless and then disable those
5460 actions, it could identify such states as unreachable and then remove those
5461 states.
5462 However, Bison does not compute which goto actions are useless.
5463 @end itemize
5464 @end itemize
5465 @c lr.keep-unreachable-states
5466
5467 @c ================================================== lr.type
5468
5469 @item lr.type
5470 @findex %define lr.type
5471 @cindex LALR
5472 @cindex IELR
5473 @cindex LR
5474
5475 @itemize @bullet
5476 @item Language(s): all
5477
5478 @item Purpose: Specify the type of parser tables within the
5479 LR(1) family.
5480 (This feature is experimental.
5481 More user feedback will help to stabilize it.)
5482
5483 @item Accepted Values:
5484 @itemize
5485 @item @code{lalr}.
5486 While Bison generates LALR parser tables by default for
5487 historical reasons, IELR or canonical LR is almost
5488 always preferable for deterministic parsers.
5489 The trouble is that LALR parser tables can suffer from
5490 mysterious conflicts and thus may not accept the full set of sentences
5491 that IELR and canonical LR accept.
5492 @xref{Mystery Conflicts}, for details.
5493 However, there are at least two scenarios where LALR may be
5494 worthwhile:
5495 @itemize
5496 @cindex GLR with LALR
5497 @item When employing GLR parsers (@pxref{GLR Parsers}), if you
5498 do not resolve any conflicts statically (for example, with @code{%left}
5499 or @code{%prec}), then the parser explores all potential parses of any
5500 given input.
5501 In this case, the use of LALR parser tables is guaranteed not
5502 to alter the language accepted by the parser.
5503 LALR parser tables are the smallest parser tables Bison can
5504 currently generate, so they may be preferable.
5505 Nevertheless, once you begin to resolve conflicts statically,
5506 GLR begins to behave more like a deterministic parser, and so
5507 IELR and canonical LR can be helpful to avoid
5508 LALR's mysterious behavior.
5509
5510 @item Occasionally during development, an especially malformed grammar
5511 with a major recurring flaw may severely impede the IELR or
5512 canonical LR parser table generation algorithm.
5513 LALR can be a quick way to generate parser tables in order to
5514 investigate such problems while ignoring the more subtle differences
5515 from IELR and canonical LR.
5516 @end itemize
5517
5518 @item @code{ielr}.
5519 IELR is a minimal LR algorithm.
5520 That is, given any grammar (LR or non-LR),
5521 IELR and canonical LR always accept exactly the same
5522 set of sentences.
5523 However, as for LALR, the number of parser states is often an
5524 order of magnitude less for IELR than for canonical
5525 LR.
5526 More importantly, because canonical LR's extra parser states
5527 may contain duplicate conflicts in the case of non-LR
5528 grammars, the number of conflicts for IELR is often an order
5529 of magnitude less as well.
5530 This can significantly reduce the complexity of developing of a grammar.
5531
5532 @item @code{canonical-lr}.
5533 @cindex delayed syntax errors
5534 @cindex syntax errors delayed
5535 @cindex LAC
5536 @findex %nonassoc
5537 While inefficient, canonical LR parser tables can be an interesting
5538 means to explore a grammar because they have a property that IELR and
5539 LALR tables do not. That is, if @code{%nonassoc} is not used and
5540 default reductions are left disabled (@pxref{%define
5541 Summary,,lr.default-reductions}), then, for every left context of
5542 every canonical LR state, the set of tokens accepted by that state is
5543 guaranteed to be the exact set of tokens that is syntactically
5544 acceptable in that left context. It might then seem that an advantage
5545 of canonical LR parsers in production is that, under the above
5546 constraints, they are guaranteed to detect a syntax error as soon as
5547 possible without performing any unnecessary reductions. However, IELR
5548 parsers using LAC (@pxref{%define Summary,,parse.lac}) are also able
5549 to achieve this behavior without sacrificing @code{%nonassoc} or
5550 default reductions.
5551 @end itemize
5552
5553 @item Default Value: @code{lalr}
5554 @end itemize
5555
5556
5557 @c ================================================== namespace
5558 @item namespace
5559 @findex %define namespace
5560 Obsoleted by @code{api.namespace}
5561 @c namespace
5562
5563
5564 @c ================================================== parse.assert
5565 @item parse.assert
5566 @findex %define parse.assert
5567
5568 @itemize
5569 @item Languages(s): C++
5570
5571 @item Purpose: Issue runtime assertions to catch invalid uses.
5572 In C++, when variants are used (@pxref{C++ Variants}), symbols must be
5573 constructed and
5574 destroyed properly. This option checks these constraints.
5575
5576 @item Accepted Values: Boolean
5577
5578 @item Default Value: @code{false}
5579 @end itemize
5580 @c parse.assert
5581
5582
5583 @c ================================================== parse.error
5584 @item parse.error
5585 @findex %define parse.error
5586 @itemize
5587 @item Languages(s):
5588 all
5589 @item Purpose:
5590 Control the kind of error messages passed to the error reporting
5591 function. @xref{Error Reporting, ,The Error Reporting Function
5592 @code{yyerror}}.
5593 @item Accepted Values:
5594 @itemize
5595 @item @code{simple}
5596 Error messages passed to @code{yyerror} are simply @w{@code{"syntax
5597 error"}}.
5598 @item @code{verbose}
5599 Error messages report the unexpected token, and possibly the expected
5600 ones.
5601 @end itemize
5602
5603 @item Default Value:
5604 @code{simple}
5605 @end itemize
5606 @c parse.error
5607
5608
5609 @c ================================================== parse.lac
5610 @item parse.lac
5611 @findex %define parse.lac
5612 @cindex LAC
5613 @cindex lookahead correction
5614
5615 @itemize
5616 @item Languages(s): C
5617
5618 @item Purpose: Enable LAC (lookahead correction) to improve
5619 syntax error handling.
5620
5621 Canonical LR, IELR, and LALR can suffer
5622 from a couple of problems upon encountering a syntax error. First, the
5623 parser might perform additional parser stack reductions before
5624 discovering the syntax error. Such reductions perform user semantic
5625 actions that are unexpected because they are based on an invalid token,
5626 and they cause error recovery to begin in a different syntactic context
5627 than the one in which the invalid token was encountered. Second, when
5628 verbose error messages are enabled (with @code{%error-verbose} or
5629 @code{#define YYERROR_VERBOSE}), the expected token list in the syntax
5630 error message can both contain invalid tokens and omit valid tokens.
5631
5632 The culprits for the above problems are @code{%nonassoc}, default
5633 reductions in inconsistent states, and parser state merging. Thus,
5634 IELR and LALR suffer the most. Canonical
5635 LR can suffer only if @code{%nonassoc} is used or if default
5636 reductions are enabled for inconsistent states.
5637
5638 LAC is a new mechanism within the parsing algorithm that
5639 completely solves these problems for canonical LR,
5640 IELR, and LALR without sacrificing @code{%nonassoc},
5641 default reductions, or state mering. Conceptually, the mechanism is
5642 straight-forward. Whenever the parser fetches a new token from the
5643 scanner so that it can determine the next parser action, it immediately
5644 suspends normal parsing and performs an exploratory parse using a
5645 temporary copy of the normal parser state stack. During this
5646 exploratory parse, the parser does not perform user semantic actions.
5647 If the exploratory parse reaches a shift action, normal parsing then
5648 resumes on the normal parser stacks. If the exploratory parse reaches
5649 an error instead, the parser reports a syntax error. If verbose syntax
5650 error messages are enabled, the parser must then discover the list of
5651 expected tokens, so it performs a separate exploratory parse for each
5652 token in the grammar.
5653
5654 There is one subtlety about the use of LAC. That is, when in a
5655 consistent parser state with a default reduction, the parser will not
5656 attempt to fetch a token from the scanner because no lookahead is
5657 needed to determine the next parser action. Thus, whether default
5658 reductions are enabled in consistent states (@pxref{%define
5659 Summary,,lr.default-reductions}) affects how soon the parser detects a
5660 syntax error: when it @emph{reaches} an erroneous token or when it
5661 eventually @emph{needs} that token as a lookahead. The latter
5662 behavior is probably more intuitive, so Bison currently provides no
5663 way to achieve the former behavior while default reductions are fully
5664 enabled.
5665
5666 Thus, when LAC is in use, for some fixed decision of whether
5667 to enable default reductions in consistent states, canonical
5668 LR and IELR behave exactly the same for both
5669 syntactically acceptable and syntactically unacceptable input. While
5670 LALR still does not support the full language-recognition
5671 power of canonical LR and IELR, LAC at
5672 least enables LALR's syntax error handling to correctly
5673 reflect LALR's language-recognition power.
5674
5675 Because LAC requires many parse actions to be performed twice,
5676 it can have a performance penalty. However, not all parse actions must
5677 be performed twice. Specifically, during a series of default reductions
5678 in consistent states and shift actions, the parser never has to initiate
5679 an exploratory parse. Moreover, the most time-consuming tasks in a
5680 parse are often the file I/O, the lexical analysis performed by the
5681 scanner, and the user's semantic actions, but none of these are
5682 performed during the exploratory parse. Finally, the base of the
5683 temporary stack used during an exploratory parse is a pointer into the
5684 normal parser state stack so that the stack is never physically copied.
5685 In our experience, the performance penalty of LAC has proven
5686 insignificant for practical grammars.
5687
5688 @item Accepted Values: @code{none}, @code{full}
5689
5690 @item Default Value: @code{none}
5691 @end itemize
5692 @c parse.lac
5693
5694 @c ================================================== parse.trace
5695 @item parse.trace
5696 @findex %define parse.trace
5697
5698 @itemize
5699 @item Languages(s): C, C++
5700
5701 @item Purpose: Require parser instrumentation for tracing.
5702 In C/C++, define the macro @code{YYDEBUG} to 1 in the parser implementation
5703 file if it is not already defined, so that the debugging facilities are
5704 compiled. @xref{Tracing, ,Tracing Your Parser}.
5705
5706 @item Accepted Values: Boolean
5707
5708 @item Default Value: @code{false}
5709 @end itemize
5710 @c parse.trace
5711
5712 @c ================================================== variant
5713 @item variant
5714 @findex %define variant
5715
5716 @itemize @bullet
5717 @item Language(s):
5718 C++
5719
5720 @item Purpose:
5721 Request variant-based semantic values.
5722 @xref{C++ Variants}.
5723
5724 @item Accepted Values:
5725 Boolean.
5726
5727 @item Default Value:
5728 @code{false}
5729 @end itemize
5730 @c variant
5731 @end table
5732
5733
5734 @node %code Summary
5735 @subsection %code Summary
5736 @findex %code
5737 @cindex Prologue
5738
5739 The @code{%code} directive inserts code verbatim into the output
5740 parser source at any of a predefined set of locations. It thus serves
5741 as a flexible and user-friendly alternative to the traditional Yacc
5742 prologue, @code{%@{@var{code}%@}}. This section summarizes the
5743 functionality of @code{%code} for the various target languages
5744 supported by Bison. For a detailed discussion of how to use
5745 @code{%code} in place of @code{%@{@var{code}%@}} for C/C++ and why it
5746 is advantageous to do so, @pxref{Prologue Alternatives}.
5747
5748 @deffn {Directive} %code @{@var{code}@}
5749 This is the unqualified form of the @code{%code} directive. It
5750 inserts @var{code} verbatim at a language-dependent default location
5751 in the parser implementation.
5752
5753 For C/C++, the default location is the parser implementation file
5754 after the usual contents of the parser header file. Thus, the
5755 unqualified form replaces @code{%@{@var{code}%@}} for most purposes.
5756
5757 For Java, the default location is inside the parser class.
5758 @end deffn
5759
5760 @deffn {Directive} %code @var{qualifier} @{@var{code}@}
5761 This is the qualified form of the @code{%code} directive.
5762 @var{qualifier} identifies the purpose of @var{code} and thus the
5763 location(s) where Bison should insert it. That is, if you need to
5764 specify location-sensitive @var{code} that does not belong at the
5765 default location selected by the unqualified @code{%code} form, use
5766 this form instead.
5767 @end deffn
5768
5769 For any particular qualifier or for the unqualified form, if there are
5770 multiple occurrences of the @code{%code} directive, Bison concatenates
5771 the specified code in the order in which it appears in the grammar
5772 file.
5773
5774 Not all qualifiers are accepted for all target languages. Unaccepted
5775 qualifiers produce an error. Some of the accepted qualifiers are:
5776
5777 @table @code
5778 @item requires
5779 @findex %code requires
5780
5781 @itemize @bullet
5782 @item Language(s): C, C++
5783
5784 @item Purpose: This is the best place to write dependency code required for
5785 @code{YYSTYPE} and @code{YYLTYPE}.
5786 In other words, it's the best place to define types referenced in @code{%union}
5787 directives, and it's the best place to override Bison's default @code{YYSTYPE}
5788 and @code{YYLTYPE} definitions.
5789
5790 @item Location(s): The parser header file and the parser implementation file
5791 before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
5792 definitions.
5793 @end itemize
5794
5795 @item provides
5796 @findex %code provides
5797
5798 @itemize @bullet
5799 @item Language(s): C, C++
5800
5801 @item Purpose: This is the best place to write additional definitions and
5802 declarations that should be provided to other modules.
5803
5804 @item Location(s): The parser header file and the parser implementation
5805 file after the Bison-generated @code{YYSTYPE}, @code{YYLTYPE}, and
5806 token definitions.
5807 @end itemize
5808
5809 @item top
5810 @findex %code top
5811
5812 @itemize @bullet
5813 @item Language(s): C, C++
5814
5815 @item Purpose: The unqualified @code{%code} or @code{%code requires}
5816 should usually be more appropriate than @code{%code top}. However,
5817 occasionally it is necessary to insert code much nearer the top of the
5818 parser implementation file. For example:
5819
5820 @smallexample
5821 %code top @{
5822 #define _GNU_SOURCE
5823 #include <stdio.h>
5824 @}
5825 @end smallexample
5826
5827 @item Location(s): Near the top of the parser implementation file.
5828 @end itemize
5829
5830 @item imports
5831 @findex %code imports
5832
5833 @itemize @bullet
5834 @item Language(s): Java
5835
5836 @item Purpose: This is the best place to write Java import directives.
5837
5838 @item Location(s): The parser Java file after any Java package directive and
5839 before any class definitions.
5840 @end itemize
5841 @end table
5842
5843 Though we say the insertion locations are language-dependent, they are
5844 technically skeleton-dependent. Writers of non-standard skeletons
5845 however should choose their locations consistently with the behavior
5846 of the standard Bison skeletons.
5847
5848
5849 @node Multiple Parsers
5850 @section Multiple Parsers in the Same Program
5851
5852 Most programs that use Bison parse only one language and therefore contain
5853 only one Bison parser. But what if you want to parse more than one
5854 language with the same program? Then you need to avoid a name conflict
5855 between different definitions of @code{yyparse}, @code{yylval}, and so on.
5856
5857 The easy way to do this is to use the option @samp{-p @var{prefix}}
5858 (@pxref{Invocation, ,Invoking Bison}). This renames the interface
5859 functions and variables of the Bison parser to start with @var{prefix}
5860 instead of @samp{yy}. You can use this to give each parser distinct
5861 names that do not conflict.
5862
5863 The precise list of symbols renamed is @code{yyparse}, @code{yylex},
5864 @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
5865 @code{yychar} and @code{yydebug}. If you use a push parser,
5866 @code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5867 @code{yypstate_new} and @code{yypstate_delete} will also be renamed.
5868 For example, if you use @samp{-p c}, the names become @code{cparse},
5869 @code{clex}, and so on.
5870
5871 @strong{All the other variables and macros associated with Bison are not
5872 renamed.} These others are not global; there is no conflict if the same
5873 name is used in different parsers. For example, @code{YYSTYPE} is not
5874 renamed, but defining this in different ways in different parsers causes
5875 no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
5876
5877 The @samp{-p} option works by adding macro definitions to the
5878 beginning of the parser implementation file, defining @code{yyparse}
5879 as @code{@var{prefix}parse}, and so on. This effectively substitutes
5880 one name for the other in the entire parser implementation file.
5881
5882 @node Interface
5883 @chapter Parser C-Language Interface
5884 @cindex C-language interface
5885 @cindex interface
5886
5887 The Bison parser is actually a C function named @code{yyparse}. Here we
5888 describe the interface conventions of @code{yyparse} and the other
5889 functions that it needs to use.
5890
5891 Keep in mind that the parser uses many C identifiers starting with
5892 @samp{yy} and @samp{YY} for internal purposes. If you use such an
5893 identifier (aside from those in this manual) in an action or in epilogue
5894 in the grammar file, you are likely to run into trouble.
5895
5896 @menu
5897 * Parser Function:: How to call @code{yyparse} and what it returns.
5898 * Push Parser Function:: How to call @code{yypush_parse} and what it returns.
5899 * Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
5900 * Parser Create Function:: How to call @code{yypstate_new} and what it returns.
5901 * Parser Delete Function:: How to call @code{yypstate_delete} and what it returns.
5902 * Lexical:: You must supply a function @code{yylex}
5903 which reads tokens.
5904 * Error Reporting:: You must supply a function @code{yyerror}.
5905 * Action Features:: Special features for use in actions.
5906 * Internationalization:: How to let the parser speak in the user's
5907 native language.
5908 @end menu
5909
5910 @node Parser Function
5911 @section The Parser Function @code{yyparse}
5912 @findex yyparse
5913
5914 You call the function @code{yyparse} to cause parsing to occur. This
5915 function reads tokens, executes actions, and ultimately returns when it
5916 encounters end-of-input or an unrecoverable syntax error. You can also
5917 write an action which directs @code{yyparse} to return immediately
5918 without reading further.
5919
5920
5921 @deftypefun int yyparse (void)
5922 The value returned by @code{yyparse} is 0 if parsing was successful (return
5923 is due to end-of-input).
5924
5925 The value is 1 if parsing failed because of invalid input, i.e., input
5926 that contains a syntax error or that causes @code{YYABORT} to be
5927 invoked.
5928
5929 The value is 2 if parsing failed due to memory exhaustion.
5930 @end deftypefun
5931
5932 In an action, you can cause immediate return from @code{yyparse} by using
5933 these macros:
5934
5935 @defmac YYACCEPT
5936 @findex YYACCEPT
5937 Return immediately with value 0 (to report success).
5938 @end defmac
5939
5940 @defmac YYABORT
5941 @findex YYABORT
5942 Return immediately with value 1 (to report failure).
5943 @end defmac
5944
5945 If you use a reentrant parser, you can optionally pass additional
5946 parameter information to it in a reentrant way. To do so, use the
5947 declaration @code{%parse-param}:
5948
5949 @deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
5950 @findex %parse-param
5951 Declare that one or more
5952 @var{argument-declaration} are additional @code{yyparse} arguments.
5953 The @var{argument-declaration} is used when declaring
5954 functions or prototypes. The last identifier in
5955 @var{argument-declaration} must be the argument name.
5956 @end deffn
5957
5958 Here's an example. Write this in the parser:
5959
5960 @example
5961 %parse-param @{int *nastiness@} @{int *randomness@}
5962 @end example
5963
5964 @noindent
5965 Then call the parser like this:
5966
5967 @example
5968 @{
5969 int nastiness, randomness;
5970 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
5971 value = yyparse (&nastiness, &randomness);
5972 @dots{}
5973 @}
5974 @end example
5975
5976 @noindent
5977 In the grammar actions, use expressions like this to refer to the data:
5978
5979 @example
5980 exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
5981 @end example
5982
5983 @node Push Parser Function
5984 @section The Push Parser Function @code{yypush_parse}
5985 @findex yypush_parse
5986
5987 (The current push parsing interface is experimental and may evolve.
5988 More user feedback will help to stabilize it.)
5989
5990 You call the function @code{yypush_parse} to parse a single token. This
5991 function is available if either the @samp{%define api.push-pull push} or
5992 @samp{%define api.push-pull both} declaration is used.
5993 @xref{Push Decl, ,A Push Parser}.
5994
5995 @deftypefun int yypush_parse (yypstate *yyps)
5996 The value returned by @code{yypush_parse} is the same as for yyparse with the
5997 following exception. @code{yypush_parse} will return YYPUSH_MORE if more input
5998 is required to finish parsing the grammar.
5999 @end deftypefun
6000
6001 @node Pull Parser Function
6002 @section The Pull Parser Function @code{yypull_parse}
6003 @findex yypull_parse
6004
6005 (The current push parsing interface is experimental and may evolve.
6006 More user feedback will help to stabilize it.)
6007
6008 You call the function @code{yypull_parse} to parse the rest of the input
6009 stream. This function is available if the @samp{%define api.push-pull both}
6010 declaration is used.
6011 @xref{Push Decl, ,A Push Parser}.
6012
6013 @deftypefun int yypull_parse (yypstate *yyps)
6014 The value returned by @code{yypull_parse} is the same as for @code{yyparse}.
6015 @end deftypefun
6016
6017 @node Parser Create Function
6018 @section The Parser Create Function @code{yystate_new}
6019 @findex yypstate_new
6020
6021 (The current push parsing interface is experimental and may evolve.
6022 More user feedback will help to stabilize it.)
6023
6024 You call the function @code{yypstate_new} to create a new parser instance.
6025 This function is available if either the @samp{%define api.push-pull push} or
6026 @samp{%define api.push-pull both} declaration is used.
6027 @xref{Push Decl, ,A Push Parser}.
6028
6029 @deftypefun yypstate *yypstate_new (void)
6030 The function will return a valid parser instance if there was memory available
6031 or 0 if no memory was available.
6032 In impure mode, it will also return 0 if a parser instance is currently
6033 allocated.
6034 @end deftypefun
6035
6036 @node Parser Delete Function
6037 @section The Parser Delete Function @code{yystate_delete}
6038 @findex yypstate_delete
6039
6040 (The current push parsing interface is experimental and may evolve.
6041 More user feedback will help to stabilize it.)
6042
6043 You call the function @code{yypstate_delete} to delete a parser instance.
6044 function is available if either the @samp{%define api.push-pull push} or
6045 @samp{%define api.push-pull both} declaration is used.
6046 @xref{Push Decl, ,A Push Parser}.
6047
6048 @deftypefun void yypstate_delete (yypstate *yyps)
6049 This function will reclaim the memory associated with a parser instance.
6050 After this call, you should no longer attempt to use the parser instance.
6051 @end deftypefun
6052
6053 @node Lexical
6054 @section The Lexical Analyzer Function @code{yylex}
6055 @findex yylex
6056 @cindex lexical analyzer
6057
6058 The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
6059 the input stream and returns them to the parser. Bison does not create
6060 this function automatically; you must write it so that @code{yyparse} can
6061 call it. The function is sometimes referred to as a lexical scanner.
6062
6063 In simple programs, @code{yylex} is often defined at the end of the
6064 Bison grammar file. If @code{yylex} is defined in a separate source
6065 file, you need to arrange for the token-type macro definitions to be
6066 available there. To do this, use the @samp{-d} option when you run
6067 Bison, so that it will write these macro definitions into the separate
6068 parser header file, @file{@var{name}.tab.h}, which you can include in
6069 the other source files that need it. @xref{Invocation, ,Invoking
6070 Bison}.
6071
6072 @menu
6073 * Calling Convention:: How @code{yyparse} calls @code{yylex}.
6074 * Token Values:: How @code{yylex} must return the semantic value
6075 of the token it has read.
6076 * Token Locations:: How @code{yylex} must return the text location
6077 (line number, etc.) of the token, if the
6078 actions want that.
6079 * Pure Calling:: How the calling convention differs in a pure parser
6080 (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
6081 @end menu
6082
6083 @node Calling Convention
6084 @subsection Calling Convention for @code{yylex}
6085
6086 The value that @code{yylex} returns must be the positive numeric code
6087 for the type of token it has just found; a zero or negative value
6088 signifies end-of-input.
6089
6090 When a token is referred to in the grammar rules by a name, that name
6091 in the parser implementation file becomes a C macro whose definition
6092 is the proper numeric code for that token type. So @code{yylex} can
6093 use the name to indicate that type. @xref{Symbols}.
6094
6095 When a token is referred to in the grammar rules by a character literal,
6096 the numeric code for that character is also the code for the token type.
6097 So @code{yylex} can simply return that character code, possibly converted
6098 to @code{unsigned char} to avoid sign-extension. The null character
6099 must not be used this way, because its code is zero and that
6100 signifies end-of-input.
6101
6102 Here is an example showing these things:
6103
6104 @example
6105 int
6106 yylex (void)
6107 @{
6108 @dots{}
6109 if (c == EOF) /* Detect end-of-input. */
6110 return 0;
6111 @dots{}
6112 if (c == '+' || c == '-')
6113 return c; /* Assume token type for `+' is '+'. */
6114 @dots{}
6115 return INT; /* Return the type of the token. */
6116 @dots{}
6117 @}
6118 @end example
6119
6120 @noindent
6121 This interface has been designed so that the output from the @code{lex}
6122 utility can be used without change as the definition of @code{yylex}.
6123
6124 If the grammar uses literal string tokens, there are two ways that
6125 @code{yylex} can determine the token type codes for them:
6126
6127 @itemize @bullet
6128 @item
6129 If the grammar defines symbolic token names as aliases for the
6130 literal string tokens, @code{yylex} can use these symbolic names like
6131 all others. In this case, the use of the literal string tokens in
6132 the grammar file has no effect on @code{yylex}.
6133
6134 @item
6135 @code{yylex} can find the multicharacter token in the @code{yytname}
6136 table. The index of the token in the table is the token type's code.
6137 The name of a multicharacter token is recorded in @code{yytname} with a
6138 double-quote, the token's characters, and another double-quote. The
6139 token's characters are escaped as necessary to be suitable as input
6140 to Bison.
6141
6142 Here's code for looking up a multicharacter token in @code{yytname},
6143 assuming that the characters of the token are stored in
6144 @code{token_buffer}, and assuming that the token does not contain any
6145 characters like @samp{"} that require escaping.
6146
6147 @smallexample
6148 for (i = 0; i < YYNTOKENS; i++)
6149 @{
6150 if (yytname[i] != 0
6151 && yytname[i][0] == '"'
6152 && ! strncmp (yytname[i] + 1, token_buffer,
6153 strlen (token_buffer))
6154 && yytname[i][strlen (token_buffer) + 1] == '"'
6155 && yytname[i][strlen (token_buffer) + 2] == 0)
6156 break;
6157 @}
6158 @end smallexample
6159
6160 The @code{yytname} table is generated only if you use the
6161 @code{%token-table} declaration. @xref{Decl Summary}.
6162 @end itemize
6163
6164 @node Token Values
6165 @subsection Semantic Values of Tokens
6166
6167 @vindex yylval
6168 In an ordinary (nonreentrant) parser, the semantic value of the token must
6169 be stored into the global variable @code{yylval}. When you are using
6170 just one data type for semantic values, @code{yylval} has that type.
6171 Thus, if the type is @code{int} (the default), you might write this in
6172 @code{yylex}:
6173
6174 @example
6175 @group
6176 @dots{}
6177 yylval = value; /* Put value onto Bison stack. */
6178 return INT; /* Return the type of the token. */
6179 @dots{}
6180 @end group
6181 @end example
6182
6183 When you are using multiple data types, @code{yylval}'s type is a union
6184 made from the @code{%union} declaration (@pxref{Union Decl, ,The
6185 Collection of Value Types}). So when you store a token's value, you
6186 must use the proper member of the union. If the @code{%union}
6187 declaration looks like this:
6188
6189 @example
6190 @group
6191 %union @{
6192 int intval;
6193 double val;
6194 symrec *tptr;
6195 @}
6196 @end group
6197 @end example
6198
6199 @noindent
6200 then the code in @code{yylex} might look like this:
6201
6202 @example
6203 @group
6204 @dots{}
6205 yylval.intval = value; /* Put value onto Bison stack. */
6206 return INT; /* Return the type of the token. */
6207 @dots{}
6208 @end group
6209 @end example
6210
6211 @node Token Locations
6212 @subsection Textual Locations of Tokens
6213
6214 @vindex yylloc
6215 If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
6216 Tracking Locations}) in actions to keep track of the textual locations
6217 of tokens and groupings, then you must provide this information in
6218 @code{yylex}. The function @code{yyparse} expects to find the textual
6219 location of a token just parsed in the global variable @code{yylloc}.
6220 So @code{yylex} must store the proper data in that variable.
6221
6222 By default, the value of @code{yylloc} is a structure and you need only
6223 initialize the members that are going to be used by the actions. The
6224 four members are called @code{first_line}, @code{first_column},
6225 @code{last_line} and @code{last_column}. Note that the use of this
6226 feature makes the parser noticeably slower.
6227
6228 @tindex YYLTYPE
6229 The data type of @code{yylloc} has the name @code{YYLTYPE}.
6230
6231 @node Pure Calling
6232 @subsection Calling Conventions for Pure Parsers
6233
6234 When you use the Bison declaration @samp{%define api.pure} to request a
6235 pure, reentrant parser, the global communication variables @code{yylval}
6236 and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
6237 Parser}.) In such parsers the two global variables are replaced by
6238 pointers passed as arguments to @code{yylex}. You must declare them as
6239 shown here, and pass the information back by storing it through those
6240 pointers.
6241
6242 @example
6243 int
6244 yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
6245 @{
6246 @dots{}
6247 *lvalp = value; /* Put value onto Bison stack. */
6248 return INT; /* Return the type of the token. */
6249 @dots{}
6250 @}
6251 @end example
6252
6253 If the grammar file does not use the @samp{@@} constructs to refer to
6254 textual locations, then the type @code{YYLTYPE} will not be defined. In
6255 this case, omit the second argument; @code{yylex} will be called with
6256 only one argument.
6257
6258 If you wish to pass additional arguments to @code{yylex}, use
6259 @code{%lex-param} just like @code{%parse-param} (@pxref{Parser
6260 Function}). To pass additional arguments to both @code{yylex} and
6261 @code{yyparse}, use @code{%param}.
6262
6263 @deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
6264 @findex %lex-param
6265 Specify that @var{argument-declaration} are additional @code{yylex} argument
6266 declarations. You may pass one or more such declarations, which is
6267 equivalent to repeating @code{%lex-param}.
6268 @end deffn
6269
6270 @deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
6271 @findex %param
6272 Specify that @var{argument-declaration} are additional
6273 @code{yylex}/@code{yyparse} argument declaration. This is equivalent to
6274 @samp{%lex-param @{@var{argument-declaration}@} @dots{} %parse-param
6275 @{@var{argument-declaration}@} @dots{}}. You may pass one or more
6276 declarations, which is equivalent to repeating @code{%param}.
6277 @end deffn
6278
6279 For instance:
6280
6281 @example
6282 %lex-param @{scanner_mode *mode@}
6283 %parse-param @{parser_mode *mode@}
6284 %param @{environment_type *env@}
6285 @end example
6286
6287 @noindent
6288 results in the following signature:
6289
6290 @example
6291 int yylex (scanner_mode *mode, environment_type *env);
6292 int yyparse (parser_mode *mode, environment_type *env);
6293 @end example
6294
6295 If @samp{%define api.pure} is added:
6296
6297 @example
6298 int yylex (YYSTYPE *lvalp, scanner_mode *mode, environment_type *env);
6299 int yyparse (parser_mode *mode, environment_type *env);
6300 @end example
6301
6302 @noindent
6303 and finally, if both @samp{%define api.pure} and @code{%locations} are used:
6304
6305 @example
6306 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp,
6307 scanner_mode *mode, environment_type *env);
6308 int yyparse (parser_mode *mode, environment_type *env);
6309 @end example
6310
6311 @node Error Reporting
6312 @section The Error Reporting Function @code{yyerror}
6313 @cindex error reporting function
6314 @findex yyerror
6315 @cindex parse error
6316 @cindex syntax error
6317
6318 The Bison parser detects a @dfn{syntax error} (or @dfn{parse error})
6319 whenever it reads a token which cannot satisfy any syntax rule. An
6320 action in the grammar can also explicitly proclaim an error, using the
6321 macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
6322 in Actions}).
6323
6324 The Bison parser expects to report the error by calling an error
6325 reporting function named @code{yyerror}, which you must supply. It is
6326 called by @code{yyparse} whenever a syntax error is found, and it
6327 receives one argument. For a syntax error, the string is normally
6328 @w{@code{"syntax error"}}.
6329
6330 @findex %define parse.error
6331 If you invoke @samp{%define parse.error verbose} in the Bison
6332 declarations section (@pxref{Bison Declarations, ,The Bison Declarations
6333 Section}), then Bison provides a more verbose and specific error message
6334 string instead of just plain @w{@code{"syntax error"}}.
6335
6336 The parser can detect one other kind of error: memory exhaustion. This
6337 can happen when the input contains constructions that are very deeply
6338 nested. It isn't likely you will encounter this, since the Bison
6339 parser normally extends its stack automatically up to a very large limit. But
6340 if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
6341 fashion, except that the argument string is @w{@code{"memory exhausted"}}.
6342
6343 In some cases diagnostics like @w{@code{"syntax error"}} are
6344 translated automatically from English to some other language before
6345 they are passed to @code{yyerror}. @xref{Internationalization}.
6346
6347 The following definition suffices in simple programs:
6348
6349 @example
6350 @group
6351 void
6352 yyerror (char const *s)
6353 @{
6354 @end group
6355 @group
6356 fprintf (stderr, "%s\n", s);
6357 @}
6358 @end group
6359 @end example
6360
6361 After @code{yyerror} returns to @code{yyparse}, the latter will attempt
6362 error recovery if you have written suitable error recovery grammar rules
6363 (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
6364 immediately return 1.
6365
6366 Obviously, in location tracking pure parsers, @code{yyerror} should have
6367 an access to the current location.
6368 This is indeed the case for the GLR
6369 parsers, but not for the Yacc parser, for historical reasons. I.e., if
6370 @samp{%locations %define api.pure} is passed then the prototypes for
6371 @code{yyerror} are:
6372
6373 @example
6374 void yyerror (char const *msg); /* Yacc parsers. */
6375 void yyerror (YYLTYPE *locp, char const *msg); /* GLR parsers. */
6376 @end example
6377
6378 If @samp{%parse-param @{int *nastiness@}} is used, then:
6379
6380 @example
6381 void yyerror (int *nastiness, char const *msg); /* Yacc parsers. */
6382 void yyerror (int *nastiness, char const *msg); /* GLR parsers. */
6383 @end example
6384
6385 Finally, GLR and Yacc parsers share the same @code{yyerror} calling
6386 convention for absolutely pure parsers, i.e., when the calling
6387 convention of @code{yylex} @emph{and} the calling convention of
6388 @samp{%define api.pure} are pure.
6389 I.e.:
6390
6391 @example
6392 /* Location tracking. */
6393 %locations
6394 /* Pure yylex. */
6395 %define api.pure
6396 %lex-param @{int *nastiness@}
6397 /* Pure yyparse. */
6398 %parse-param @{int *nastiness@}
6399 %parse-param @{int *randomness@}
6400 @end example
6401
6402 @noindent
6403 results in the following signatures for all the parser kinds:
6404
6405 @example
6406 int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
6407 int yyparse (int *nastiness, int *randomness);
6408 void yyerror (YYLTYPE *locp,
6409 int *nastiness, int *randomness,
6410 char const *msg);
6411 @end example
6412
6413 @noindent
6414 The prototypes are only indications of how the code produced by Bison
6415 uses @code{yyerror}. Bison-generated code always ignores the returned
6416 value, so @code{yyerror} can return any type, including @code{void}.
6417 Also, @code{yyerror} can be a variadic function; that is why the
6418 message is always passed last.
6419
6420 Traditionally @code{yyerror} returns an @code{int} that is always
6421 ignored, but this is purely for historical reasons, and @code{void} is
6422 preferable since it more accurately describes the return type for
6423 @code{yyerror}.
6424
6425 @vindex yynerrs
6426 The variable @code{yynerrs} contains the number of syntax errors
6427 reported so far. Normally this variable is global; but if you
6428 request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
6429 then it is a local variable which only the actions can access.
6430
6431 @node Action Features
6432 @section Special Features for Use in Actions
6433 @cindex summary, action features
6434 @cindex action features summary
6435
6436 Here is a table of Bison constructs, variables and macros that
6437 are useful in actions.
6438
6439 @deffn {Variable} $$
6440 Acts like a variable that contains the semantic value for the
6441 grouping made by the current rule. @xref{Actions}.
6442 @end deffn
6443
6444 @deffn {Variable} $@var{n}
6445 Acts like a variable that contains the semantic value for the
6446 @var{n}th component of the current rule. @xref{Actions}.
6447 @end deffn
6448
6449 @deffn {Variable} $<@var{typealt}>$
6450 Like @code{$$} but specifies alternative @var{typealt} in the union
6451 specified by the @code{%union} declaration. @xref{Action Types, ,Data
6452 Types of Values in Actions}.
6453 @end deffn
6454
6455 @deffn {Variable} $<@var{typealt}>@var{n}
6456 Like @code{$@var{n}} but specifies alternative @var{typealt} in the
6457 union specified by the @code{%union} declaration.
6458 @xref{Action Types, ,Data Types of Values in Actions}.
6459 @end deffn
6460
6461 @deffn {Macro} YYABORT;
6462 Return immediately from @code{yyparse}, indicating failure.
6463 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6464 @end deffn
6465
6466 @deffn {Macro} YYACCEPT;
6467 Return immediately from @code{yyparse}, indicating success.
6468 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6469 @end deffn
6470
6471 @deffn {Macro} YYBACKUP (@var{token}, @var{value});
6472 @findex YYBACKUP
6473 Unshift a token. This macro is allowed only for rules that reduce
6474 a single value, and only when there is no lookahead token.
6475 It is also disallowed in GLR parsers.
6476 It installs a lookahead token with token type @var{token} and
6477 semantic value @var{value}; then it discards the value that was
6478 going to be reduced by this rule.
6479
6480 If the macro is used when it is not valid, such as when there is
6481 a lookahead token already, then it reports a syntax error with
6482 a message @samp{cannot back up} and performs ordinary error
6483 recovery.
6484
6485 In either case, the rest of the action is not executed.
6486 @end deffn
6487
6488 @deffn {Macro} YYEMPTY
6489 @vindex YYEMPTY
6490 Value stored in @code{yychar} when there is no lookahead token.
6491 @end deffn
6492
6493 @deffn {Macro} YYEOF
6494 @vindex YYEOF
6495 Value stored in @code{yychar} when the lookahead is the end of the input
6496 stream.
6497 @end deffn
6498
6499 @deffn {Macro} YYERROR;
6500 @findex YYERROR
6501 Cause an immediate syntax error. This statement initiates error
6502 recovery just as if the parser itself had detected an error; however, it
6503 does not call @code{yyerror}, and does not print any message. If you
6504 want to print an error message, call @code{yyerror} explicitly before
6505 the @samp{YYERROR;} statement. @xref{Error Recovery}.
6506 @end deffn
6507
6508 @deffn {Macro} YYRECOVERING
6509 @findex YYRECOVERING
6510 The expression @code{YYRECOVERING ()} yields 1 when the parser
6511 is recovering from a syntax error, and 0 otherwise.
6512 @xref{Error Recovery}.
6513 @end deffn
6514
6515 @deffn {Variable} yychar
6516 Variable containing either the lookahead token, or @code{YYEOF} when the
6517 lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
6518 has been performed so the next token is not yet known.
6519 Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
6520 Actions}).
6521 @xref{Lookahead, ,Lookahead Tokens}.
6522 @end deffn
6523
6524 @deffn {Macro} yyclearin;
6525 Discard the current lookahead token. This is useful primarily in
6526 error rules.
6527 Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
6528 Semantic Actions}).
6529 @xref{Error Recovery}.
6530 @end deffn
6531
6532 @deffn {Macro} yyerrok;
6533 Resume generating error messages immediately for subsequent syntax
6534 errors. This is useful primarily in error rules.
6535 @xref{Error Recovery}.
6536 @end deffn
6537
6538 @deffn {Variable} yylloc
6539 Variable containing the lookahead token location when @code{yychar} is not set
6540 to @code{YYEMPTY} or @code{YYEOF}.
6541 Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
6542 Actions}).
6543 @xref{Actions and Locations, ,Actions and Locations}.
6544 @end deffn
6545
6546 @deffn {Variable} yylval
6547 Variable containing the lookahead token semantic value when @code{yychar} is
6548 not set to @code{YYEMPTY} or @code{YYEOF}.
6549 Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
6550 Actions}).
6551 @xref{Actions, ,Actions}.
6552 @end deffn
6553
6554 @deffn {Value} @@$
6555 @findex @@$
6556 Acts like a structure variable containing information on the textual location
6557 of the grouping made by the current rule. @xref{Locations, ,
6558 Tracking Locations}.
6559
6560 @c Check if those paragraphs are still useful or not.
6561
6562 @c @example
6563 @c struct @{
6564 @c int first_line, last_line;
6565 @c int first_column, last_column;
6566 @c @};
6567 @c @end example
6568
6569 @c Thus, to get the starting line number of the third component, you would
6570 @c use @samp{@@3.first_line}.
6571
6572 @c In order for the members of this structure to contain valid information,
6573 @c you must make @code{yylex} supply this information about each token.
6574 @c If you need only certain members, then @code{yylex} need only fill in
6575 @c those members.
6576
6577 @c The use of this feature makes the parser noticeably slower.
6578 @end deffn
6579
6580 @deffn {Value} @@@var{n}
6581 @findex @@@var{n}
6582 Acts like a structure variable containing information on the textual location
6583 of the @var{n}th component of the current rule. @xref{Locations, ,
6584 Tracking Locations}.
6585 @end deffn
6586
6587 @node Internationalization
6588 @section Parser Internationalization
6589 @cindex internationalization
6590 @cindex i18n
6591 @cindex NLS
6592 @cindex gettext
6593 @cindex bison-po
6594
6595 A Bison-generated parser can print diagnostics, including error and
6596 tracing messages. By default, they appear in English. However, Bison
6597 also supports outputting diagnostics in the user's native language. To
6598 make this work, the user should set the usual environment variables.
6599 @xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
6600 For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
6601 set the user's locale to French Canadian using the UTF-8
6602 encoding. The exact set of available locales depends on the user's
6603 installation.
6604
6605 The maintainer of a package that uses a Bison-generated parser enables
6606 the internationalization of the parser's output through the following
6607 steps. Here we assume a package that uses GNU Autoconf and
6608 GNU Automake.
6609
6610 @enumerate
6611 @item
6612 @cindex bison-i18n.m4
6613 Into the directory containing the GNU Autoconf macros used
6614 by the package---often called @file{m4}---copy the
6615 @file{bison-i18n.m4} file installed by Bison under
6616 @samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
6617 For example:
6618
6619 @example
6620 cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
6621 @end example
6622
6623 @item
6624 @findex BISON_I18N
6625 @vindex BISON_LOCALEDIR
6626 @vindex YYENABLE_NLS
6627 In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
6628 invocation, add an invocation of @code{BISON_I18N}. This macro is
6629 defined in the file @file{bison-i18n.m4} that you copied earlier. It
6630 causes @samp{configure} to find the value of the
6631 @code{BISON_LOCALEDIR} variable, and it defines the source-language
6632 symbol @code{YYENABLE_NLS} to enable translations in the
6633 Bison-generated parser.
6634
6635 @item
6636 In the @code{main} function of your program, designate the directory
6637 containing Bison's runtime message catalog, through a call to
6638 @samp{bindtextdomain} with domain name @samp{bison-runtime}.
6639 For example:
6640
6641 @example
6642 bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
6643 @end example
6644
6645 Typically this appears after any other call @code{bindtextdomain
6646 (PACKAGE, LOCALEDIR)} that your package already has. Here we rely on
6647 @samp{BISON_LOCALEDIR} to be defined as a string through the
6648 @file{Makefile}.
6649
6650 @item
6651 In the @file{Makefile.am} that controls the compilation of the @code{main}
6652 function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
6653 either in @samp{DEFS} or in @samp{AM_CPPFLAGS}. For example:
6654
6655 @example
6656 DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6657 @end example
6658
6659 or:
6660
6661 @example
6662 AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6663 @end example
6664
6665 @item
6666 Finally, invoke the command @command{autoreconf} to generate the build
6667 infrastructure.
6668 @end enumerate
6669
6670
6671 @node Algorithm
6672 @chapter The Bison Parser Algorithm
6673 @cindex Bison parser algorithm
6674 @cindex algorithm of parser
6675 @cindex shifting
6676 @cindex reduction
6677 @cindex parser stack
6678 @cindex stack, parser
6679
6680 As Bison reads tokens, it pushes them onto a stack along with their
6681 semantic values. The stack is called the @dfn{parser stack}. Pushing a
6682 token is traditionally called @dfn{shifting}.
6683
6684 For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
6685 @samp{3} to come. The stack will have four elements, one for each token
6686 that was shifted.
6687
6688 But the stack does not always have an element for each token read. When
6689 the last @var{n} tokens and groupings shifted match the components of a
6690 grammar rule, they can be combined according to that rule. This is called
6691 @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
6692 single grouping whose symbol is the result (left hand side) of that rule.
6693 Running the rule's action is part of the process of reduction, because this
6694 is what computes the semantic value of the resulting grouping.
6695
6696 For example, if the infix calculator's parser stack contains this:
6697
6698 @example
6699 1 + 5 * 3
6700 @end example
6701
6702 @noindent
6703 and the next input token is a newline character, then the last three
6704 elements can be reduced to 15 via the rule:
6705
6706 @example
6707 expr: expr '*' expr;
6708 @end example
6709
6710 @noindent
6711 Then the stack contains just these three elements:
6712
6713 @example
6714 1 + 15
6715 @end example
6716
6717 @noindent
6718 At this point, another reduction can be made, resulting in the single value
6719 16. Then the newline token can be shifted.
6720
6721 The parser tries, by shifts and reductions, to reduce the entire input down
6722 to a single grouping whose symbol is the grammar's start-symbol
6723 (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
6724
6725 This kind of parser is known in the literature as a bottom-up parser.
6726
6727 @menu
6728 * Lookahead:: Parser looks one token ahead when deciding what to do.
6729 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
6730 * Precedence:: Operator precedence works by resolving conflicts.
6731 * Contextual Precedence:: When an operator's precedence depends on context.
6732 * Parser States:: The parser is a finite-state-machine with stack.
6733 * Reduce/Reduce:: When two rules are applicable in the same situation.
6734 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
6735 * Generalized LR Parsing:: Parsing arbitrary context-free grammars.
6736 * Memory Management:: What happens when memory is exhausted. How to avoid it.
6737 @end menu
6738
6739 @node Lookahead
6740 @section Lookahead Tokens
6741 @cindex lookahead token
6742
6743 The Bison parser does @emph{not} always reduce immediately as soon as the
6744 last @var{n} tokens and groupings match a rule. This is because such a
6745 simple strategy is inadequate to handle most languages. Instead, when a
6746 reduction is possible, the parser sometimes ``looks ahead'' at the next
6747 token in order to decide what to do.
6748
6749 When a token is read, it is not immediately shifted; first it becomes the
6750 @dfn{lookahead token}, which is not on the stack. Now the parser can
6751 perform one or more reductions of tokens and groupings on the stack, while
6752 the lookahead token remains off to the side. When no more reductions
6753 should take place, the lookahead token is shifted onto the stack. This
6754 does not mean that all possible reductions have been done; depending on the
6755 token type of the lookahead token, some rules may choose to delay their
6756 application.
6757
6758 Here is a simple case where lookahead is needed. These three rules define
6759 expressions which contain binary addition operators and postfix unary
6760 factorial operators (@samp{!}), and allow parentheses for grouping.
6761
6762 @example
6763 @group
6764 expr: term '+' expr
6765 | term
6766 ;
6767 @end group
6768
6769 @group
6770 term: '(' expr ')'
6771 | term '!'
6772 | NUMBER
6773 ;
6774 @end group
6775 @end example
6776
6777 Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
6778 should be done? If the following token is @samp{)}, then the first three
6779 tokens must be reduced to form an @code{expr}. This is the only valid
6780 course, because shifting the @samp{)} would produce a sequence of symbols
6781 @w{@code{term ')'}}, and no rule allows this.
6782
6783 If the following token is @samp{!}, then it must be shifted immediately so
6784 that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
6785 parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
6786 @code{expr}. It would then be impossible to shift the @samp{!} because
6787 doing so would produce on the stack the sequence of symbols @code{expr
6788 '!'}. No rule allows that sequence.
6789
6790 @vindex yychar
6791 @vindex yylval
6792 @vindex yylloc
6793 The lookahead token is stored in the variable @code{yychar}.
6794 Its semantic value and location, if any, are stored in the variables
6795 @code{yylval} and @code{yylloc}.
6796 @xref{Action Features, ,Special Features for Use in Actions}.
6797
6798 @node Shift/Reduce
6799 @section Shift/Reduce Conflicts
6800 @cindex conflicts
6801 @cindex shift/reduce conflicts
6802 @cindex dangling @code{else}
6803 @cindex @code{else}, dangling
6804
6805 Suppose we are parsing a language which has if-then and if-then-else
6806 statements, with a pair of rules like this:
6807
6808 @example
6809 @group
6810 if_stmt:
6811 IF expr THEN stmt
6812 | IF expr THEN stmt ELSE stmt
6813 ;
6814 @end group
6815 @end example
6816
6817 @noindent
6818 Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
6819 terminal symbols for specific keyword tokens.
6820
6821 When the @code{ELSE} token is read and becomes the lookahead token, the
6822 contents of the stack (assuming the input is valid) are just right for
6823 reduction by the first rule. But it is also legitimate to shift the
6824 @code{ELSE}, because that would lead to eventual reduction by the second
6825 rule.
6826
6827 This situation, where either a shift or a reduction would be valid, is
6828 called a @dfn{shift/reduce conflict}. Bison is designed to resolve
6829 these conflicts by choosing to shift, unless otherwise directed by
6830 operator precedence declarations. To see the reason for this, let's
6831 contrast it with the other alternative.
6832
6833 Since the parser prefers to shift the @code{ELSE}, the result is to attach
6834 the else-clause to the innermost if-statement, making these two inputs
6835 equivalent:
6836
6837 @example
6838 if x then if y then win (); else lose;
6839
6840 if x then do; if y then win (); else lose; end;
6841 @end example
6842
6843 But if the parser chose to reduce when possible rather than shift, the
6844 result would be to attach the else-clause to the outermost if-statement,
6845 making these two inputs equivalent:
6846
6847 @example
6848 if x then if y then win (); else lose;
6849
6850 if x then do; if y then win (); end; else lose;
6851 @end example
6852
6853 The conflict exists because the grammar as written is ambiguous: either
6854 parsing of the simple nested if-statement is legitimate. The established
6855 convention is that these ambiguities are resolved by attaching the
6856 else-clause to the innermost if-statement; this is what Bison accomplishes
6857 by choosing to shift rather than reduce. (It would ideally be cleaner to
6858 write an unambiguous grammar, but that is very hard to do in this case.)
6859 This particular ambiguity was first encountered in the specifications of
6860 Algol 60 and is called the ``dangling @code{else}'' ambiguity.
6861
6862 To avoid warnings from Bison about predictable, legitimate shift/reduce
6863 conflicts, use the @code{%expect @var{n}} declaration.
6864 There will be no warning as long as the number of shift/reduce conflicts
6865 is exactly @var{n}, and Bison will report an error if there is a
6866 different number.
6867 @xref{Expect Decl, ,Suppressing Conflict Warnings}.
6868
6869 The definition of @code{if_stmt} above is solely to blame for the
6870 conflict, but the conflict does not actually appear without additional
6871 rules. Here is a complete Bison grammar file that actually manifests
6872 the conflict:
6873
6874 @example
6875 @group
6876 %token IF THEN ELSE variable
6877 %%
6878 @end group
6879 @group
6880 stmt: expr
6881 | if_stmt
6882 ;
6883 @end group
6884
6885 @group
6886 if_stmt:
6887 IF expr THEN stmt
6888 | IF expr THEN stmt ELSE stmt
6889 ;
6890 @end group
6891
6892 expr: variable
6893 ;
6894 @end example
6895
6896 @node Precedence
6897 @section Operator Precedence
6898 @cindex operator precedence
6899 @cindex precedence of operators
6900
6901 Another situation where shift/reduce conflicts appear is in arithmetic
6902 expressions. Here shifting is not always the preferred resolution; the
6903 Bison declarations for operator precedence allow you to specify when to
6904 shift and when to reduce.
6905
6906 @menu
6907 * Why Precedence:: An example showing why precedence is needed.
6908 * Using Precedence:: How to specify precedence and associativity.
6909 * Precedence Only:: How to specify precedence only.
6910 * Precedence Examples:: How these features are used in the previous example.
6911 * How Precedence:: How they work.
6912 @end menu
6913
6914 @node Why Precedence
6915 @subsection When Precedence is Needed
6916
6917 Consider the following ambiguous grammar fragment (ambiguous because the
6918 input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
6919
6920 @example
6921 @group
6922 expr: expr '-' expr
6923 | expr '*' expr
6924 | expr '<' expr
6925 | '(' expr ')'
6926 @dots{}
6927 ;
6928 @end group
6929 @end example
6930
6931 @noindent
6932 Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
6933 should it reduce them via the rule for the subtraction operator? It
6934 depends on the next token. Of course, if the next token is @samp{)}, we
6935 must reduce; shifting is invalid because no single rule can reduce the
6936 token sequence @w{@samp{- 2 )}} or anything starting with that. But if
6937 the next token is @samp{*} or @samp{<}, we have a choice: either
6938 shifting or reduction would allow the parse to complete, but with
6939 different results.
6940
6941 To decide which one Bison should do, we must consider the results. If
6942 the next operator token @var{op} is shifted, then it must be reduced
6943 first in order to permit another opportunity to reduce the difference.
6944 The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
6945 hand, if the subtraction is reduced before shifting @var{op}, the result
6946 is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
6947 reduce should depend on the relative precedence of the operators
6948 @samp{-} and @var{op}: @samp{*} should be shifted first, but not
6949 @samp{<}.
6950
6951 @cindex associativity
6952 What about input such as @w{@samp{1 - 2 - 5}}; should this be
6953 @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
6954 operators we prefer the former, which is called @dfn{left association}.
6955 The latter alternative, @dfn{right association}, is desirable for
6956 assignment operators. The choice of left or right association is a
6957 matter of whether the parser chooses to shift or reduce when the stack
6958 contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
6959 makes right-associativity.
6960
6961 @node Using Precedence
6962 @subsection Specifying Operator Precedence
6963 @findex %left
6964 @findex %nonassoc
6965 @findex %precedence
6966 @findex %right
6967
6968 Bison allows you to specify these choices with the operator precedence
6969 declarations @code{%left} and @code{%right}. Each such declaration
6970 contains a list of tokens, which are operators whose precedence and
6971 associativity is being declared. The @code{%left} declaration makes all
6972 those operators left-associative and the @code{%right} declaration makes
6973 them right-associative. A third alternative is @code{%nonassoc}, which
6974 declares that it is a syntax error to find the same operator twice ``in a
6975 row''.
6976 The last alternative, @code{%precedence}, allows to define only
6977 precedence and no associativity at all. As a result, any
6978 associativity-related conflict that remains will be reported as an
6979 compile-time error. The directive @code{%nonassoc} creates run-time
6980 error: using the operator in a associative way is a syntax error. The
6981 directive @code{%precedence} creates compile-time errors: an operator
6982 @emph{can} be involved in an associativity-related conflict, contrary to
6983 what expected the grammar author.
6984
6985 The relative precedence of different operators is controlled by the
6986 order in which they are declared. The first precedence/associativity
6987 declaration in the file declares the operators whose
6988 precedence is lowest, the next such declaration declares the operators
6989 whose precedence is a little higher, and so on.
6990
6991 @node Precedence Only
6992 @subsection Specifying Precedence Only
6993 @findex %precedence
6994
6995 Since POSIX Yacc defines only @code{%left}, @code{%right}, and
6996 @code{%nonassoc}, which all defines precedence and associativity, little
6997 attention is paid to the fact that precedence cannot be defined without
6998 defining associativity. Yet, sometimes, when trying to solve a
6999 conflict, precedence suffices. In such a case, using @code{%left},
7000 @code{%right}, or @code{%nonassoc} might hide future (associativity
7001 related) conflicts that would remain hidden.
7002
7003 The dangling @code{else} ambiguity (@pxref{Shift/Reduce, , Shift/Reduce
7004 Conflicts}) can be solved explicitly. This shift/reduce conflicts occurs
7005 in the following situation, where the period denotes the current parsing
7006 state:
7007
7008 @example
7009 if @var{e1} then if @var{e2} then @var{s1} . else @var{s2}
7010 @end example
7011
7012 The conflict involves the reduction of the rule @samp{IF expr THEN
7013 stmt}, which precedence is by default that of its last token
7014 (@code{THEN}), and the shifting of the token @code{ELSE}. The usual
7015 disambiguation (attach the @code{else} to the closest @code{if}),
7016 shifting must be preferred, i.e., the precedence of @code{ELSE} must be
7017 higher than that of @code{THEN}. But neither is expected to be involved
7018 in an associativity related conflict, which can be specified as follows.
7019
7020 @example
7021 %precedence THEN
7022 %precedence ELSE
7023 @end example
7024
7025 The unary-minus is another typical example where associativity is
7026 usually over-specified, see @ref{Infix Calc, , Infix Notation
7027 Calculator: @code{calc}}. The @code{%left} directive is traditionally
7028 used to declare the precedence of @code{NEG}, which is more than needed
7029 since it also defines its associativity. While this is harmless in the
7030 traditional example, who knows how @code{NEG} might be used in future
7031 evolutions of the grammar@dots{}
7032
7033 @node Precedence Examples
7034 @subsection Precedence Examples
7035
7036 In our example, we would want the following declarations:
7037
7038 @example
7039 %left '<'
7040 %left '-'
7041 %left '*'
7042 @end example
7043
7044 In a more complete example, which supports other operators as well, we
7045 would declare them in groups of equal precedence. For example, @code{'+'} is
7046 declared with @code{'-'}:
7047
7048 @example
7049 %left '<' '>' '=' NE LE GE
7050 %left '+' '-'
7051 %left '*' '/'
7052 @end example
7053
7054 @noindent
7055 (Here @code{NE} and so on stand for the operators for ``not equal''
7056 and so on. We assume that these tokens are more than one character long
7057 and therefore are represented by names, not character literals.)
7058
7059 @node How Precedence
7060 @subsection How Precedence Works
7061
7062 The first effect of the precedence declarations is to assign precedence
7063 levels to the terminal symbols declared. The second effect is to assign
7064 precedence levels to certain rules: each rule gets its precedence from
7065 the last terminal symbol mentioned in the components. (You can also
7066 specify explicitly the precedence of a rule. @xref{Contextual
7067 Precedence, ,Context-Dependent Precedence}.)
7068
7069 Finally, the resolution of conflicts works by comparing the precedence
7070 of the rule being considered with that of the lookahead token. If the
7071 token's precedence is higher, the choice is to shift. If the rule's
7072 precedence is higher, the choice is to reduce. If they have equal
7073 precedence, the choice is made based on the associativity of that
7074 precedence level. The verbose output file made by @samp{-v}
7075 (@pxref{Invocation, ,Invoking Bison}) says how each conflict was
7076 resolved.
7077
7078 Not all rules and not all tokens have precedence. If either the rule or
7079 the lookahead token has no precedence, then the default is to shift.
7080
7081 @node Contextual Precedence
7082 @section Context-Dependent Precedence
7083 @cindex context-dependent precedence
7084 @cindex unary operator precedence
7085 @cindex precedence, context-dependent
7086 @cindex precedence, unary operator
7087 @findex %prec
7088
7089 Often the precedence of an operator depends on the context. This sounds
7090 outlandish at first, but it is really very common. For example, a minus
7091 sign typically has a very high precedence as a unary operator, and a
7092 somewhat lower precedence (lower than multiplication) as a binary operator.
7093
7094 The Bison precedence declarations
7095 can only be used once for a given token; so a token has
7096 only one precedence declared in this way. For context-dependent
7097 precedence, you need to use an additional mechanism: the @code{%prec}
7098 modifier for rules.
7099
7100 The @code{%prec} modifier declares the precedence of a particular rule by
7101 specifying a terminal symbol whose precedence should be used for that rule.
7102 It's not necessary for that symbol to appear otherwise in the rule. The
7103 modifier's syntax is:
7104
7105 @example
7106 %prec @var{terminal-symbol}
7107 @end example
7108
7109 @noindent
7110 and it is written after the components of the rule. Its effect is to
7111 assign the rule the precedence of @var{terminal-symbol}, overriding
7112 the precedence that would be deduced for it in the ordinary way. The
7113 altered rule precedence then affects how conflicts involving that rule
7114 are resolved (@pxref{Precedence, ,Operator Precedence}).
7115
7116 Here is how @code{%prec} solves the problem of unary minus. First, declare
7117 a precedence for a fictitious terminal symbol named @code{UMINUS}. There
7118 are no tokens of this type, but the symbol serves to stand for its
7119 precedence:
7120
7121 @example
7122 @dots{}
7123 %left '+' '-'
7124 %left '*'
7125 %left UMINUS
7126 @end example
7127
7128 Now the precedence of @code{UMINUS} can be used in specific rules:
7129
7130 @example
7131 @group
7132 exp: @dots{}
7133 | exp '-' exp
7134 @dots{}
7135 | '-' exp %prec UMINUS
7136 @end group
7137 @end example
7138
7139 @ifset defaultprec
7140 If you forget to append @code{%prec UMINUS} to the rule for unary
7141 minus, Bison silently assumes that minus has its usual precedence.
7142 This kind of problem can be tricky to debug, since one typically
7143 discovers the mistake only by testing the code.
7144
7145 The @code{%no-default-prec;} declaration makes it easier to discover
7146 this kind of problem systematically. It causes rules that lack a
7147 @code{%prec} modifier to have no precedence, even if the last terminal
7148 symbol mentioned in their components has a declared precedence.
7149
7150 If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
7151 for all rules that participate in precedence conflict resolution.
7152 Then you will see any shift/reduce conflict until you tell Bison how
7153 to resolve it, either by changing your grammar or by adding an
7154 explicit precedence. This will probably add declarations to the
7155 grammar, but it helps to protect against incorrect rule precedences.
7156
7157 The effect of @code{%no-default-prec;} can be reversed by giving
7158 @code{%default-prec;}, which is the default.
7159 @end ifset
7160
7161 @node Parser States
7162 @section Parser States
7163 @cindex finite-state machine
7164 @cindex parser state
7165 @cindex state (of parser)
7166
7167 The function @code{yyparse} is implemented using a finite-state machine.
7168 The values pushed on the parser stack are not simply token type codes; they
7169 represent the entire sequence of terminal and nonterminal symbols at or
7170 near the top of the stack. The current state collects all the information
7171 about previous input which is relevant to deciding what to do next.
7172
7173 Each time a lookahead token is read, the current parser state together
7174 with the type of lookahead token are looked up in a table. This table
7175 entry can say, ``Shift the lookahead token.'' In this case, it also
7176 specifies the new parser state, which is pushed onto the top of the
7177 parser stack. Or it can say, ``Reduce using rule number @var{n}.''
7178 This means that a certain number of tokens or groupings are taken off
7179 the top of the stack, and replaced by one grouping. In other words,
7180 that number of states are popped from the stack, and one new state is
7181 pushed.
7182
7183 There is one other alternative: the table can say that the lookahead token
7184 is erroneous in the current state. This causes error processing to begin
7185 (@pxref{Error Recovery}).
7186
7187 @node Reduce/Reduce
7188 @section Reduce/Reduce Conflicts
7189 @cindex reduce/reduce conflict
7190 @cindex conflicts, reduce/reduce
7191
7192 A reduce/reduce conflict occurs if there are two or more rules that apply
7193 to the same sequence of input. This usually indicates a serious error
7194 in the grammar.
7195
7196 For example, here is an erroneous attempt to define a sequence
7197 of zero or more @code{word} groupings.
7198
7199 @example
7200 sequence: /* empty */
7201 @{ printf ("empty sequence\n"); @}
7202 | maybeword
7203 | sequence word
7204 @{ printf ("added word %s\n", $2); @}
7205 ;
7206
7207 maybeword: /* empty */
7208 @{ printf ("empty maybeword\n"); @}
7209 | word
7210 @{ printf ("single word %s\n", $1); @}
7211 ;
7212 @end example
7213
7214 @noindent
7215 The error is an ambiguity: there is more than one way to parse a single
7216 @code{word} into a @code{sequence}. It could be reduced to a
7217 @code{maybeword} and then into a @code{sequence} via the second rule.
7218 Alternatively, nothing-at-all could be reduced into a @code{sequence}
7219 via the first rule, and this could be combined with the @code{word}
7220 using the third rule for @code{sequence}.
7221
7222 There is also more than one way to reduce nothing-at-all into a
7223 @code{sequence}. This can be done directly via the first rule,
7224 or indirectly via @code{maybeword} and then the second rule.
7225
7226 You might think that this is a distinction without a difference, because it
7227 does not change whether any particular input is valid or not. But it does
7228 affect which actions are run. One parsing order runs the second rule's
7229 action; the other runs the first rule's action and the third rule's action.
7230 In this example, the output of the program changes.
7231
7232 Bison resolves a reduce/reduce conflict by choosing to use the rule that
7233 appears first in the grammar, but it is very risky to rely on this. Every
7234 reduce/reduce conflict must be studied and usually eliminated. Here is the
7235 proper way to define @code{sequence}:
7236
7237 @example
7238 sequence: /* empty */
7239 @{ printf ("empty sequence\n"); @}
7240 | sequence word
7241 @{ printf ("added word %s\n", $2); @}
7242 ;
7243 @end example
7244
7245 Here is another common error that yields a reduce/reduce conflict:
7246
7247 @example
7248 sequence: /* empty */
7249 | sequence words
7250 | sequence redirects
7251 ;
7252
7253 words: /* empty */
7254 | words word
7255 ;
7256
7257 redirects:/* empty */
7258 | redirects redirect
7259 ;
7260 @end example
7261
7262 @noindent
7263 The intention here is to define a sequence which can contain either
7264 @code{word} or @code{redirect} groupings. The individual definitions of
7265 @code{sequence}, @code{words} and @code{redirects} are error-free, but the
7266 three together make a subtle ambiguity: even an empty input can be parsed
7267 in infinitely many ways!
7268
7269 Consider: nothing-at-all could be a @code{words}. Or it could be two
7270 @code{words} in a row, or three, or any number. It could equally well be a
7271 @code{redirects}, or two, or any number. Or it could be a @code{words}
7272 followed by three @code{redirects} and another @code{words}. And so on.
7273
7274 Here are two ways to correct these rules. First, to make it a single level
7275 of sequence:
7276
7277 @example
7278 sequence: /* empty */
7279 | sequence word
7280 | sequence redirect
7281 ;
7282 @end example
7283
7284 Second, to prevent either a @code{words} or a @code{redirects}
7285 from being empty:
7286
7287 @example
7288 sequence: /* empty */
7289 | sequence words
7290 | sequence redirects
7291 ;
7292
7293 words: word
7294 | words word
7295 ;
7296
7297 redirects:redirect
7298 | redirects redirect
7299 ;
7300 @end example
7301
7302 @node Mystery Conflicts
7303 @section Mysterious Reduce/Reduce Conflicts
7304
7305 Sometimes reduce/reduce conflicts can occur that don't look warranted.
7306 Here is an example:
7307
7308 @example
7309 @group
7310 %token ID
7311
7312 %%
7313 def: param_spec return_spec ','
7314 ;
7315 param_spec:
7316 type
7317 | name_list ':' type
7318 ;
7319 @end group
7320 @group
7321 return_spec:
7322 type
7323 | name ':' type
7324 ;
7325 @end group
7326 @group
7327 type: ID
7328 ;
7329 @end group
7330 @group
7331 name: ID
7332 ;
7333 name_list:
7334 name
7335 | name ',' name_list
7336 ;
7337 @end group
7338 @end example
7339
7340 It would seem that this grammar can be parsed with only a single token
7341 of lookahead: when a @code{param_spec} is being read, an @code{ID} is
7342 a @code{name} if a comma or colon follows, or a @code{type} if another
7343 @code{ID} follows. In other words, this grammar is LR(1).
7344
7345 @cindex LR(1)
7346 @cindex LALR(1)
7347 However, for historical reasons, Bison cannot by default handle all
7348 LR(1) grammars.
7349 In this grammar, two contexts, that after an @code{ID} at the beginning
7350 of a @code{param_spec} and likewise at the beginning of a
7351 @code{return_spec}, are similar enough that Bison assumes they are the
7352 same.
7353 They appear similar because the same set of rules would be
7354 active---the rule for reducing to a @code{name} and that for reducing to
7355 a @code{type}. Bison is unable to determine at that stage of processing
7356 that the rules would require different lookahead tokens in the two
7357 contexts, so it makes a single parser state for them both. Combining
7358 the two contexts causes a conflict later. In parser terminology, this
7359 occurrence means that the grammar is not LALR(1).
7360
7361 For many practical grammars (specifically those that fall into the
7362 non-LR(1) class), the limitations of LALR(1) result in difficulties
7363 beyond just mysterious reduce/reduce conflicts. The best way to fix
7364 all these problems is to select a different parser table generation
7365 algorithm. Either IELR(1) or canonical LR(1) would suffice, but the
7366 former is more efficient and easier to debug during development.
7367 @xref{%define Summary,,lr.type}, for details. (Bison's IELR(1) and
7368 canonical LR(1) implementations are experimental. More user feedback
7369 will help to stabilize them.)
7370
7371 If you instead wish to work around LALR(1)'s limitations, you
7372 can often fix a mysterious conflict by identifying the two parser states
7373 that are being confused, and adding something to make them look
7374 distinct. In the above example, adding one rule to
7375 @code{return_spec} as follows makes the problem go away:
7376
7377 @example
7378 @group
7379 %token BOGUS
7380 @dots{}
7381 %%
7382 @dots{}
7383 return_spec:
7384 type
7385 | name ':' type
7386 /* This rule is never used. */
7387 | ID BOGUS
7388 ;
7389 @end group
7390 @end example
7391
7392 This corrects the problem because it introduces the possibility of an
7393 additional active rule in the context after the @code{ID} at the beginning of
7394 @code{return_spec}. This rule is not active in the corresponding context
7395 in a @code{param_spec}, so the two contexts receive distinct parser states.
7396 As long as the token @code{BOGUS} is never generated by @code{yylex},
7397 the added rule cannot alter the way actual input is parsed.
7398
7399 In this particular example, there is another way to solve the problem:
7400 rewrite the rule for @code{return_spec} to use @code{ID} directly
7401 instead of via @code{name}. This also causes the two confusing
7402 contexts to have different sets of active rules, because the one for
7403 @code{return_spec} activates the altered rule for @code{return_spec}
7404 rather than the one for @code{name}.
7405
7406 @example
7407 param_spec:
7408 type
7409 | name_list ':' type
7410 ;
7411 return_spec:
7412 type
7413 | ID ':' type
7414 ;
7415 @end example
7416
7417 For a more detailed exposition of LALR(1) parsers and parser
7418 generators, @pxref{Bibliography,,DeRemer 1982}.
7419
7420 @node Generalized LR Parsing
7421 @section Generalized LR (GLR) Parsing
7422 @cindex GLR parsing
7423 @cindex generalized LR (GLR) parsing
7424 @cindex ambiguous grammars
7425 @cindex nondeterministic parsing
7426
7427 Bison produces @emph{deterministic} parsers that choose uniquely
7428 when to reduce and which reduction to apply
7429 based on a summary of the preceding input and on one extra token of lookahead.
7430 As a result, normal Bison handles a proper subset of the family of
7431 context-free languages.
7432 Ambiguous grammars, since they have strings with more than one possible
7433 sequence of reductions cannot have deterministic parsers in this sense.
7434 The same is true of languages that require more than one symbol of
7435 lookahead, since the parser lacks the information necessary to make a
7436 decision at the point it must be made in a shift-reduce parser.
7437 Finally, as previously mentioned (@pxref{Mystery Conflicts}),
7438 there are languages where Bison's default choice of how to
7439 summarize the input seen so far loses necessary information.
7440
7441 When you use the @samp{%glr-parser} declaration in your grammar file,
7442 Bison generates a parser that uses a different algorithm, called
7443 Generalized LR (or GLR). A Bison GLR
7444 parser uses the same basic
7445 algorithm for parsing as an ordinary Bison parser, but behaves
7446 differently in cases where there is a shift-reduce conflict that has not
7447 been resolved by precedence rules (@pxref{Precedence}) or a
7448 reduce-reduce conflict. When a GLR parser encounters such a
7449 situation, it
7450 effectively @emph{splits} into a several parsers, one for each possible
7451 shift or reduction. These parsers then proceed as usual, consuming
7452 tokens in lock-step. Some of the stacks may encounter other conflicts
7453 and split further, with the result that instead of a sequence of states,
7454 a Bison GLR parsing stack is what is in effect a tree of states.
7455
7456 In effect, each stack represents a guess as to what the proper parse
7457 is. Additional input may indicate that a guess was wrong, in which case
7458 the appropriate stack silently disappears. Otherwise, the semantics
7459 actions generated in each stack are saved, rather than being executed
7460 immediately. When a stack disappears, its saved semantic actions never
7461 get executed. When a reduction causes two stacks to become equivalent,
7462 their sets of semantic actions are both saved with the state that
7463 results from the reduction. We say that two stacks are equivalent
7464 when they both represent the same sequence of states,
7465 and each pair of corresponding states represents a
7466 grammar symbol that produces the same segment of the input token
7467 stream.
7468
7469 Whenever the parser makes a transition from having multiple
7470 states to having one, it reverts to the normal deterministic parsing
7471 algorithm, after resolving and executing the saved-up actions.
7472 At this transition, some of the states on the stack will have semantic
7473 values that are sets (actually multisets) of possible actions. The
7474 parser tries to pick one of the actions by first finding one whose rule
7475 has the highest dynamic precedence, as set by the @samp{%dprec}
7476 declaration. Otherwise, if the alternative actions are not ordered by
7477 precedence, but there the same merging function is declared for both
7478 rules by the @samp{%merge} declaration,
7479 Bison resolves and evaluates both and then calls the merge function on
7480 the result. Otherwise, it reports an ambiguity.
7481
7482 It is possible to use a data structure for the GLR parsing tree that
7483 permits the processing of any LR(1) grammar in linear time (in the
7484 size of the input), any unambiguous (not necessarily
7485 LR(1)) grammar in
7486 quadratic worst-case time, and any general (possibly ambiguous)
7487 context-free grammar in cubic worst-case time. However, Bison currently
7488 uses a simpler data structure that requires time proportional to the
7489 length of the input times the maximum number of stacks required for any
7490 prefix of the input. Thus, really ambiguous or nondeterministic
7491 grammars can require exponential time and space to process. Such badly
7492 behaving examples, however, are not generally of practical interest.
7493 Usually, nondeterminism in a grammar is local---the parser is ``in
7494 doubt'' only for a few tokens at a time. Therefore, the current data
7495 structure should generally be adequate. On LR(1) portions of a
7496 grammar, in particular, it is only slightly slower than with the
7497 deterministic LR(1) Bison parser.
7498
7499 For a more detailed exposition of GLR parsers, @pxref{Bibliography,,Scott
7500 2000}.
7501
7502 @node Memory Management
7503 @section Memory Management, and How to Avoid Memory Exhaustion
7504 @cindex memory exhaustion
7505 @cindex memory management
7506 @cindex stack overflow
7507 @cindex parser stack overflow
7508 @cindex overflow of parser stack
7509
7510 The Bison parser stack can run out of memory if too many tokens are shifted and
7511 not reduced. When this happens, the parser function @code{yyparse}
7512 calls @code{yyerror} and then returns 2.
7513
7514 Because Bison parsers have growing stacks, hitting the upper limit
7515 usually results from using a right recursion instead of a left
7516 recursion, @xref{Recursion, ,Recursive Rules}.
7517
7518 @vindex YYMAXDEPTH
7519 By defining the macro @code{YYMAXDEPTH}, you can control how deep the
7520 parser stack can become before memory is exhausted. Define the
7521 macro with a value that is an integer. This value is the maximum number
7522 of tokens that can be shifted (and not reduced) before overflow.
7523
7524 The stack space allowed is not necessarily allocated. If you specify a
7525 large value for @code{YYMAXDEPTH}, the parser normally allocates a small
7526 stack at first, and then makes it bigger by stages as needed. This
7527 increasing allocation happens automatically and silently. Therefore,
7528 you do not need to make @code{YYMAXDEPTH} painfully small merely to save
7529 space for ordinary inputs that do not need much stack.
7530
7531 However, do not allow @code{YYMAXDEPTH} to be a value so large that
7532 arithmetic overflow could occur when calculating the size of the stack
7533 space. Also, do not allow @code{YYMAXDEPTH} to be less than
7534 @code{YYINITDEPTH}.
7535
7536 @cindex default stack limit
7537 The default value of @code{YYMAXDEPTH}, if you do not define it, is
7538 10000.
7539
7540 @vindex YYINITDEPTH
7541 You can control how much stack is allocated initially by defining the
7542 macro @code{YYINITDEPTH} to a positive integer. For the deterministic
7543 parser in C, this value must be a compile-time constant
7544 unless you are assuming C99 or some other target language or compiler
7545 that allows variable-length arrays. The default is 200.
7546
7547 Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
7548
7549 You can generate a deterministic parser containing C++ user code from
7550 the default (C) skeleton, as well as from the C++ skeleton
7551 (@pxref{C++ Parsers}). However, if you do use the default skeleton
7552 and want to allow the parsing stack to grow,
7553 be careful not to use semantic types or location types that require
7554 non-trivial copy constructors.
7555 The C skeleton bypasses these constructors when copying data to
7556 new, larger stacks.
7557
7558 @node Error Recovery
7559 @chapter Error Recovery
7560 @cindex error recovery
7561 @cindex recovery from errors
7562
7563 It is not usually acceptable to have a program terminate on a syntax
7564 error. For example, a compiler should recover sufficiently to parse the
7565 rest of the input file and check it for errors; a calculator should accept
7566 another expression.
7567
7568 In a simple interactive command parser where each input is one line, it may
7569 be sufficient to allow @code{yyparse} to return 1 on error and have the
7570 caller ignore the rest of the input line when that happens (and then call
7571 @code{yyparse} again). But this is inadequate for a compiler, because it
7572 forgets all the syntactic context leading up to the error. A syntax error
7573 deep within a function in the compiler input should not cause the compiler
7574 to treat the following line like the beginning of a source file.
7575
7576 @findex error
7577 You can define how to recover from a syntax error by writing rules to
7578 recognize the special token @code{error}. This is a terminal symbol that
7579 is always defined (you need not declare it) and reserved for error
7580 handling. The Bison parser generates an @code{error} token whenever a
7581 syntax error happens; if you have provided a rule to recognize this token
7582 in the current context, the parse can continue.
7583
7584 For example:
7585
7586 @example
7587 stmnts: /* empty string */
7588 | stmnts '\n'
7589 | stmnts exp '\n'
7590 | stmnts error '\n'
7591 @end example
7592
7593 The fourth rule in this example says that an error followed by a newline
7594 makes a valid addition to any @code{stmnts}.
7595
7596 What happens if a syntax error occurs in the middle of an @code{exp}? The
7597 error recovery rule, interpreted strictly, applies to the precise sequence
7598 of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
7599 the middle of an @code{exp}, there will probably be some additional tokens
7600 and subexpressions on the stack after the last @code{stmnts}, and there
7601 will be tokens to read before the next newline. So the rule is not
7602 applicable in the ordinary way.
7603
7604 But Bison can force the situation to fit the rule, by discarding part of
7605 the semantic context and part of the input. First it discards states
7606 and objects from the stack until it gets back to a state in which the
7607 @code{error} token is acceptable. (This means that the subexpressions
7608 already parsed are discarded, back to the last complete @code{stmnts}.)
7609 At this point the @code{error} token can be shifted. Then, if the old
7610 lookahead token is not acceptable to be shifted next, the parser reads
7611 tokens and discards them until it finds a token which is acceptable. In
7612 this example, Bison reads and discards input until the next newline so
7613 that the fourth rule can apply. Note that discarded symbols are
7614 possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
7615 Discarded Symbols}, for a means to reclaim this memory.
7616
7617 The choice of error rules in the grammar is a choice of strategies for
7618 error recovery. A simple and useful strategy is simply to skip the rest of
7619 the current input line or current statement if an error is detected:
7620
7621 @example
7622 stmnt: error ';' /* On error, skip until ';' is read. */
7623 @end example
7624
7625 It is also useful to recover to the matching close-delimiter of an
7626 opening-delimiter that has already been parsed. Otherwise the
7627 close-delimiter will probably appear to be unmatched, and generate another,
7628 spurious error message:
7629
7630 @example
7631 primary: '(' expr ')'
7632 | '(' error ')'
7633 @dots{}
7634 ;
7635 @end example
7636
7637 Error recovery strategies are necessarily guesses. When they guess wrong,
7638 one syntax error often leads to another. In the above example, the error
7639 recovery rule guesses that an error is due to bad input within one
7640 @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
7641 middle of a valid @code{stmnt}. After the error recovery rule recovers
7642 from the first error, another syntax error will be found straightaway,
7643 since the text following the spurious semicolon is also an invalid
7644 @code{stmnt}.
7645
7646 To prevent an outpouring of error messages, the parser will output no error
7647 message for another syntax error that happens shortly after the first; only
7648 after three consecutive input tokens have been successfully shifted will
7649 error messages resume.
7650
7651 Note that rules which accept the @code{error} token may have actions, just
7652 as any other rules can.
7653
7654 @findex yyerrok
7655 You can make error messages resume immediately by using the macro
7656 @code{yyerrok} in an action. If you do this in the error rule's action, no
7657 error messages will be suppressed. This macro requires no arguments;
7658 @samp{yyerrok;} is a valid C statement.
7659
7660 @findex yyclearin
7661 The previous lookahead token is reanalyzed immediately after an error. If
7662 this is unacceptable, then the macro @code{yyclearin} may be used to clear
7663 this token. Write the statement @samp{yyclearin;} in the error rule's
7664 action.
7665 @xref{Action Features, ,Special Features for Use in Actions}.
7666
7667 For example, suppose that on a syntax error, an error handling routine is
7668 called that advances the input stream to some point where parsing should
7669 once again commence. The next symbol returned by the lexical scanner is
7670 probably correct. The previous lookahead token ought to be discarded
7671 with @samp{yyclearin;}.
7672
7673 @vindex YYRECOVERING
7674 The expression @code{YYRECOVERING ()} yields 1 when the parser
7675 is recovering from a syntax error, and 0 otherwise.
7676 Syntax error diagnostics are suppressed while recovering from a syntax
7677 error.
7678
7679 @node Context Dependency
7680 @chapter Handling Context Dependencies
7681
7682 The Bison paradigm is to parse tokens first, then group them into larger
7683 syntactic units. In many languages, the meaning of a token is affected by
7684 its context. Although this violates the Bison paradigm, certain techniques
7685 (known as @dfn{kludges}) may enable you to write Bison parsers for such
7686 languages.
7687
7688 @menu
7689 * Semantic Tokens:: Token parsing can depend on the semantic context.
7690 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
7691 * Tie-in Recovery:: Lexical tie-ins have implications for how
7692 error recovery rules must be written.
7693 @end menu
7694
7695 (Actually, ``kludge'' means any technique that gets its job done but is
7696 neither clean nor robust.)
7697
7698 @node Semantic Tokens
7699 @section Semantic Info in Token Types
7700
7701 The C language has a context dependency: the way an identifier is used
7702 depends on what its current meaning is. For example, consider this:
7703
7704 @example
7705 foo (x);
7706 @end example
7707
7708 This looks like a function call statement, but if @code{foo} is a typedef
7709 name, then this is actually a declaration of @code{x}. How can a Bison
7710 parser for C decide how to parse this input?
7711
7712 The method used in GNU C is to have two different token types,
7713 @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
7714 identifier, it looks up the current declaration of the identifier in order
7715 to decide which token type to return: @code{TYPENAME} if the identifier is
7716 declared as a typedef, @code{IDENTIFIER} otherwise.
7717
7718 The grammar rules can then express the context dependency by the choice of
7719 token type to recognize. @code{IDENTIFIER} is accepted as an expression,
7720 but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
7721 @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
7722 is @emph{not} significant, such as in declarations that can shadow a
7723 typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
7724 accepted---there is one rule for each of the two token types.
7725
7726 This technique is simple to use if the decision of which kinds of
7727 identifiers to allow is made at a place close to where the identifier is
7728 parsed. But in C this is not always so: C allows a declaration to
7729 redeclare a typedef name provided an explicit type has been specified
7730 earlier:
7731
7732 @example
7733 typedef int foo, bar;
7734 int baz (void)
7735 @{
7736 static bar (bar); /* @r{redeclare @code{bar} as static variable} */
7737 extern foo foo (foo); /* @r{redeclare @code{foo} as function} */
7738 return foo (bar);
7739 @}
7740 @end example
7741
7742 Unfortunately, the name being declared is separated from the declaration
7743 construct itself by a complicated syntactic structure---the ``declarator''.
7744
7745 As a result, part of the Bison parser for C needs to be duplicated, with
7746 all the nonterminal names changed: once for parsing a declaration in
7747 which a typedef name can be redefined, and once for parsing a
7748 declaration in which that can't be done. Here is a part of the
7749 duplication, with actions omitted for brevity:
7750
7751 @example
7752 initdcl:
7753 declarator maybeasm '='
7754 init
7755 | declarator maybeasm
7756 ;
7757
7758 notype_initdcl:
7759 notype_declarator maybeasm '='
7760 init
7761 | notype_declarator maybeasm
7762 ;
7763 @end example
7764
7765 @noindent
7766 Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
7767 cannot. The distinction between @code{declarator} and
7768 @code{notype_declarator} is the same sort of thing.
7769
7770 There is some similarity between this technique and a lexical tie-in
7771 (described next), in that information which alters the lexical analysis is
7772 changed during parsing by other parts of the program. The difference is
7773 here the information is global, and is used for other purposes in the
7774 program. A true lexical tie-in has a special-purpose flag controlled by
7775 the syntactic context.
7776
7777 @node Lexical Tie-ins
7778 @section Lexical Tie-ins
7779 @cindex lexical tie-in
7780
7781 One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
7782 which is set by Bison actions, whose purpose is to alter the way tokens are
7783 parsed.
7784
7785 For example, suppose we have a language vaguely like C, but with a special
7786 construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
7787 an expression in parentheses in which all integers are hexadecimal. In
7788 particular, the token @samp{a1b} must be treated as an integer rather than
7789 as an identifier if it appears in that context. Here is how you can do it:
7790
7791 @example
7792 @group
7793 %@{
7794 int hexflag;
7795 int yylex (void);
7796 void yyerror (char const *);
7797 %@}
7798 %%
7799 @dots{}
7800 @end group
7801 @group
7802 expr: IDENTIFIER
7803 | constant
7804 | HEX '('
7805 @{ hexflag = 1; @}
7806 expr ')'
7807 @{ hexflag = 0;
7808 $$ = $4; @}
7809 | expr '+' expr
7810 @{ $$ = make_sum ($1, $3); @}
7811 @dots{}
7812 ;
7813 @end group
7814
7815 @group
7816 constant:
7817 INTEGER
7818 | STRING
7819 ;
7820 @end group
7821 @end example
7822
7823 @noindent
7824 Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
7825 it is nonzero, all integers are parsed in hexadecimal, and tokens starting
7826 with letters are parsed as integers if possible.
7827
7828 The declaration of @code{hexflag} shown in the prologue of the grammar
7829 file is needed to make it accessible to the actions (@pxref{Prologue,
7830 ,The Prologue}). You must also write the code in @code{yylex} to obey
7831 the flag.
7832
7833 @node Tie-in Recovery
7834 @section Lexical Tie-ins and Error Recovery
7835
7836 Lexical tie-ins make strict demands on any error recovery rules you have.
7837 @xref{Error Recovery}.
7838
7839 The reason for this is that the purpose of an error recovery rule is to
7840 abort the parsing of one construct and resume in some larger construct.
7841 For example, in C-like languages, a typical error recovery rule is to skip
7842 tokens until the next semicolon, and then start a new statement, like this:
7843
7844 @example
7845 stmt: expr ';'
7846 | IF '(' expr ')' stmt @{ @dots{} @}
7847 @dots{}
7848 error ';'
7849 @{ hexflag = 0; @}
7850 ;
7851 @end example
7852
7853 If there is a syntax error in the middle of a @samp{hex (@var{expr})}
7854 construct, this error rule will apply, and then the action for the
7855 completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
7856 remain set for the entire rest of the input, or until the next @code{hex}
7857 keyword, causing identifiers to be misinterpreted as integers.
7858
7859 To avoid this problem the error recovery rule itself clears @code{hexflag}.
7860
7861 There may also be an error recovery rule that works within expressions.
7862 For example, there could be a rule which applies within parentheses
7863 and skips to the close-parenthesis:
7864
7865 @example
7866 @group
7867 expr: @dots{}
7868 | '(' expr ')'
7869 @{ $$ = $2; @}
7870 | '(' error ')'
7871 @dots{}
7872 @end group
7873 @end example
7874
7875 If this rule acts within the @code{hex} construct, it is not going to abort
7876 that construct (since it applies to an inner level of parentheses within
7877 the construct). Therefore, it should not clear the flag: the rest of
7878 the @code{hex} construct should be parsed with the flag still in effect.
7879
7880 What if there is an error recovery rule which might abort out of the
7881 @code{hex} construct or might not, depending on circumstances? There is no
7882 way you can write the action to determine whether a @code{hex} construct is
7883 being aborted or not. So if you are using a lexical tie-in, you had better
7884 make sure your error recovery rules are not of this kind. Each rule must
7885 be such that you can be sure that it always will, or always won't, have to
7886 clear the flag.
7887
7888 @c ================================================== Debugging Your Parser
7889
7890 @node Debugging
7891 @chapter Debugging Your Parser
7892
7893 Developing a parser can be a challenge, especially if you don't
7894 understand the algorithm (@pxref{Algorithm, ,The Bison Parser
7895 Algorithm}). Even so, sometimes a detailed description of the automaton
7896 can help (@pxref{Understanding, , Understanding Your Parser}), or
7897 tracing the execution of the parser can give some insight on why it
7898 behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
7899
7900 @menu
7901 * Understanding:: Understanding the structure of your parser.
7902 * Tracing:: Tracing the execution of your parser.
7903 @end menu
7904
7905 @node Understanding
7906 @section Understanding Your Parser
7907
7908 As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
7909 Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
7910 frequent than one would hope), looking at this automaton is required to
7911 tune or simply fix a parser. Bison provides two different
7912 representation of it, either textually or graphically (as a DOT file).
7913
7914 The textual file is generated when the options @option{--report} or
7915 @option{--verbose} are specified, see @xref{Invocation, , Invoking
7916 Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
7917 the parser implementation file name, and adding @samp{.output}
7918 instead. Therefore, if the grammar file is @file{foo.y}, then the
7919 parser implementation file is called @file{foo.tab.c} by default. As
7920 a consequence, the verbose output file is called @file{foo.output}.
7921
7922 The following grammar file, @file{calc.y}, will be used in the sequel:
7923
7924 @example
7925 %token NUM STR
7926 %left '+' '-'
7927 %left '*'
7928 %%
7929 exp: exp '+' exp
7930 | exp '-' exp
7931 | exp '*' exp
7932 | exp '/' exp
7933 | NUM
7934 ;
7935 useless: STR;
7936 %%
7937 @end example
7938
7939 @command{bison} reports:
7940
7941 @example
7942 calc.y: warning: 1 nonterminal useless in grammar
7943 calc.y: warning: 1 rule useless in grammar
7944 calc.y:11.1-7: warning: nonterminal useless in grammar: useless
7945 calc.y:11.10-12: warning: rule useless in grammar: useless: STR
7946 calc.y: conflicts: 7 shift/reduce
7947 @end example
7948
7949 When given @option{--report=state}, in addition to @file{calc.tab.c}, it
7950 creates a file @file{calc.output} with contents detailed below. The
7951 order of the output and the exact presentation might vary, but the
7952 interpretation is the same.
7953
7954 The first section includes details on conflicts that were solved thanks
7955 to precedence and/or associativity:
7956
7957 @example
7958 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
7959 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
7960 Conflict in state 8 between rule 2 and token '*' resolved as shift.
7961 @exdent @dots{}
7962 @end example
7963
7964 @noindent
7965 The next section lists states that still have conflicts.
7966
7967 @example
7968 State 8 conflicts: 1 shift/reduce
7969 State 9 conflicts: 1 shift/reduce
7970 State 10 conflicts: 1 shift/reduce
7971 State 11 conflicts: 4 shift/reduce
7972 @end example
7973
7974 @noindent
7975 @cindex token, useless
7976 @cindex useless token
7977 @cindex nonterminal, useless
7978 @cindex useless nonterminal
7979 @cindex rule, useless
7980 @cindex useless rule
7981 The next section reports useless tokens, nonterminal and rules. Useless
7982 nonterminals and rules are removed in order to produce a smaller parser,
7983 but useless tokens are preserved, since they might be used by the
7984 scanner (note the difference between ``useless'' and ``unused''
7985 below):
7986
7987 @example
7988 Nonterminals useless in grammar:
7989 useless
7990
7991 Terminals unused in grammar:
7992 STR
7993
7994 Rules useless in grammar:
7995 #6 useless: STR;
7996 @end example
7997
7998 @noindent
7999 The next section reproduces the exact grammar that Bison used:
8000
8001 @example
8002 Grammar
8003
8004 Number, Line, Rule
8005 0 5 $accept -> exp $end
8006 1 5 exp -> exp '+' exp
8007 2 6 exp -> exp '-' exp
8008 3 7 exp -> exp '*' exp
8009 4 8 exp -> exp '/' exp
8010 5 9 exp -> NUM
8011 @end example
8012
8013 @noindent
8014 and reports the uses of the symbols:
8015
8016 @example
8017 Terminals, with rules where they appear
8018
8019 $end (0) 0
8020 '*' (42) 3
8021 '+' (43) 1
8022 '-' (45) 2
8023 '/' (47) 4
8024 error (256)
8025 NUM (258) 5
8026
8027 Nonterminals, with rules where they appear
8028
8029 $accept (8)
8030 on left: 0
8031 exp (9)
8032 on left: 1 2 3 4 5, on right: 0 1 2 3 4
8033 @end example
8034
8035 @noindent
8036 @cindex item
8037 @cindex pointed rule
8038 @cindex rule, pointed
8039 Bison then proceeds onto the automaton itself, describing each state
8040 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
8041 item is a production rule together with a point (marked by @samp{.})
8042 that the input cursor.
8043
8044 @example
8045 state 0
8046
8047 $accept -> . exp $ (rule 0)
8048
8049 NUM shift, and go to state 1
8050
8051 exp go to state 2
8052 @end example
8053
8054 This reads as follows: ``state 0 corresponds to being at the very
8055 beginning of the parsing, in the initial rule, right before the start
8056 symbol (here, @code{exp}). When the parser returns to this state right
8057 after having reduced a rule that produced an @code{exp}, the control
8058 flow jumps to state 2. If there is no such transition on a nonterminal
8059 symbol, and the lookahead is a @code{NUM}, then this token is shifted on
8060 the parse stack, and the control flow jumps to state 1. Any other
8061 lookahead triggers a syntax error.''
8062
8063 @cindex core, item set
8064 @cindex item set core
8065 @cindex kernel, item set
8066 @cindex item set core
8067 Even though the only active rule in state 0 seems to be rule 0, the
8068 report lists @code{NUM} as a lookahead token because @code{NUM} can be
8069 at the beginning of any rule deriving an @code{exp}. By default Bison
8070 reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
8071 you want to see more detail you can invoke @command{bison} with
8072 @option{--report=itemset} to list all the items, include those that can
8073 be derived:
8074
8075 @example
8076 state 0
8077
8078 $accept -> . exp $ (rule 0)
8079 exp -> . exp '+' exp (rule 1)
8080 exp -> . exp '-' exp (rule 2)
8081 exp -> . exp '*' exp (rule 3)
8082 exp -> . exp '/' exp (rule 4)
8083 exp -> . NUM (rule 5)
8084
8085 NUM shift, and go to state 1
8086
8087 exp go to state 2
8088 @end example
8089
8090 @noindent
8091 In the state 1...
8092
8093 @example
8094 state 1
8095
8096 exp -> NUM . (rule 5)
8097
8098 $default reduce using rule 5 (exp)
8099 @end example
8100
8101 @noindent
8102 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead token
8103 (@samp{$default}), the parser will reduce it. If it was coming from
8104 state 0, then, after this reduction it will return to state 0, and will
8105 jump to state 2 (@samp{exp: go to state 2}).
8106
8107 @example
8108 state 2
8109
8110 $accept -> exp . $ (rule 0)
8111 exp -> exp . '+' exp (rule 1)
8112 exp -> exp . '-' exp (rule 2)
8113 exp -> exp . '*' exp (rule 3)
8114 exp -> exp . '/' exp (rule 4)
8115
8116 $ shift, and go to state 3
8117 '+' shift, and go to state 4
8118 '-' shift, and go to state 5
8119 '*' shift, and go to state 6
8120 '/' shift, and go to state 7
8121 @end example
8122
8123 @noindent
8124 In state 2, the automaton can only shift a symbol. For instance,
8125 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
8126 @samp{+}, it will be shifted on the parse stack, and the automaton
8127 control will jump to state 4, corresponding to the item @samp{exp -> exp
8128 '+' . exp}. Since there is no default action, any other token than
8129 those listed above will trigger a syntax error.
8130
8131 @cindex accepting state
8132 The state 3 is named the @dfn{final state}, or the @dfn{accepting
8133 state}:
8134
8135 @example
8136 state 3
8137
8138 $accept -> exp $ . (rule 0)
8139
8140 $default accept
8141 @end example
8142
8143 @noindent
8144 the initial rule is completed (the start symbol and the end
8145 of input were read), the parsing exits successfully.
8146
8147 The interpretation of states 4 to 7 is straightforward, and is left to
8148 the reader.
8149
8150 @example
8151 state 4
8152
8153 exp -> exp '+' . exp (rule 1)
8154
8155 NUM shift, and go to state 1
8156
8157 exp go to state 8
8158
8159 state 5
8160
8161 exp -> exp '-' . exp (rule 2)
8162
8163 NUM shift, and go to state 1
8164
8165 exp go to state 9
8166
8167 state 6
8168
8169 exp -> exp '*' . exp (rule 3)
8170
8171 NUM shift, and go to state 1
8172
8173 exp go to state 10
8174
8175 state 7
8176
8177 exp -> exp '/' . exp (rule 4)
8178
8179 NUM shift, and go to state 1
8180
8181 exp go to state 11
8182 @end example
8183
8184 As was announced in beginning of the report, @samp{State 8 conflicts:
8185 1 shift/reduce}:
8186
8187 @example
8188 state 8
8189
8190 exp -> exp . '+' exp (rule 1)
8191 exp -> exp '+' exp . (rule 1)
8192 exp -> exp . '-' exp (rule 2)
8193 exp -> exp . '*' exp (rule 3)
8194 exp -> exp . '/' exp (rule 4)
8195
8196 '*' shift, and go to state 6
8197 '/' shift, and go to state 7
8198
8199 '/' [reduce using rule 1 (exp)]
8200 $default reduce using rule 1 (exp)
8201 @end example
8202
8203 Indeed, there are two actions associated to the lookahead @samp{/}:
8204 either shifting (and going to state 7), or reducing rule 1. The
8205 conflict means that either the grammar is ambiguous, or the parser lacks
8206 information to make the right decision. Indeed the grammar is
8207 ambiguous, as, since we did not specify the precedence of @samp{/}, the
8208 sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
8209 NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
8210 NUM}, which corresponds to reducing rule 1.
8211
8212 Because in deterministic parsing a single decision can be made, Bison
8213 arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
8214 Shift/Reduce Conflicts}. Discarded actions are reported in between
8215 square brackets.
8216
8217 Note that all the previous states had a single possible action: either
8218 shifting the next token and going to the corresponding state, or
8219 reducing a single rule. In the other cases, i.e., when shifting
8220 @emph{and} reducing is possible or when @emph{several} reductions are
8221 possible, the lookahead is required to select the action. State 8 is
8222 one such state: if the lookahead is @samp{*} or @samp{/} then the action
8223 is shifting, otherwise the action is reducing rule 1. In other words,
8224 the first two items, corresponding to rule 1, are not eligible when the
8225 lookahead token is @samp{*}, since we specified that @samp{*} has higher
8226 precedence than @samp{+}. More generally, some items are eligible only
8227 with some set of possible lookahead tokens. When run with
8228 @option{--report=lookahead}, Bison specifies these lookahead tokens:
8229
8230 @example
8231 state 8
8232
8233 exp -> exp . '+' exp (rule 1)
8234 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
8235 exp -> exp . '-' exp (rule 2)
8236 exp -> exp . '*' exp (rule 3)
8237 exp -> exp . '/' exp (rule 4)
8238
8239 '*' shift, and go to state 6
8240 '/' shift, and go to state 7
8241
8242 '/' [reduce using rule 1 (exp)]
8243 $default reduce using rule 1 (exp)
8244 @end example
8245
8246 The remaining states are similar:
8247
8248 @example
8249 state 9
8250
8251 exp -> exp . '+' exp (rule 1)
8252 exp -> exp . '-' exp (rule 2)
8253 exp -> exp '-' exp . (rule 2)
8254 exp -> exp . '*' exp (rule 3)
8255 exp -> exp . '/' exp (rule 4)
8256
8257 '*' shift, and go to state 6
8258 '/' shift, and go to state 7
8259
8260 '/' [reduce using rule 2 (exp)]
8261 $default reduce using rule 2 (exp)
8262
8263 state 10
8264
8265 exp -> exp . '+' exp (rule 1)
8266 exp -> exp . '-' exp (rule 2)
8267 exp -> exp . '*' exp (rule 3)
8268 exp -> exp '*' exp . (rule 3)
8269 exp -> exp . '/' exp (rule 4)
8270
8271 '/' shift, and go to state 7
8272
8273 '/' [reduce using rule 3 (exp)]
8274 $default reduce using rule 3 (exp)
8275
8276 state 11
8277
8278 exp -> exp . '+' exp (rule 1)
8279 exp -> exp . '-' exp (rule 2)
8280 exp -> exp . '*' exp (rule 3)
8281 exp -> exp . '/' exp (rule 4)
8282 exp -> exp '/' exp . (rule 4)
8283
8284 '+' shift, and go to state 4
8285 '-' shift, and go to state 5
8286 '*' shift, and go to state 6
8287 '/' shift, and go to state 7
8288
8289 '+' [reduce using rule 4 (exp)]
8290 '-' [reduce using rule 4 (exp)]
8291 '*' [reduce using rule 4 (exp)]
8292 '/' [reduce using rule 4 (exp)]
8293 $default reduce using rule 4 (exp)
8294 @end example
8295
8296 @noindent
8297 Observe that state 11 contains conflicts not only due to the lack of
8298 precedence of @samp{/} with respect to @samp{+}, @samp{-}, and
8299 @samp{*}, but also because the
8300 associativity of @samp{/} is not specified.
8301
8302
8303 @node Tracing
8304 @section Tracing Your Parser
8305 @findex yydebug
8306 @cindex debugging
8307 @cindex tracing the parser
8308
8309 If a Bison grammar compiles properly but doesn't do what you want when it
8310 runs, the @code{yydebug} parser-trace feature can help you figure out why.
8311
8312 There are several means to enable compilation of trace facilities:
8313
8314 @table @asis
8315 @item the macro @code{YYDEBUG}
8316 @findex YYDEBUG
8317 Define the macro @code{YYDEBUG} to a nonzero value when you compile the
8318 parser. This is compliant with POSIX Yacc. You could use
8319 @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
8320 YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
8321 Prologue}).
8322
8323 @item the option @option{-t}, @option{--debug}
8324 Use the @samp{-t} option when you run Bison (@pxref{Invocation,
8325 ,Invoking Bison}). This is POSIX compliant too.
8326
8327 @item the directive @samp{%debug}
8328 @findex %debug
8329 Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison Declaration
8330 Summary}). This Bison extension is maintained for backward
8331 compatibility with previous versions of Bison.
8332
8333 @item the variable @samp{parse.trace}
8334 @findex %define parse.trace
8335 Add the @samp{%define parse.trace} directive (@pxref{%define
8336 Summary,,parse.trace}), or pass the @option{-Dparse.trace} option
8337 (@pxref{Bison Options}). This is a Bison extension, which is especially
8338 useful for languages that don't use a preprocessor. Unless POSIX and Yacc
8339 portability matter to you, this is the preferred solution.
8340 @end table
8341
8342 We suggest that you always enable the trace option so that debugging is
8343 always possible.
8344
8345 The trace facility outputs messages with macro calls of the form
8346 @code{YYFPRINTF (stderr, @var{format}, @var{args})} where
8347 @var{format} and @var{args} are the usual @code{printf} format and variadic
8348 arguments. If you define @code{YYDEBUG} to a nonzero value but do not
8349 define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
8350 and @code{YYFPRINTF} is defined to @code{fprintf}.
8351
8352 Once you have compiled the program with trace facilities, the way to
8353 request a trace is to store a nonzero value in the variable @code{yydebug}.
8354 You can do this by making the C code do it (in @code{main}, perhaps), or
8355 you can alter the value with a C debugger.
8356
8357 Each step taken by the parser when @code{yydebug} is nonzero produces a
8358 line or two of trace information, written on @code{stderr}. The trace
8359 messages tell you these things:
8360
8361 @itemize @bullet
8362 @item
8363 Each time the parser calls @code{yylex}, what kind of token was read.
8364
8365 @item
8366 Each time a token is shifted, the depth and complete contents of the
8367 state stack (@pxref{Parser States}).
8368
8369 @item
8370 Each time a rule is reduced, which rule it is, and the complete contents
8371 of the state stack afterward.
8372 @end itemize
8373
8374 To make sense of this information, it helps to refer to the listing file
8375 produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
8376 Bison}). This file shows the meaning of each state in terms of
8377 positions in various rules, and also what each state will do with each
8378 possible input token. As you read the successive trace messages, you
8379 can see that the parser is functioning according to its specification in
8380 the listing file. Eventually you will arrive at the place where
8381 something undesirable happens, and you will see which parts of the
8382 grammar are to blame.
8383
8384 The parser implementation file is a C program and you can use C
8385 debuggers on it, but it's not easy to interpret what it is doing. The
8386 parser function is a finite-state machine interpreter, and aside from
8387 the actions it executes the same code over and over. Only the values
8388 of variables show where in the grammar it is working.
8389
8390 @findex YYPRINT
8391 The debugging information normally gives the token type of each token
8392 read, but not its semantic value. You can optionally define a macro
8393 named @code{YYPRINT} to provide a way to print the value. If you define
8394 @code{YYPRINT}, it should take three arguments. The parser will pass a
8395 standard I/O stream, the numeric code for the token type, and the token
8396 value (from @code{yylval}).
8397
8398 Here is an example of @code{YYPRINT} suitable for the multi-function
8399 calculator (@pxref{Mfcalc Declarations, ,Declarations for @code{mfcalc}}):
8400
8401 @smallexample
8402 %@{
8403 static void print_token_value (FILE *, int, YYSTYPE);
8404 #define YYPRINT(file, type, value) print_token_value (file, type, value)
8405 %@}
8406
8407 @dots{} %% @dots{} %% @dots{}
8408
8409 static void
8410 print_token_value (FILE *file, int type, YYSTYPE value)
8411 @{
8412 if (type == VAR)
8413 fprintf (file, "%s", value.tptr->name);
8414 else if (type == NUM)
8415 fprintf (file, "%d", value.val);
8416 @}
8417 @end smallexample
8418
8419 @c ================================================= Invoking Bison
8420
8421 @node Invocation
8422 @chapter Invoking Bison
8423 @cindex invoking Bison
8424 @cindex Bison invocation
8425 @cindex options for invoking Bison
8426
8427 The usual way to invoke Bison is as follows:
8428
8429 @example
8430 bison @var{infile}
8431 @end example
8432
8433 Here @var{infile} is the grammar file name, which usually ends in
8434 @samp{.y}. The parser implementation file's name is made by replacing
8435 the @samp{.y} with @samp{.tab.c} and removing any leading directory.
8436 Thus, the @samp{bison foo.y} file name yields @file{foo.tab.c}, and
8437 the @samp{bison hack/foo.y} file name yields @file{foo.tab.c}. It's
8438 also possible, in case you are writing C++ code instead of C in your
8439 grammar file, to name it @file{foo.ypp} or @file{foo.y++}. Then, the
8440 output files will take an extension like the given one as input
8441 (respectively @file{foo.tab.cpp} and @file{foo.tab.c++}). This
8442 feature takes effect with all options that manipulate file names like
8443 @samp{-o} or @samp{-d}.
8444
8445 For example :
8446
8447 @example
8448 bison -d @var{infile.yxx}
8449 @end example
8450 @noindent
8451 will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
8452
8453 @example
8454 bison -d -o @var{output.c++} @var{infile.y}
8455 @end example
8456 @noindent
8457 will produce @file{output.c++} and @file{outfile.h++}.
8458
8459 For compatibility with POSIX, the standard Bison
8460 distribution also contains a shell script called @command{yacc} that
8461 invokes Bison with the @option{-y} option.
8462
8463 @menu
8464 * Bison Options:: All the options described in detail,
8465 in alphabetical order by short options.
8466 * Option Cross Key:: Alphabetical list of long options.
8467 * Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
8468 @end menu
8469
8470 @node Bison Options
8471 @section Bison Options
8472
8473 Bison supports both traditional single-letter options and mnemonic long
8474 option names. Long option names are indicated with @samp{--} instead of
8475 @samp{-}. Abbreviations for option names are allowed as long as they
8476 are unique. When a long option takes an argument, like
8477 @samp{--file-prefix}, connect the option name and the argument with
8478 @samp{=}.
8479
8480 Here is a list of options that can be used with Bison, alphabetized by
8481 short option. It is followed by a cross key alphabetized by long
8482 option.
8483
8484 @c Please, keep this ordered as in `bison --help'.
8485 @noindent
8486 Operations modes:
8487 @table @option
8488 @item -h
8489 @itemx --help
8490 Print a summary of the command-line options to Bison and exit.
8491
8492 @item -V
8493 @itemx --version
8494 Print the version number of Bison and exit.
8495
8496 @item --print-localedir
8497 Print the name of the directory containing locale-dependent data.
8498
8499 @item --print-datadir
8500 Print the name of the directory containing skeletons and XSLT.
8501
8502 @item -y
8503 @itemx --yacc
8504 Act more like the traditional Yacc command. This can cause different
8505 diagnostics to be generated, and may change behavior in other minor
8506 ways. Most importantly, imitate Yacc's output file name conventions,
8507 so that the parser implementation file is called @file{y.tab.c}, and
8508 the other outputs are called @file{y.output} and @file{y.tab.h}.
8509 Also, if generating a deterministic parser in C, generate
8510 @code{#define} statements in addition to an @code{enum} to associate
8511 token numbers with token names. Thus, the following shell script can
8512 substitute for Yacc, and the Bison distribution contains such a script
8513 for compatibility with POSIX:
8514
8515 @example
8516 #! /bin/sh
8517 bison -y "$@@"
8518 @end example
8519
8520 The @option{-y}/@option{--yacc} option is intended for use with
8521 traditional Yacc grammars. If your grammar uses a Bison extension
8522 like @samp{%glr-parser}, Bison might not be Yacc-compatible even if
8523 this option is specified.
8524
8525 @item -W [@var{category}]
8526 @itemx --warnings[=@var{category}]
8527 Output warnings falling in @var{category}. @var{category} can be one
8528 of:
8529 @table @code
8530 @item midrule-values
8531 Warn about mid-rule values that are set but not used within any of the actions
8532 of the parent rule.
8533 For example, warn about unused @code{$2} in:
8534
8535 @example
8536 exp: '1' @{ $$ = 1; @} '+' exp @{ $$ = $1 + $4; @};
8537 @end example
8538
8539 Also warn about mid-rule values that are used but not set.
8540 For example, warn about unset @code{$$} in the mid-rule action in:
8541
8542 @example
8543 exp: '1' @{ $1 = 1; @} '+' exp @{ $$ = $2 + $4; @};
8544 @end example
8545
8546 These warnings are not enabled by default since they sometimes prove to
8547 be false alarms in existing grammars employing the Yacc constructs
8548 @code{$0} or @code{$-@var{n}} (where @var{n} is some positive integer).
8549
8550
8551 @item yacc
8552 Incompatibilities with POSIX Yacc.
8553
8554 @item all
8555 All the warnings.
8556 @item none
8557 Turn off all the warnings.
8558 @item error
8559 Treat warnings as errors.
8560 @end table
8561
8562 A category can be turned off by prefixing its name with @samp{no-}. For
8563 instance, @option{-Wno-yacc} will hide the warnings about
8564 POSIX Yacc incompatibilities.
8565 @end table
8566
8567 @noindent
8568 Tuning the parser:
8569
8570 @table @option
8571 @item -t
8572 @itemx --debug
8573 In the parser implementation file, define the macro @code{YYDEBUG} to
8574 1 if it is not already defined, so that the debugging facilities are
8575 compiled. @xref{Tracing, ,Tracing Your Parser}.
8576
8577 @item -D @var{name}[=@var{value}]
8578 @itemx --define=@var{name}[=@var{value}]
8579 @itemx -F @var{name}[=@var{value}]
8580 @itemx --force-define=@var{name}[=@var{value}]
8581 Each of these is equivalent to @samp{%define @var{name} "@var{value}"}
8582 (@pxref{%define Summary}) except that Bison processes multiple
8583 definitions for the same @var{name} as follows:
8584
8585 @itemize
8586 @item
8587 Bison quietly ignores all command-line definitions for @var{name} except
8588 the last.
8589 @item
8590 If that command-line definition is specified by a @code{-D} or
8591 @code{--define}, Bison reports an error for any @code{%define}
8592 definition for @var{name}.
8593 @item
8594 If that command-line definition is specified by a @code{-F} or
8595 @code{--force-define} instead, Bison quietly ignores all @code{%define}
8596 definitions for @var{name}.
8597 @item
8598 Otherwise, Bison reports an error if there are multiple @code{%define}
8599 definitions for @var{name}.
8600 @end itemize
8601
8602 You should avoid using @code{-F} and @code{--force-define} in your
8603 make files unless you are confident that it is safe to quietly ignore
8604 any conflicting @code{%define} that may be added to the grammar file.
8605
8606 @item -L @var{language}
8607 @itemx --language=@var{language}
8608 Specify the programming language for the generated parser, as if
8609 @code{%language} was specified (@pxref{Decl Summary, , Bison Declaration
8610 Summary}). Currently supported languages include C, C++, and Java.
8611 @var{language} is case-insensitive.
8612
8613 This option is experimental and its effect may be modified in future
8614 releases.
8615
8616 @item --locations
8617 Pretend that @code{%locations} was specified. @xref{Decl Summary}.
8618
8619 @item -p @var{prefix}
8620 @itemx --name-prefix=@var{prefix}
8621 Pretend that @code{%name-prefix "@var{prefix}"} was specified.
8622 @xref{Decl Summary}.
8623
8624 @item -l
8625 @itemx --no-lines
8626 Don't put any @code{#line} preprocessor commands in the parser
8627 implementation file. Ordinarily Bison puts them in the parser
8628 implementation file so that the C compiler and debuggers will
8629 associate errors with your source file, the grammar file. This option
8630 causes them to associate errors with the parser implementation file,
8631 treating it as an independent source file in its own right.
8632
8633 @item -S @var{file}
8634 @itemx --skeleton=@var{file}
8635 Specify the skeleton to use, similar to @code{%skeleton}
8636 (@pxref{Decl Summary, , Bison Declaration Summary}).
8637
8638 @c You probably don't need this option unless you are developing Bison.
8639 @c You should use @option{--language} if you want to specify the skeleton for a
8640 @c different language, because it is clearer and because it will always
8641 @c choose the correct skeleton for non-deterministic or push parsers.
8642
8643 If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
8644 file in the Bison installation directory.
8645 If it does, @var{file} is an absolute file name or a file name relative to the
8646 current working directory.
8647 This is similar to how most shells resolve commands.
8648
8649 @item -k
8650 @itemx --token-table
8651 Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
8652 @end table
8653
8654 @noindent
8655 Adjust the output:
8656
8657 @table @option
8658 @item --defines[=@var{file}]
8659 Pretend that @code{%defines} was specified, i.e., write an extra output
8660 file containing macro definitions for the token type names defined in
8661 the grammar, as well as a few other declarations. @xref{Decl Summary}.
8662
8663 @item -d
8664 This is the same as @code{--defines} except @code{-d} does not accept a
8665 @var{file} argument since POSIX Yacc requires that @code{-d} can be bundled
8666 with other short options.
8667
8668 @item -b @var{file-prefix}
8669 @itemx --file-prefix=@var{prefix}
8670 Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
8671 for all Bison output file names. @xref{Decl Summary}.
8672
8673 @item -r @var{things}
8674 @itemx --report=@var{things}
8675 Write an extra output file containing verbose description of the comma
8676 separated list of @var{things} among:
8677
8678 @table @code
8679 @item state
8680 Description of the grammar, conflicts (resolved and unresolved), and
8681 parser's automaton.
8682
8683 @item lookahead
8684 Implies @code{state} and augments the description of the automaton with
8685 each rule's lookahead set.
8686
8687 @item itemset
8688 Implies @code{state} and augments the description of the automaton with
8689 the full set of items for each state, instead of its core only.
8690 @end table
8691
8692 @item --report-file=@var{file}
8693 Specify the @var{file} for the verbose description.
8694
8695 @item -v
8696 @itemx --verbose
8697 Pretend that @code{%verbose} was specified, i.e., write an extra output
8698 file containing verbose descriptions of the grammar and
8699 parser. @xref{Decl Summary}.
8700
8701 @item -o @var{file}
8702 @itemx --output=@var{file}
8703 Specify the @var{file} for the parser implementation file.
8704
8705 The other output files' names are constructed from @var{file} as
8706 described under the @samp{-v} and @samp{-d} options.
8707
8708 @item -g [@var{file}]
8709 @itemx --graph[=@var{file}]
8710 Output a graphical representation of the parser's
8711 automaton computed by Bison, in @uref{http://www.graphviz.org/, Graphviz}
8712 @uref{http://www.graphviz.org/doc/info/lang.html, DOT} format.
8713 @code{@var{file}} is optional.
8714 If omitted and the grammar file is @file{foo.y}, the output file will be
8715 @file{foo.dot}.
8716
8717 @item -x [@var{file}]
8718 @itemx --xml[=@var{file}]
8719 Output an XML report of the parser's automaton computed by Bison.
8720 @code{@var{file}} is optional.
8721 If omitted and the grammar file is @file{foo.y}, the output file will be
8722 @file{foo.xml}.
8723 (The current XML schema is experimental and may evolve.
8724 More user feedback will help to stabilize it.)
8725 @end table
8726
8727 @node Option Cross Key
8728 @section Option Cross Key
8729
8730 Here is a list of options, alphabetized by long option, to help you find
8731 the corresponding short option and directive.
8732
8733 @multitable {@option{--force-define=@var{name}[=@var{value}]}} {@option{-F @var{name}[=@var{value}]}} {@code{%nondeterministic-parser}}
8734 @headitem Long Option @tab Short Option @tab Bison Directive
8735 @include cross-options.texi
8736 @end multitable
8737
8738 @node Yacc Library
8739 @section Yacc Library
8740
8741 The Yacc library contains default implementations of the
8742 @code{yyerror} and @code{main} functions. These default
8743 implementations are normally not useful, but POSIX requires
8744 them. To use the Yacc library, link your program with the
8745 @option{-ly} option. Note that Bison's implementation of the Yacc
8746 library is distributed under the terms of the GNU General
8747 Public License (@pxref{Copying}).
8748
8749 If you use the Yacc library's @code{yyerror} function, you should
8750 declare @code{yyerror} as follows:
8751
8752 @example
8753 int yyerror (char const *);
8754 @end example
8755
8756 Bison ignores the @code{int} value returned by this @code{yyerror}.
8757 If you use the Yacc library's @code{main} function, your
8758 @code{yyparse} function should have the following type signature:
8759
8760 @example
8761 int yyparse (void);
8762 @end example
8763
8764 @c ================================================= C++ Bison
8765
8766 @node Other Languages
8767 @chapter Parsers Written In Other Languages
8768
8769 @menu
8770 * C++ Parsers:: The interface to generate C++ parser classes
8771 * Java Parsers:: The interface to generate Java parser classes
8772 @end menu
8773
8774 @node C++ Parsers
8775 @section C++ Parsers
8776
8777 @menu
8778 * C++ Bison Interface:: Asking for C++ parser generation
8779 * C++ Semantic Values:: %union vs. C++
8780 * C++ Location Values:: The position and location classes
8781 * C++ Parser Interface:: Instantiating and running the parser
8782 * C++ Scanner Interface:: Exchanges between yylex and parse
8783 * A Complete C++ Example:: Demonstrating their use
8784 @end menu
8785
8786 @node C++ Bison Interface
8787 @subsection C++ Bison Interface
8788 @c - %skeleton "lalr1.cc"
8789 @c - Always pure
8790 @c - initial action
8791
8792 The C++ deterministic parser is selected using the skeleton directive,
8793 @samp{%skeleton "lalr1.cc"}, or the synonymous command-line option
8794 @option{--skeleton=lalr1.cc}.
8795 @xref{Decl Summary}.
8796
8797 When run, @command{bison} will create several entities in the @samp{yy}
8798 namespace.
8799 @findex %define api.namespace
8800 Use the @samp{%define api.namespace} directive to change the namespace name,
8801 see @ref{%define Summary,,api.namespace}. The various classes are generated
8802 in the following files:
8803
8804 @table @file
8805 @item position.hh
8806 @itemx location.hh
8807 The definition of the classes @code{position} and @code{location},
8808 used for location tracking when enabled. @xref{C++ Location Values}.
8809
8810 @item stack.hh
8811 An auxiliary class @code{stack} used by the parser.
8812
8813 @item @var{file}.hh
8814 @itemx @var{file}.cc
8815 (Assuming the extension of the grammar file was @samp{.yy}.) The
8816 declaration and implementation of the C++ parser class. The basename
8817 and extension of these two files follow the same rules as with regular C
8818 parsers (@pxref{Invocation}).
8819
8820 The header is @emph{mandatory}; you must either pass
8821 @option{-d}/@option{--defines} to @command{bison}, or use the
8822 @samp{%defines} directive.
8823 @end table
8824
8825 All these files are documented using Doxygen; run @command{doxygen}
8826 for a complete and accurate documentation.
8827
8828 @node C++ Semantic Values
8829 @subsection C++ Semantic Values
8830 @c - No objects in unions
8831 @c - YYSTYPE
8832 @c - Printer and destructor
8833
8834 Bison supports two different means to handle semantic values in C++. One is
8835 alike the C interface, and relies on unions (@pxref{C++ Unions}). As C++
8836 practitioners know, unions are inconvenient in C++, therefore another
8837 approach is provided, based on variants (@pxref{C++ Variants}).
8838
8839 @menu
8840 * C++ Unions:: Semantic values cannot be objects
8841 * C++ Variants:: Using objects as semantic values
8842 @end menu
8843
8844 @node C++ Unions
8845 @subsubsection C++ Unions
8846
8847 The @code{%union} directive works as for C, see @ref{Union Decl, ,The
8848 Collection of Value Types}. In particular it produces a genuine
8849 @code{union}, which have a few specific features in C++.
8850 @itemize @minus
8851 @item
8852 The type @code{YYSTYPE} is defined but its use is discouraged: rather
8853 you should refer to the parser's encapsulated type
8854 @code{yy::parser::semantic_type}.
8855 @item
8856 Non POD (Plain Old Data) types cannot be used. C++ forbids any
8857 instance of classes with constructors in unions: only @emph{pointers}
8858 to such objects are allowed.
8859 @end itemize
8860
8861 Because objects have to be stored via pointers, memory is not
8862 reclaimed automatically: using the @code{%destructor} directive is the
8863 only means to avoid leaks. @xref{Destructor Decl, , Freeing Discarded
8864 Symbols}.
8865
8866 @node C++ Variants
8867 @subsubsection C++ Variants
8868
8869 Starting with version 2.6, Bison provides a @emph{variant} based
8870 implementation of semantic values for C++. This alleviates all the
8871 limitations reported in the previous section, and in particular, object
8872 types can be used without pointers.
8873
8874 To enable variant-based semantic values, set @code{%define} variable
8875 @code{variant} (@pxref{%define Summary,, variant}). Once this defined,
8876 @code{%union} is ignored, and instead of using the name of the fields of the
8877 @code{%union} to ``type'' the symbols, use genuine types.
8878
8879 For instance, instead of
8880
8881 @example
8882 %union
8883 @{
8884 int ival;
8885 std::string* sval;
8886 @}
8887 %token <ival> NUMBER;
8888 %token <sval> STRING;
8889 @end example
8890
8891 @noindent
8892 write
8893
8894 @example
8895 %token <int> NUMBER;
8896 %token <std::string> STRING;
8897 @end example
8898
8899 @code{STRING} is no longer a pointer, which should fairly simplify the user
8900 actions in the grammar and in the scanner (in particular the memory
8901 management).
8902
8903 Since C++ features destructors, and since it is customary to specialize
8904 @code{operator<<} to support uniform printing of values, variants also
8905 typically simplify Bison printers and destructors.
8906
8907 Variants are stricter than unions. When based on unions, you may play any
8908 dirty game with @code{yylval}, say storing an @code{int}, reading a
8909 @code{char*}, and then storing a @code{double} in it. This is no longer
8910 possible with variants: they must be initialized, then assigned to, and
8911 eventually, destroyed.
8912
8913 @deftypemethod {semantic_type} {T&} build<T> ()
8914 Initialize, but leave empty. Returns the address where the actual value may
8915 be stored. Requires that the variant was not initialized yet.
8916 @end deftypemethod
8917
8918 @deftypemethod {semantic_type} {T&} build<T> (const T& @var{t})
8919 Initialize, and copy-construct from @var{t}.
8920 @end deftypemethod
8921
8922
8923 @strong{Warning}: We do not use Boost.Variant, for two reasons. First, it
8924 appeared unacceptable to require Boost on the user's machine (i.e., the
8925 machine on which the generated parser will be compiled, not the machine on
8926 which @command{bison} was run). Second, for each possible semantic value,
8927 Boost.Variant not only stores the value, but also a tag specifying its
8928 type. But the parser already ``knows'' the type of the semantic value, so
8929 that would be duplicating the information.
8930
8931 Therefore we developed light-weight variants whose type tag is external (so
8932 they are really like @code{unions} for C++ actually). But our code is much
8933 less mature that Boost.Variant. So there is a number of limitations in
8934 (the current implementation of) variants:
8935 @itemize
8936 @item
8937 Alignment must be enforced: values should be aligned in memory according to
8938 the most demanding type. Computing the smallest alignment possible requires
8939 meta-programming techniques that are not currently implemented in Bison, and
8940 therefore, since, as far as we know, @code{double} is the most demanding
8941 type on all platforms, alignments are enforced for @code{double} whatever
8942 types are actually used. This may waste space in some cases.
8943
8944 @item
8945 Our implementation is not conforming with strict aliasing rules. Alias
8946 analysis is a technique used in optimizing compilers to detect when two
8947 pointers are disjoint (they cannot ``meet''). Our implementation breaks
8948 some of the rules that G++ 4.4 uses in its alias analysis, so @emph{strict
8949 alias analysis must be disabled}. Use the option
8950 @option{-fno-strict-aliasing} to compile the generated parser.
8951
8952 @item
8953 There might be portability issues we are not aware of.
8954 @end itemize
8955
8956 As far as we know, these limitations @emph{can} be alleviated. All it takes
8957 is some time and/or some talented C++ hacker willing to contribute to Bison.
8958
8959 @node C++ Location Values
8960 @subsection C++ Location Values
8961 @c - %locations
8962 @c - class Position
8963 @c - class Location
8964 @c - %define filename_type "const symbol::Symbol"
8965
8966 When the directive @code{%locations} is used, the C++ parser supports
8967 location tracking, see @ref{Locations, , Locations Overview}. Two
8968 auxiliary classes define a @code{position}, a single point in a file,
8969 and a @code{location}, a range composed of a pair of
8970 @code{position}s (possibly spanning several files).
8971
8972 @deftypemethod {position} {std::string*} file
8973 The name of the file. It will always be handled as a pointer, the
8974 parser will never duplicate nor deallocate it. As an experimental
8975 feature you may change it to @samp{@var{type}*} using @samp{%define
8976 filename_type "@var{type}"}.
8977 @end deftypemethod
8978
8979 @deftypemethod {position} {unsigned int} line
8980 The line, starting at 1.
8981 @end deftypemethod
8982
8983 @deftypemethod {position} {unsigned int} lines (int @var{height} = 1)
8984 Advance by @var{height} lines, resetting the column number.
8985 @end deftypemethod
8986
8987 @deftypemethod {position} {unsigned int} column
8988 The column, starting at 0.
8989 @end deftypemethod
8990
8991 @deftypemethod {position} {unsigned int} columns (int @var{width} = 1)
8992 Advance by @var{width} columns, without changing the line number.
8993 @end deftypemethod
8994
8995 @deftypemethod {position} {position&} operator+= (position& @var{pos}, int @var{width})
8996 @deftypemethodx {position} {position} operator+ (const position& @var{pos}, int @var{width})
8997 @deftypemethodx {position} {position&} operator-= (const position& @var{pos}, int @var{width})
8998 @deftypemethodx {position} {position} operator- (position& @var{pos}, int @var{width})
8999 Various forms of syntactic sugar for @code{columns}.
9000 @end deftypemethod
9001
9002 @deftypemethod {position} {position} operator<< (std::ostream @var{o}, const position& @var{p})
9003 Report @var{p} on @var{o} like this:
9004 @samp{@var{file}:@var{line}.@var{column}}, or
9005 @samp{@var{line}.@var{column}} if @var{file} is null.
9006 @end deftypemethod
9007
9008 @deftypemethod {location} {position} begin
9009 @deftypemethodx {location} {position} end
9010 The first, inclusive, position of the range, and the first beyond.
9011 @end deftypemethod
9012
9013 @deftypemethod {location} {unsigned int} columns (int @var{width} = 1)
9014 @deftypemethodx {location} {unsigned int} lines (int @var{height} = 1)
9015 Advance the @code{end} position.
9016 @end deftypemethod
9017
9018 @deftypemethod {location} {location} operator+ (const location& @var{begin}, const location& @var{end})
9019 @deftypemethodx {location} {location} operator+ (const location& @var{begin}, int @var{width})
9020 @deftypemethodx {location} {location} operator+= (const location& @var{loc}, int @var{width})
9021 Various forms of syntactic sugar.
9022 @end deftypemethod
9023
9024 @deftypemethod {location} {void} step ()
9025 Move @code{begin} onto @code{end}.
9026 @end deftypemethod
9027
9028
9029 @node C++ Parser Interface
9030 @subsection C++ Parser Interface
9031 @c - define parser_class_name
9032 @c - Ctor
9033 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
9034 @c debug_stream.
9035 @c - Reporting errors
9036
9037 The output files @file{@var{output}.hh} and @file{@var{output}.cc}
9038 declare and define the parser class in the namespace @code{yy}. The
9039 class name defaults to @code{parser}, but may be changed using
9040 @samp{%define parser_class_name "@var{name}"}. The interface of
9041 this class is detailed below. It can be extended using the
9042 @code{%parse-param} feature: its semantics is slightly changed since
9043 it describes an additional member of the parser class, and an
9044 additional argument for its constructor.
9045
9046 @defcv {Type} {parser} {semantic_type}
9047 @defcvx {Type} {parser} {location_type}
9048 The types for semantic values and locations (if enabled).
9049 @end defcv
9050
9051 @defcv {Type} {parser} {token}
9052 A structure that contains (only) the definition of the tokens as the
9053 @code{yytokentype} enumeration. To refer to the token @code{FOO}, the
9054 scanner should use @code{yy::parser::token::FOO}. The scanner can use
9055 @samp{typedef yy::parser::token token;} to ``import'' the token enumeration
9056 (@pxref{Calc++ Scanner}).
9057 @end defcv
9058
9059 @defcv {Type} {parser} {syntax_error}
9060 This class derives from @code{std::runtime_error}. Throw instances of it
9061 from user actions to raise parse errors. This is equivalent with first
9062 invoking @code{error} to report the location and message of the syntax
9063 error, and then to invoke @code{YYERROR} to enter the error-recovery mode.
9064 But contrary to @code{YYERROR} which can only be invoked from user actions
9065 (i.e., written in the action itself), the exception can be thrown from
9066 function invoked from the user action.
9067 @end defcv
9068
9069 @deftypemethod {parser} {} parser (@var{type1} @var{arg1}, ...)
9070 Build a new parser object. There are no arguments by default, unless
9071 @samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
9072 @end deftypemethod
9073
9074 @deftypemethod {syntax_error} {} syntax_error (const location_type& @var{l}, const std::string& @var{m})
9075 @deftypemethodx {syntax_error} {} syntax_error (const std::string& @var{m})
9076 Instantiate a syntax-error exception.
9077 @end deftypemethod
9078
9079 @deftypemethod {parser} {int} parse ()
9080 Run the syntactic analysis, and return 0 on success, 1 otherwise.
9081 @end deftypemethod
9082
9083 @deftypemethod {parser} {std::ostream&} debug_stream ()
9084 @deftypemethodx {parser} {void} set_debug_stream (std::ostream& @var{o})
9085 Get or set the stream used for tracing the parsing. It defaults to
9086 @code{std::cerr}.
9087 @end deftypemethod
9088
9089 @deftypemethod {parser} {debug_level_type} debug_level ()
9090 @deftypemethodx {parser} {void} set_debug_level (debug_level @var{l})
9091 Get or set the tracing level. Currently its value is either 0, no trace,
9092 or nonzero, full tracing.
9093 @end deftypemethod
9094
9095 @deftypemethod {parser} {void} error (const location_type& @var{l}, const std::string& @var{m})
9096 @deftypemethodx {parser} {void} error (const std::string& @var{m})
9097 The definition for this member function must be supplied by the user:
9098 the parser uses it to report a parser error occurring at @var{l},
9099 described by @var{m}. If location tracking is not enabled, the second
9100 signature is used.
9101 @end deftypemethod
9102
9103
9104 @node C++ Scanner Interface
9105 @subsection C++ Scanner Interface
9106 @c - prefix for yylex.
9107 @c - Pure interface to yylex
9108 @c - %lex-param
9109
9110 The parser invokes the scanner by calling @code{yylex}. Contrary to C
9111 parsers, C++ parsers are always pure: there is no point in using the
9112 @samp{%define api.pure} directive. The actual interface with @code{yylex}
9113 depends whether you use unions, or variants.
9114
9115 @menu
9116 * Split Symbols:: Passing symbols as two/three components
9117 * Complete Symbols:: Making symbols a whole
9118 @end menu
9119
9120 @node Split Symbols
9121 @subsubsection Split Symbols
9122
9123 Therefore the interface is as follows.
9124
9125 @deftypemethod {parser} {int} yylex (semantic_type* @var{yylval}, location_type* @var{yylloc}, @var{type1} @var{arg1}, ...)
9126 @deftypemethodx {parser} {int} yylex (semantic_type* @var{yylval}, @var{type1} @var{arg1}, ...)
9127 Return the next token. Its type is the return value, its semantic value and
9128 location (if enabled) being @var{yylval} and @var{yylloc}. Invocations of
9129 @samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
9130 @end deftypemethod
9131
9132 Note that when using variants, the interface for @code{yylex} is the same,
9133 but @code{yylval} is handled differently.
9134
9135 Regular union-based code in Lex scanner typically look like:
9136
9137 @example
9138 [0-9]+ @{
9139 yylval.ival = text_to_int (yytext);
9140 return yy::parser::INTEGER;
9141 @}
9142 [a-z]+ @{
9143 yylval.sval = new std::string (yytext);
9144 return yy::parser::IDENTIFIER;
9145 @}
9146 @end example
9147
9148 Using variants, @code{yylval} is already constructed, but it is not
9149 initialized. So the code would look like:
9150
9151 @example
9152 [0-9]+ @{
9153 yylval.build<int>() = text_to_int (yytext);
9154 return yy::parser::INTEGER;
9155 @}
9156 [a-z]+ @{
9157 yylval.build<std::string> = yytext;
9158 return yy::parser::IDENTIFIER;
9159 @}
9160 @end example
9161
9162 @noindent
9163 or
9164
9165 @example
9166 [0-9]+ @{
9167 yylval.build(text_to_int (yytext));
9168 return yy::parser::INTEGER;
9169 @}
9170 [a-z]+ @{
9171 yylval.build(yytext);
9172 return yy::parser::IDENTIFIER;
9173 @}
9174 @end example
9175
9176
9177 @node Complete Symbols
9178 @subsubsection Complete Symbols
9179
9180 If you specified both @code{%define variant} and @code{%define lex_symbol},
9181 the @code{parser} class also defines the class @code{parser::symbol_type}
9182 which defines a @emph{complete} symbol, aggregating its type (i.e., the
9183 traditional value returned by @code{yylex}), its semantic value (i.e., the
9184 value passed in @code{yylval}, and possibly its location (@code{yylloc}).
9185
9186 @deftypemethod {symbol_type} {} symbol_type (token_type @var{type}, const semantic_type& @var{value}, const location_type& @var{location})
9187 Build a complete terminal symbol which token type is @var{type}, and which
9188 semantic value is @var{value}. If location tracking is enabled, also pass
9189 the @var{location}.
9190 @end deftypemethod
9191
9192 This interface is low-level and should not be used for two reasons. First,
9193 it is inconvenient, as you still have to build the semantic value, which is
9194 a variant, and second, because consistency is not enforced: as with unions,
9195 it is still possible to give an integer as semantic value for a string.
9196
9197 So for each token type, Bison generates named constructors as follows.
9198
9199 @deftypemethod {symbol_type} {} make_@var{token} (const @var{value_type}& @var{value}, const location_type& @var{location})
9200 @deftypemethodx {symbol_type} {} make_@var{token} (const location_type& @var{location})
9201 Build a complete terminal symbol for the token type @var{token} (not
9202 including the @code{api.tokens.prefix}) whose possible semantic value is
9203 @var{value} of adequate @var{value_type}. If location tracking is enabled,
9204 also pass the @var{location}.
9205 @end deftypemethod
9206
9207 For instance, given the following declarations:
9208
9209 @example
9210 %define api.tokens.prefix "TOK_"
9211 %token <std::string> IDENTIFIER;
9212 %token <int> INTEGER;
9213 %token COLON;
9214 @end example
9215
9216 @noindent
9217 Bison generates the following functions:
9218
9219 @example
9220 symbol_type make_IDENTIFIER(const std::string& v,
9221 const location_type& l);
9222 symbol_type make_INTEGER(const int& v,
9223 const location_type& loc);
9224 symbol_type make_COLON(const location_type& loc);
9225 @end example
9226
9227 @noindent
9228 which should be used in a Lex-scanner as follows.
9229
9230 @example
9231 [0-9]+ return yy::parser::make_INTEGER(text_to_int (yytext), loc);
9232 [a-z]+ return yy::parser::make_IDENTIFIER(yytext, loc);
9233 ":" return yy::parser::make_COLON(loc);
9234 @end example
9235
9236 Tokens that do not have an identifier are not accessible: you cannot simply
9237 use characters such as @code{':'}, they must be declared with @code{%token}.
9238
9239 @node A Complete C++ Example
9240 @subsection A Complete C++ Example
9241
9242 This section demonstrates the use of a C++ parser with a simple but
9243 complete example. This example should be available on your system,
9244 ready to compile, in the directory @dfn{.../bison/examples/calc++}. It
9245 focuses on the use of Bison, therefore the design of the various C++
9246 classes is very naive: no accessors, no encapsulation of members etc.
9247 We will use a Lex scanner, and more precisely, a Flex scanner, to
9248 demonstrate the various interactions. A hand-written scanner is
9249 actually easier to interface with.
9250
9251 @menu
9252 * Calc++ --- C++ Calculator:: The specifications
9253 * Calc++ Parsing Driver:: An active parsing context
9254 * Calc++ Parser:: A parser class
9255 * Calc++ Scanner:: A pure C++ Flex scanner
9256 * Calc++ Top Level:: Conducting the band
9257 @end menu
9258
9259 @node Calc++ --- C++ Calculator
9260 @subsubsection Calc++ --- C++ Calculator
9261
9262 Of course the grammar is dedicated to arithmetics, a single
9263 expression, possibly preceded by variable assignments. An
9264 environment containing possibly predefined variables such as
9265 @code{one} and @code{two}, is exchanged with the parser. An example
9266 of valid input follows.
9267
9268 @example
9269 three := 3
9270 seven := one + two * three
9271 seven * seven
9272 @end example
9273
9274 @node Calc++ Parsing Driver
9275 @subsubsection Calc++ Parsing Driver
9276 @c - An env
9277 @c - A place to store error messages
9278 @c - A place for the result
9279
9280 To support a pure interface with the parser (and the scanner) the
9281 technique of the ``parsing context'' is convenient: a structure
9282 containing all the data to exchange. Since, in addition to simply
9283 launch the parsing, there are several auxiliary tasks to execute (open
9284 the file for parsing, instantiate the parser etc.), we recommend
9285 transforming the simple parsing context structure into a fully blown
9286 @dfn{parsing driver} class.
9287
9288 The declaration of this driver class, @file{calc++-driver.hh}, is as
9289 follows. The first part includes the CPP guard and imports the
9290 required standard library components, and the declaration of the parser
9291 class.
9292
9293 @comment file: calc++-driver.hh
9294 @example
9295 #ifndef CALCXX_DRIVER_HH
9296 # define CALCXX_DRIVER_HH
9297 # include <string>
9298 # include <map>
9299 # include "calc++-parser.hh"
9300 @end example
9301
9302
9303 @noindent
9304 Then comes the declaration of the scanning function. Flex expects
9305 the signature of @code{yylex} to be defined in the macro
9306 @code{YY_DECL}, and the C++ parser expects it to be declared. We can
9307 factor both as follows.
9308
9309 @comment file: calc++-driver.hh
9310 @example
9311 // Tell Flex the lexer's prototype ...
9312 # define YY_DECL \
9313 yy::calcxx_parser::symbol_type yylex (calcxx_driver& driver)
9314 // ... and declare it for the parser's sake.
9315 YY_DECL;
9316 @end example
9317
9318 @noindent
9319 The @code{calcxx_driver} class is then declared with its most obvious
9320 members.
9321
9322 @comment file: calc++-driver.hh
9323 @example
9324 // Conducting the whole scanning and parsing of Calc++.
9325 class calcxx_driver
9326 @{
9327 public:
9328 calcxx_driver ();
9329 virtual ~calcxx_driver ();
9330
9331 std::map<std::string, int> variables;
9332
9333 int result;
9334 @end example
9335
9336 @noindent
9337 To encapsulate the coordination with the Flex scanner, it is useful to have
9338 member functions to open and close the scanning phase.
9339
9340 @comment file: calc++-driver.hh
9341 @example
9342 // Handling the scanner.
9343 void scan_begin ();
9344 void scan_end ();
9345 bool trace_scanning;
9346 @end example
9347
9348 @noindent
9349 Similarly for the parser itself.
9350
9351 @comment file: calc++-driver.hh
9352 @example
9353 // Run the parser on file F.
9354 // Return 0 on success.
9355 int parse (const std::string& f);
9356 // The name of the file being parsed.
9357 // Used later to pass the file name to the location tracker.
9358 std::string file;
9359 // Whether parser traces should be generated.
9360 bool trace_parsing;
9361 @end example
9362
9363 @noindent
9364 To demonstrate pure handling of parse errors, instead of simply
9365 dumping them on the standard error output, we will pass them to the
9366 compiler driver using the following two member functions. Finally, we
9367 close the class declaration and CPP guard.
9368
9369 @comment file: calc++-driver.hh
9370 @example
9371 // Error handling.
9372 void error (const yy::location& l, const std::string& m);
9373 void error (const std::string& m);
9374 @};
9375 #endif // ! CALCXX_DRIVER_HH
9376 @end example
9377
9378 The implementation of the driver is straightforward. The @code{parse}
9379 member function deserves some attention. The @code{error} functions
9380 are simple stubs, they should actually register the located error
9381 messages and set error state.
9382
9383 @comment file: calc++-driver.cc
9384 @example
9385 #include "calc++-driver.hh"
9386 #include "calc++-parser.hh"
9387
9388 calcxx_driver::calcxx_driver ()
9389 : trace_scanning (false), trace_parsing (false)
9390 @{
9391 variables["one"] = 1;
9392 variables["two"] = 2;
9393 @}
9394
9395 calcxx_driver::~calcxx_driver ()
9396 @{
9397 @}
9398
9399 int
9400 calcxx_driver::parse (const std::string &f)
9401 @{
9402 file = f;
9403 scan_begin ();
9404 yy::calcxx_parser parser (*this);
9405 parser.set_debug_level (trace_parsing);
9406 int res = parser.parse ();
9407 scan_end ();
9408 return res;
9409 @}
9410
9411 void
9412 calcxx_driver::error (const yy::location& l, const std::string& m)
9413 @{
9414 std::cerr << l << ": " << m << std::endl;
9415 @}
9416
9417 void
9418 calcxx_driver::error (const std::string& m)
9419 @{
9420 std::cerr << m << std::endl;
9421 @}
9422 @end example
9423
9424 @node Calc++ Parser
9425 @subsubsection Calc++ Parser
9426
9427 The grammar file @file{calc++-parser.yy} starts by asking for the C++
9428 deterministic parser skeleton, the creation of the parser header file,
9429 and specifies the name of the parser class. Because the C++ skeleton
9430 changed several times, it is safer to require the version you designed
9431 the grammar for.
9432
9433 @comment file: calc++-parser.yy
9434 @example
9435 %skeleton "lalr1.cc" /* -*- C++ -*- */
9436 %require "@value{VERSION}"
9437 %defines
9438 %define parser_class_name "calcxx_parser"
9439 @end example
9440
9441 @noindent
9442 @findex %define variant
9443 @findex %define lex_symbol
9444 This example will use genuine C++ objects as semantic values, therefore, we
9445 require the variant-based interface. To make sure we properly use it, we
9446 enable assertions. To fully benefit from type-safety and more natural
9447 definition of ``symbol'', we enable @code{lex_symbol}.
9448
9449 @comment file: calc++-parser.yy
9450 @example
9451 %define variant
9452 %define parse.assert
9453 %define lex_symbol
9454 @end example
9455
9456 @noindent
9457 @findex %code requires
9458 Then come the declarations/inclusions needed by the semantic values.
9459 Because the parser uses the parsing driver and reciprocally, both would like
9460 to include the header of the other, which is, of course, insane. This
9461 mutual dependency will be broken using forward declarations. Because the
9462 driver's header needs detailed knowledge about the parser class (in
9463 particular its inner types), it is the parser's header which will use a
9464 forward declaration of the driver. @xref{%code Summary}.
9465
9466 @comment file: calc++-parser.yy
9467 @example
9468 %code requires
9469 @{
9470 # include <string>
9471 class calcxx_driver;
9472 @}
9473 @end example
9474
9475 @noindent
9476 The driver is passed by reference to the parser and to the scanner.
9477 This provides a simple but effective pure interface, not relying on
9478 global variables.
9479
9480 @comment file: calc++-parser.yy
9481 @example
9482 // The parsing context.
9483 %param @{ calcxx_driver& driver @}
9484 @end example
9485
9486 @noindent
9487 Then we request location tracking, and initialize the
9488 first location's file name. Afterward new locations are computed
9489 relatively to the previous locations: the file name will be
9490 propagated.
9491
9492 @comment file: calc++-parser.yy
9493 @example
9494 %locations
9495 %initial-action
9496 @{
9497 // Initialize the initial location.
9498 @@$.begin.filename = @@$.end.filename = &driver.file;
9499 @};
9500 @end example
9501
9502 @noindent
9503 Use the following two directives to enable parser tracing and verbose
9504 error messages.
9505
9506 @comment file: calc++-parser.yy
9507 @example
9508 %define parse.trace
9509 %define parse.error verbose
9510 @end example
9511
9512 @noindent
9513 @findex %code
9514 The code between @samp{%code @{} and @samp{@}} is output in the
9515 @file{*.cc} file; it needs detailed knowledge about the driver.
9516
9517 @comment file: calc++-parser.yy
9518 @example
9519 %code
9520 @{
9521 # include "calc++-driver.hh"
9522 @}
9523 @end example
9524
9525
9526 @noindent
9527 The token numbered as 0 corresponds to end of file; the following line
9528 allows for nicer error messages referring to ``end of file'' instead of
9529 ``$end''. Similarly user friendly names are provided for each symbol. To
9530 avoid name clashes in the generated files (@pxref{Calc++ Scanner}), prefix
9531 tokens with @code{TOK_} (@pxref{%define Summary,,api.tokens.prefix}).
9532
9533 @comment file: calc++-parser.yy
9534 @example
9535 %define api.tokens.prefix "TOK_"
9536 %token
9537 END 0 "end of file"
9538 ASSIGN ":="
9539 MINUS "-"
9540 PLUS "+"
9541 STAR "*"
9542 SLASH "/"
9543 LPAREN "("
9544 RPAREN ")"
9545 ;
9546 @end example
9547
9548 @noindent
9549 Since we use variant-based semantic values, @code{%union} is not used, and
9550 both @code{%type} and @code{%token} expect genuine types, as opposed to type
9551 tags.
9552
9553 @comment file: calc++-parser.yy
9554 @example
9555 %token <std::string> IDENTIFIER "identifier"
9556 %token <int> NUMBER "number"
9557 %type <int> exp
9558 @end example
9559
9560 @noindent
9561 No @code{%destructor} is needed to enable memory deallocation during error
9562 recovery; the memory, for strings for instance, will be reclaimed by the
9563 regular destructors. All the values are printed using their
9564 @code{operator<<}.
9565
9566 @c FIXME: Document %printer, and mention that it takes a braced-code operand.
9567 @comment file: calc++-parser.yy
9568 @example
9569 %printer @{ debug_stream () << $$; @} <*>;
9570 @end example
9571
9572 @noindent
9573 The grammar itself is straightforward (@pxref{Location Tracking Calc, ,
9574 Location Tracking Calculator: @code{ltcalc}}).
9575
9576 @comment file: calc++-parser.yy
9577 @example
9578 %%
9579 %start unit;
9580 unit: assignments exp @{ driver.result = $2; @};
9581
9582 assignments:
9583 assignments assignment @{@}
9584 | /* Nothing. */ @{@};
9585
9586 assignment:
9587 "identifier" ":=" exp @{ driver.variables[$1] = $3; @};
9588
9589 %left "+" "-";
9590 %left "*" "/";
9591 exp:
9592 exp "+" exp @{ $$ = $1 + $3; @}
9593 | exp "-" exp @{ $$ = $1 - $3; @}
9594 | exp "*" exp @{ $$ = $1 * $3; @}
9595 | exp "/" exp @{ $$ = $1 / $3; @}
9596 | "(" exp ")" @{ std::swap ($$, $2); @}
9597 | "identifier" @{ $$ = driver.variables[$1]; @}
9598 | "number" @{ std::swap ($$, $1); @};
9599 %%
9600 @end example
9601
9602 @noindent
9603 Finally the @code{error} member function registers the errors to the
9604 driver.
9605
9606 @comment file: calc++-parser.yy
9607 @example
9608 void
9609 yy::calcxx_parser::error (const location_type& l,
9610 const std::string& m)
9611 @{
9612 driver.error (l, m);
9613 @}
9614 @end example
9615
9616 @node Calc++ Scanner
9617 @subsubsection Calc++ Scanner
9618
9619 The Flex scanner first includes the driver declaration, then the
9620 parser's to get the set of defined tokens.
9621
9622 @comment file: calc++-scanner.ll
9623 @example
9624 %@{ /* -*- C++ -*- */
9625 # include <cerrno>
9626 # include <climits>
9627 # include <cstdlib>
9628 # include <string>
9629 # include "calc++-driver.hh"
9630 # include "calc++-parser.hh"
9631
9632 // Work around an incompatibility in flex (at least versions
9633 // 2.5.31 through 2.5.33): it generates code that does
9634 // not conform to C89. See Debian bug 333231
9635 // <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>.
9636 # undef yywrap
9637 # define yywrap() 1
9638
9639 // The location of the current token.
9640 static yy::location loc;
9641 %@}
9642 @end example
9643
9644 @noindent
9645 Because there is no @code{#include}-like feature we don't need
9646 @code{yywrap}, we don't need @code{unput} either, and we parse an
9647 actual file, this is not an interactive session with the user.
9648 Finally, we enable scanner tracing.
9649
9650 @comment file: calc++-scanner.ll
9651 @example
9652 %option noyywrap nounput batch debug
9653 @end example
9654
9655 @noindent
9656 Abbreviations allow for more readable rules.
9657
9658 @comment file: calc++-scanner.ll
9659 @example
9660 id [a-zA-Z][a-zA-Z_0-9]*
9661 int [0-9]+
9662 blank [ \t]
9663 @end example
9664
9665 @noindent
9666 The following paragraph suffices to track locations accurately. Each
9667 time @code{yylex} is invoked, the begin position is moved onto the end
9668 position. Then when a pattern is matched, its width is added to the end
9669 column. When matching ends of lines, the end
9670 cursor is adjusted, and each time blanks are matched, the begin cursor
9671 is moved onto the end cursor to effectively ignore the blanks
9672 preceding tokens. Comments would be treated equally.
9673
9674 @comment file: calc++-scanner.ll
9675 @example
9676 %@{
9677 // Code run each time a pattern is matched.
9678 # define YY_USER_ACTION loc.columns (yyleng);
9679 %@}
9680 %%
9681 %@{
9682 // Code run each time yylex is called.
9683 loc.step ();
9684 %@}
9685 @{blank@}+ loc.step ();
9686 [\n]+ loc.lines (yyleng); loc.step ();
9687 @end example
9688
9689 @noindent
9690 The rules are simple. The driver is used to report errors.
9691
9692 @comment file: calc++-scanner.ll
9693 @example
9694 "-" return yy::calcxx_parser::make_MINUS(loc);
9695 "+" return yy::calcxx_parser::make_PLUS(loc);
9696 "*" return yy::calcxx_parser::make_STAR(loc);
9697 "/" return yy::calcxx_parser::make_SLASH(loc);
9698 "(" return yy::calcxx_parser::make_LPAREN(loc);
9699 ")" return yy::calcxx_parser::make_RPAREN(loc);
9700 ":=" return yy::calcxx_parser::make_ASSIGN(loc);
9701
9702 @{int@} @{
9703 errno = 0;
9704 long n = strtol (yytext, NULL, 10);
9705 if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
9706 driver.error (loc, "integer is out of range");
9707 return yy::calcxx_parser::make_NUMBER(n, loc);
9708 @}
9709 @{id@} return yy::calcxx_parser::make_IDENTIFIER(yytext, loc);
9710 . driver.error (loc, "invalid character");
9711 <<EOF>> return yy::calcxx_parser::make_END(loc);
9712 %%
9713 @end example
9714
9715 @noindent
9716 Finally, because the scanner-related driver's member-functions depend
9717 on the scanner's data, it is simpler to implement them in this file.
9718
9719 @comment file: calc++-scanner.ll
9720 @example
9721 void
9722 calcxx_driver::scan_begin ()
9723 @{
9724 yy_flex_debug = trace_scanning;
9725 if (file == "-")
9726 yyin = stdin;
9727 else if (!(yyin = fopen (file.c_str (), "r")))
9728 @{
9729 error (std::string ("cannot open ") + file + ": " + strerror(errno));
9730 exit (1);
9731 @}
9732 @}
9733
9734 void
9735 calcxx_driver::scan_end ()
9736 @{
9737 fclose (yyin);
9738 @}
9739 @end example
9740
9741 @node Calc++ Top Level
9742 @subsubsection Calc++ Top Level
9743
9744 The top level file, @file{calc++.cc}, poses no problem.
9745
9746 @comment file: calc++.cc
9747 @example
9748 #include <iostream>
9749 #include "calc++-driver.hh"
9750
9751 int
9752 main (int argc, char *argv[])
9753 @{
9754 int res = 0;
9755 calcxx_driver driver;
9756 for (++argv; argv[0]; ++argv)
9757 if (*argv == std::string ("-p"))
9758 driver.trace_parsing = true;
9759 else if (*argv == std::string ("-s"))
9760 driver.trace_scanning = true;
9761 else if (!driver.parse (*argv))
9762 std::cout << driver.result << std::endl;
9763 else
9764 res = 1;
9765 return res;
9766 @}
9767 @end example
9768
9769 @node Java Parsers
9770 @section Java Parsers
9771
9772 @menu
9773 * Java Bison Interface:: Asking for Java parser generation
9774 * Java Semantic Values:: %type and %token vs. Java
9775 * Java Location Values:: The position and location classes
9776 * Java Parser Interface:: Instantiating and running the parser
9777 * Java Scanner Interface:: Specifying the scanner for the parser
9778 * Java Action Features:: Special features for use in actions
9779 * Java Differences:: Differences between C/C++ and Java Grammars
9780 * Java Declarations Summary:: List of Bison declarations used with Java
9781 @end menu
9782
9783 @node Java Bison Interface
9784 @subsection Java Bison Interface
9785 @c - %language "Java"
9786
9787 (The current Java interface is experimental and may evolve.
9788 More user feedback will help to stabilize it.)
9789
9790 The Java parser skeletons are selected using the @code{%language "Java"}
9791 directive or the @option{-L java}/@option{--language=java} option.
9792
9793 @c FIXME: Documented bug.
9794 When generating a Java parser, @code{bison @var{basename}.y} will
9795 create a single Java source file named @file{@var{basename}.java}
9796 containing the parser implementation. Using a grammar file without a
9797 @file{.y} suffix is currently broken. The basename of the parser
9798 implementation file can be changed by the @code{%file-prefix}
9799 directive or the @option{-p}/@option{--name-prefix} option. The
9800 entire parser implementation file name can be changed by the
9801 @code{%output} directive or the @option{-o}/@option{--output} option.
9802 The parser implementation file contains a single class for the parser.
9803
9804 You can create documentation for generated parsers using Javadoc.
9805
9806 Contrary to C parsers, Java parsers do not use global variables; the
9807 state of the parser is always local to an instance of the parser class.
9808 Therefore, all Java parsers are ``pure'', and the @code{%pure-parser}
9809 and @samp{%define api.pure} directives does not do anything when used in
9810 Java.
9811
9812 Push parsers are currently unsupported in Java and @code{%define
9813 api.push-pull} have no effect.
9814
9815 GLR parsers are currently unsupported in Java. Do not use the
9816 @code{glr-parser} directive.
9817
9818 No header file can be generated for Java parsers. Do not use the
9819 @code{%defines} directive or the @option{-d}/@option{--defines} options.
9820
9821 @c FIXME: Possible code change.
9822 Currently, support for tracing is always compiled
9823 in. Thus the @samp{%define parse.trace} and @samp{%token-table}
9824 directives and the
9825 @option{-t}/@option{--debug} and @option{-k}/@option{--token-table}
9826 options have no effect. This may change in the future to eliminate
9827 unused code in the generated parser, so use @samp{%define parse.trace}
9828 explicitly
9829 if needed. Also, in the future the
9830 @code{%token-table} directive might enable a public interface to
9831 access the token names and codes.
9832
9833 Getting a ``code too large'' error from the Java compiler means the code
9834 hit the 64KB bytecode per method limitation of the Java class file.
9835 Try reducing the amount of code in actions and static initializers;
9836 otherwise, report a bug so that the parser skeleton will be improved.
9837
9838
9839 @node Java Semantic Values
9840 @subsection Java Semantic Values
9841 @c - No %union, specify type in %type/%token.
9842 @c - YYSTYPE
9843 @c - Printer and destructor
9844
9845 There is no @code{%union} directive in Java parsers. Instead, the
9846 semantic values' types (class names) should be specified in the
9847 @code{%type} or @code{%token} directive:
9848
9849 @example
9850 %type <Expression> expr assignment_expr term factor
9851 %type <Integer> number
9852 @end example
9853
9854 By default, the semantic stack is declared to have @code{Object} members,
9855 which means that the class types you specify can be of any class.
9856 To improve the type safety of the parser, you can declare the common
9857 superclass of all the semantic values using the @samp{%define stype}
9858 directive. For example, after the following declaration:
9859
9860 @example
9861 %define stype "ASTNode"
9862 @end example
9863
9864 @noindent
9865 any @code{%type} or @code{%token} specifying a semantic type which
9866 is not a subclass of ASTNode, will cause a compile-time error.
9867
9868 @c FIXME: Documented bug.
9869 Types used in the directives may be qualified with a package name.
9870 Primitive data types are accepted for Java version 1.5 or later. Note
9871 that in this case the autoboxing feature of Java 1.5 will be used.
9872 Generic types may not be used; this is due to a limitation in the
9873 implementation of Bison, and may change in future releases.
9874
9875 Java parsers do not support @code{%destructor}, since the language
9876 adopts garbage collection. The parser will try to hold references
9877 to semantic values for as little time as needed.
9878
9879 Java parsers do not support @code{%printer}, as @code{toString()}
9880 can be used to print the semantic values. This however may change
9881 (in a backwards-compatible way) in future versions of Bison.
9882
9883
9884 @node Java Location Values
9885 @subsection Java Location Values
9886 @c - %locations
9887 @c - class Position
9888 @c - class Location
9889
9890 When the directive @code{%locations} is used, the Java parser
9891 supports location tracking, see @ref{Locations, , Locations Overview}.
9892 An auxiliary user-defined class defines a @dfn{position}, a single point
9893 in a file; Bison itself defines a class representing a @dfn{location},
9894 a range composed of a pair of positions (possibly spanning several
9895 files). The location class is an inner class of the parser; the name
9896 is @code{Location} by default, and may also be renamed using
9897 @samp{%define location_type "@var{class-name}"}.
9898
9899 The location class treats the position as a completely opaque value.
9900 By default, the class name is @code{Position}, but this can be changed
9901 with @samp{%define position_type "@var{class-name}"}. This class must
9902 be supplied by the user.
9903
9904
9905 @deftypeivar {Location} {Position} begin
9906 @deftypeivarx {Location} {Position} end
9907 The first, inclusive, position of the range, and the first beyond.
9908 @end deftypeivar
9909
9910 @deftypeop {Constructor} {Location} {} Location (Position @var{loc})
9911 Create a @code{Location} denoting an empty range located at a given point.
9912 @end deftypeop
9913
9914 @deftypeop {Constructor} {Location} {} Location (Position @var{begin}, Position @var{end})
9915 Create a @code{Location} from the endpoints of the range.
9916 @end deftypeop
9917
9918 @deftypemethod {Location} {String} toString ()
9919 Prints the range represented by the location. For this to work
9920 properly, the position class should override the @code{equals} and
9921 @code{toString} methods appropriately.
9922 @end deftypemethod
9923
9924
9925 @node Java Parser Interface
9926 @subsection Java Parser Interface
9927 @c - define parser_class_name
9928 @c - Ctor
9929 @c - parse, error, set_debug_level, debug_level, set_debug_stream,
9930 @c debug_stream.
9931 @c - Reporting errors
9932
9933 The name of the generated parser class defaults to @code{YYParser}. The
9934 @code{YY} prefix may be changed using the @code{%name-prefix} directive
9935 or the @option{-p}/@option{--name-prefix} option. Alternatively, use
9936 @samp{%define parser_class_name "@var{name}"} to give a custom name to
9937 the class. The interface of this class is detailed below.
9938
9939 By default, the parser class has package visibility. A declaration
9940 @samp{%define public} will change to public visibility. Remember that,
9941 according to the Java language specification, the name of the @file{.java}
9942 file should match the name of the class in this case. Similarly, you can
9943 use @code{abstract}, @code{final} and @code{strictfp} with the
9944 @code{%define} declaration to add other modifiers to the parser class.
9945 A single @samp{%define annotations "@var{annotations}"} directive can
9946 be used to add any number of annotations to the parser class.
9947
9948 The Java package name of the parser class can be specified using the
9949 @samp{%define package} directive. The superclass and the implemented
9950 interfaces of the parser class can be specified with the @code{%define
9951 extends} and @samp{%define implements} directives.
9952
9953 The parser class defines an inner class, @code{Location}, that is used
9954 for location tracking (see @ref{Java Location Values}), and a inner
9955 interface, @code{Lexer} (see @ref{Java Scanner Interface}). Other than
9956 these inner class/interface, and the members described in the interface
9957 below, all the other members and fields are preceded with a @code{yy} or
9958 @code{YY} prefix to avoid clashes with user code.
9959
9960 The parser class can be extended using the @code{%parse-param}
9961 directive. Each occurrence of the directive will add a @code{protected
9962 final} field to the parser class, and an argument to its constructor,
9963 which initialize them automatically.
9964
9965 @deftypeop {Constructor} {YYParser} {} YYParser (@var{lex_param}, @dots{}, @var{parse_param}, @dots{})
9966 Build a new parser object with embedded @code{%code lexer}. There are
9967 no parameters, unless @code{%param}s and/or @code{%parse-param}s and/or
9968 @code{%lex-param}s are used.
9969
9970 Use @code{%code init} for code added to the start of the constructor
9971 body. This is especially useful to initialize superclasses. Use
9972 @samp{%define init_throws} to specify any uncaught exceptions.
9973 @end deftypeop
9974
9975 @deftypeop {Constructor} {YYParser} {} YYParser (Lexer @var{lexer}, @var{parse_param}, @dots{})
9976 Build a new parser object using the specified scanner. There are no
9977 additional parameters unless @code{%param}s and/or @code{%parse-param}s are
9978 used.
9979
9980 If the scanner is defined by @code{%code lexer}, this constructor is
9981 declared @code{protected} and is called automatically with a scanner
9982 created with the correct @code{%param}s and/or @code{%lex-param}s.
9983
9984 Use @code{%code init} for code added to the start of the constructor
9985 body. This is especially useful to initialize superclasses. Use
9986 @samp{%define init_throws} to specify any uncatch exceptions.
9987 @end deftypeop
9988
9989 @deftypemethod {YYParser} {boolean} parse ()
9990 Run the syntactic analysis, and return @code{true} on success,
9991 @code{false} otherwise.
9992 @end deftypemethod
9993
9994 @deftypemethod {YYParser} {boolean} getErrorVerbose ()
9995 @deftypemethodx {YYParser} {void} setErrorVerbose (boolean @var{verbose})
9996 Get or set the option to produce verbose error messages. These are only
9997 available with @samp{%define parse.error verbose}, which also turns on
9998 verbose error messages.
9999 @end deftypemethod
10000
10001 @deftypemethod {YYParser} {void} yyerror (String @var{msg})
10002 @deftypemethodx {YYParser} {void} yyerror (Position @var{pos}, String @var{msg})
10003 @deftypemethodx {YYParser} {void} yyerror (Location @var{loc}, String @var{msg})
10004 Print an error message using the @code{yyerror} method of the scanner
10005 instance in use. The @code{Location} and @code{Position} parameters are
10006 available only if location tracking is active.
10007 @end deftypemethod
10008
10009 @deftypemethod {YYParser} {boolean} recovering ()
10010 During the syntactic analysis, return @code{true} if recovering
10011 from a syntax error.
10012 @xref{Error Recovery}.
10013 @end deftypemethod
10014
10015 @deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
10016 @deftypemethodx {YYParser} {void} setDebugStream (java.io.printStream @var{o})
10017 Get or set the stream used for tracing the parsing. It defaults to
10018 @code{System.err}.
10019 @end deftypemethod
10020
10021 @deftypemethod {YYParser} {int} getDebugLevel ()
10022 @deftypemethodx {YYParser} {void} setDebugLevel (int @var{l})
10023 Get or set the tracing level. Currently its value is either 0, no trace,
10024 or nonzero, full tracing.
10025 @end deftypemethod
10026
10027 @deftypecv {Constant} {YYParser} {String} {bisonVersion}
10028 @deftypecvx {Constant} {YYParser} {String} {bisonSkeleton}
10029 Identify the Bison version and skeleton used to generate this parser.
10030 @end deftypecv
10031
10032
10033 @node Java Scanner Interface
10034 @subsection Java Scanner Interface
10035 @c - %code lexer
10036 @c - %lex-param
10037 @c - Lexer interface
10038
10039 There are two possible ways to interface a Bison-generated Java parser
10040 with a scanner: the scanner may be defined by @code{%code lexer}, or
10041 defined elsewhere. In either case, the scanner has to implement the
10042 @code{Lexer} inner interface of the parser class. This interface also
10043 contain constants for all user-defined token names and the predefined
10044 @code{EOF} token.
10045
10046 In the first case, the body of the scanner class is placed in
10047 @code{%code lexer} blocks. If you want to pass parameters from the
10048 parser constructor to the scanner constructor, specify them with
10049 @code{%lex-param}; they are passed before @code{%parse-param}s to the
10050 constructor.
10051
10052 In the second case, the scanner has to implement the @code{Lexer} interface,
10053 which is defined within the parser class (e.g., @code{YYParser.Lexer}).
10054 The constructor of the parser object will then accept an object
10055 implementing the interface; @code{%lex-param} is not used in this
10056 case.
10057
10058 In both cases, the scanner has to implement the following methods.
10059
10060 @deftypemethod {Lexer} {void} yyerror (Location @var{loc}, String @var{msg})
10061 This method is defined by the user to emit an error message. The first
10062 parameter is omitted if location tracking is not active. Its type can be
10063 changed using @samp{%define location_type "@var{class-name}".}
10064 @end deftypemethod
10065
10066 @deftypemethod {Lexer} {int} yylex ()
10067 Return the next token. Its type is the return value, its semantic
10068 value and location are saved and returned by the their methods in the
10069 interface.
10070
10071 Use @samp{%define lex_throws} to specify any uncaught exceptions.
10072 Default is @code{java.io.IOException}.
10073 @end deftypemethod
10074
10075 @deftypemethod {Lexer} {Position} getStartPos ()
10076 @deftypemethodx {Lexer} {Position} getEndPos ()
10077 Return respectively the first position of the last token that
10078 @code{yylex} returned, and the first position beyond it. These
10079 methods are not needed unless location tracking is active.
10080
10081 The return type can be changed using @samp{%define position_type
10082 "@var{class-name}".}
10083 @end deftypemethod
10084
10085 @deftypemethod {Lexer} {Object} getLVal ()
10086 Return the semantic value of the last token that yylex returned.
10087
10088 The return type can be changed using @samp{%define stype
10089 "@var{class-name}".}
10090 @end deftypemethod
10091
10092
10093 @node Java Action Features
10094 @subsection Special Features for Use in Java Actions
10095
10096 The following special constructs can be uses in Java actions.
10097 Other analogous C action features are currently unavailable for Java.
10098
10099 Use @samp{%define throws} to specify any uncaught exceptions from parser
10100 actions, and initial actions specified by @code{%initial-action}.
10101
10102 @defvar $@var{n}
10103 The semantic value for the @var{n}th component of the current rule.
10104 This may not be assigned to.
10105 @xref{Java Semantic Values}.
10106 @end defvar
10107
10108 @defvar $<@var{typealt}>@var{n}
10109 Like @code{$@var{n}} but specifies a alternative type @var{typealt}.
10110 @xref{Java Semantic Values}.
10111 @end defvar
10112
10113 @defvar $$
10114 The semantic value for the grouping made by the current rule. As a
10115 value, this is in the base type (@code{Object} or as specified by
10116 @samp{%define stype}) as in not cast to the declared subtype because
10117 casts are not allowed on the left-hand side of Java assignments.
10118 Use an explicit Java cast if the correct subtype is needed.
10119 @xref{Java Semantic Values}.
10120 @end defvar
10121
10122 @defvar $<@var{typealt}>$
10123 Same as @code{$$} since Java always allow assigning to the base type.
10124 Perhaps we should use this and @code{$<>$} for the value and @code{$$}
10125 for setting the value but there is currently no easy way to distinguish
10126 these constructs.
10127 @xref{Java Semantic Values}.
10128 @end defvar
10129
10130 @defvar @@@var{n}
10131 The location information of the @var{n}th component of the current rule.
10132 This may not be assigned to.
10133 @xref{Java Location Values}.
10134 @end defvar
10135
10136 @defvar @@$
10137 The location information of the grouping made by the current rule.
10138 @xref{Java Location Values}.
10139 @end defvar
10140
10141 @deffn {Statement} {return YYABORT;}
10142 Return immediately from the parser, indicating failure.
10143 @xref{Java Parser Interface}.
10144 @end deffn
10145
10146 @deffn {Statement} {return YYACCEPT;}
10147 Return immediately from the parser, indicating success.
10148 @xref{Java Parser Interface}.
10149 @end deffn
10150
10151 @deffn {Statement} {return YYERROR;}
10152 Start error recovery without printing an error message.
10153 @xref{Error Recovery}.
10154 @end deffn
10155
10156 @deftypefn {Function} {boolean} recovering ()
10157 Return whether error recovery is being done. In this state, the parser
10158 reads token until it reaches a known state, and then restarts normal
10159 operation.
10160 @xref{Error Recovery}.
10161 @end deftypefn
10162
10163 @deftypefn {Function} {void} yyerror (String @var{msg})
10164 @deftypefnx {Function} {void} yyerror (Position @var{loc}, String @var{msg})
10165 @deftypefnx {Function} {void} yyerror (Location @var{loc}, String @var{msg})
10166 Print an error message using the @code{yyerror} method of the scanner
10167 instance in use. The @code{Location} and @code{Position} parameters are
10168 available only if location tracking is active.
10169 @end deftypefn
10170
10171
10172 @node Java Differences
10173 @subsection Differences between C/C++ and Java Grammars
10174
10175 The different structure of the Java language forces several differences
10176 between C/C++ grammars, and grammars designed for Java parsers. This
10177 section summarizes these differences.
10178
10179 @itemize
10180 @item
10181 Java lacks a preprocessor, so the @code{YYERROR}, @code{YYACCEPT},
10182 @code{YYABORT} symbols (@pxref{Table of Symbols}) cannot obviously be
10183 macros. Instead, they should be preceded by @code{return} when they
10184 appear in an action. The actual definition of these symbols is
10185 opaque to the Bison grammar, and it might change in the future. The
10186 only meaningful operation that you can do, is to return them.
10187 See @pxref{Java Action Features}.
10188
10189 Note that of these three symbols, only @code{YYACCEPT} and
10190 @code{YYABORT} will cause a return from the @code{yyparse}
10191 method@footnote{Java parsers include the actions in a separate
10192 method than @code{yyparse} in order to have an intuitive syntax that
10193 corresponds to these C macros.}.
10194
10195 @item
10196 Java lacks unions, so @code{%union} has no effect. Instead, semantic
10197 values have a common base type: @code{Object} or as specified by
10198 @samp{%define stype}. Angle brackets on @code{%token}, @code{type},
10199 @code{$@var{n}} and @code{$$} specify subtypes rather than fields of
10200 an union. The type of @code{$$}, even with angle brackets, is the base
10201 type since Java casts are not allow on the left-hand side of assignments.
10202 Also, @code{$@var{n}} and @code{@@@var{n}} are not allowed on the
10203 left-hand side of assignments. See @pxref{Java Semantic Values} and
10204 @pxref{Java Action Features}.
10205
10206 @item
10207 The prologue declarations have a different meaning than in C/C++ code.
10208 @table @asis
10209 @item @code{%code imports}
10210 blocks are placed at the beginning of the Java source code. They may
10211 include copyright notices. For a @code{package} declarations, it is
10212 suggested to use @samp{%define package} instead.
10213
10214 @item unqualified @code{%code}
10215 blocks are placed inside the parser class.
10216
10217 @item @code{%code lexer}
10218 blocks, if specified, should include the implementation of the
10219 scanner. If there is no such block, the scanner can be any class
10220 that implements the appropriate interface (see @pxref{Java Scanner
10221 Interface}).
10222 @end table
10223
10224 Other @code{%code} blocks are not supported in Java parsers.
10225 In particular, @code{%@{ @dots{} %@}} blocks should not be used
10226 and may give an error in future versions of Bison.
10227
10228 The epilogue has the same meaning as in C/C++ code and it can
10229 be used to define other classes used by the parser @emph{outside}
10230 the parser class.
10231 @end itemize
10232
10233
10234 @node Java Declarations Summary
10235 @subsection Java Declarations Summary
10236
10237 This summary only include declarations specific to Java or have special
10238 meaning when used in a Java parser.
10239
10240 @deffn {Directive} {%language "Java"}
10241 Generate a Java class for the parser.
10242 @end deffn
10243
10244 @deffn {Directive} %lex-param @{@var{type} @var{name}@}
10245 A parameter for the lexer class defined by @code{%code lexer}
10246 @emph{only}, added as parameters to the lexer constructor and the parser
10247 constructor that @emph{creates} a lexer. Default is none.
10248 @xref{Java Scanner Interface}.
10249 @end deffn
10250
10251 @deffn {Directive} %name-prefix "@var{prefix}"
10252 The prefix of the parser class name @code{@var{prefix}Parser} if
10253 @samp{%define parser_class_name} is not used. Default is @code{YY}.
10254 @xref{Java Bison Interface}.
10255 @end deffn
10256
10257 @deffn {Directive} %parse-param @{@var{type} @var{name}@}
10258 A parameter for the parser class added as parameters to constructor(s)
10259 and as fields initialized by the constructor(s). Default is none.
10260 @xref{Java Parser Interface}.
10261 @end deffn
10262
10263 @deffn {Directive} %token <@var{type}> @var{token} @dots{}
10264 Declare tokens. Note that the angle brackets enclose a Java @emph{type}.
10265 @xref{Java Semantic Values}.
10266 @end deffn
10267
10268 @deffn {Directive} %type <@var{type}> @var{nonterminal} @dots{}
10269 Declare the type of nonterminals. Note that the angle brackets enclose
10270 a Java @emph{type}.
10271 @xref{Java Semantic Values}.
10272 @end deffn
10273
10274 @deffn {Directive} %code @{ @var{code} @dots{} @}
10275 Code appended to the inside of the parser class.
10276 @xref{Java Differences}.
10277 @end deffn
10278
10279 @deffn {Directive} {%code imports} @{ @var{code} @dots{} @}
10280 Code inserted just after the @code{package} declaration.
10281 @xref{Java Differences}.
10282 @end deffn
10283
10284 @deffn {Directive} {%code init} @{ @var{code} @dots{} @}
10285 Code inserted at the beginning of the parser constructor body.
10286 @xref{Java Parser Interface}.
10287 @end deffn
10288
10289 @deffn {Directive} {%code lexer} @{ @var{code} @dots{} @}
10290 Code added to the body of a inner lexer class within the parser class.
10291 @xref{Java Scanner Interface}.
10292 @end deffn
10293
10294 @deffn {Directive} %% @var{code} @dots{}
10295 Code (after the second @code{%%}) appended to the end of the file,
10296 @emph{outside} the parser class.
10297 @xref{Java Differences}.
10298 @end deffn
10299
10300 @deffn {Directive} %@{ @var{code} @dots{} %@}
10301 Not supported. Use @code{%code imports} instead.
10302 @xref{Java Differences}.
10303 @end deffn
10304
10305 @deffn {Directive} {%define abstract}
10306 Whether the parser class is declared @code{abstract}. Default is false.
10307 @xref{Java Bison Interface}.
10308 @end deffn
10309
10310 @deffn {Directive} {%define annotations} "@var{annotations}"
10311 The Java annotations for the parser class. Default is none.
10312 @xref{Java Bison Interface}.
10313 @end deffn
10314
10315 @deffn {Directive} {%define extends} "@var{superclass}"
10316 The superclass of the parser class. Default is none.
10317 @xref{Java Bison Interface}.
10318 @end deffn
10319
10320 @deffn {Directive} {%define final}
10321 Whether the parser class is declared @code{final}. Default is false.
10322 @xref{Java Bison Interface}.
10323 @end deffn
10324
10325 @deffn {Directive} {%define implements} "@var{interfaces}"
10326 The implemented interfaces of the parser class, a comma-separated list.
10327 Default is none.
10328 @xref{Java Bison Interface}.
10329 @end deffn
10330
10331 @deffn {Directive} {%define init_throws} "@var{exceptions}"
10332 The exceptions thrown by @code{%code init} from the parser class
10333 constructor. Default is none.
10334 @xref{Java Parser Interface}.
10335 @end deffn
10336
10337 @deffn {Directive} {%define lex_throws} "@var{exceptions}"
10338 The exceptions thrown by the @code{yylex} method of the lexer, a
10339 comma-separated list. Default is @code{java.io.IOException}.
10340 @xref{Java Scanner Interface}.
10341 @end deffn
10342
10343 @deffn {Directive} {%define location_type} "@var{class}"
10344 The name of the class used for locations (a range between two
10345 positions). This class is generated as an inner class of the parser
10346 class by @command{bison}. Default is @code{Location}.
10347 @xref{Java Location Values}.
10348 @end deffn
10349
10350 @deffn {Directive} {%define package} "@var{package}"
10351 The package to put the parser class in. Default is none.
10352 @xref{Java Bison Interface}.
10353 @end deffn
10354
10355 @deffn {Directive} {%define parser_class_name} "@var{name}"
10356 The name of the parser class. Default is @code{YYParser} or
10357 @code{@var{name-prefix}Parser}.
10358 @xref{Java Bison Interface}.
10359 @end deffn
10360
10361 @deffn {Directive} {%define position_type} "@var{class}"
10362 The name of the class used for positions. This class must be supplied by
10363 the user. Default is @code{Position}.
10364 @xref{Java Location Values}.
10365 @end deffn
10366
10367 @deffn {Directive} {%define public}
10368 Whether the parser class is declared @code{public}. Default is false.
10369 @xref{Java Bison Interface}.
10370 @end deffn
10371
10372 @deffn {Directive} {%define stype} "@var{class}"
10373 The base type of semantic values. Default is @code{Object}.
10374 @xref{Java Semantic Values}.
10375 @end deffn
10376
10377 @deffn {Directive} {%define strictfp}
10378 Whether the parser class is declared @code{strictfp}. Default is false.
10379 @xref{Java Bison Interface}.
10380 @end deffn
10381
10382 @deffn {Directive} {%define throws} "@var{exceptions}"
10383 The exceptions thrown by user-supplied parser actions and
10384 @code{%initial-action}, a comma-separated list. Default is none.
10385 @xref{Java Parser Interface}.
10386 @end deffn
10387
10388
10389 @c ================================================= FAQ
10390
10391 @node FAQ
10392 @chapter Frequently Asked Questions
10393 @cindex frequently asked questions
10394 @cindex questions
10395
10396 Several questions about Bison come up occasionally. Here some of them
10397 are addressed.
10398
10399 @menu
10400 * Memory Exhausted:: Breaking the Stack Limits
10401 * How Can I Reset the Parser:: @code{yyparse} Keeps some State
10402 * Strings are Destroyed:: @code{yylval} Loses Track of Strings
10403 * Implementing Gotos/Loops:: Control Flow in the Calculator
10404 * Multiple start-symbols:: Factoring closely related grammars
10405 * Secure? Conform?:: Is Bison POSIX safe?
10406 * I can't build Bison:: Troubleshooting
10407 * Where can I find help?:: Troubleshouting
10408 * Bug Reports:: Troublereporting
10409 * More Languages:: Parsers in C++, Java, and so on
10410 * Beta Testing:: Experimenting development versions
10411 * Mailing Lists:: Meeting other Bison users
10412 @end menu
10413
10414 @node Memory Exhausted
10415 @section Memory Exhausted
10416
10417 @display
10418 My parser returns with error with a @samp{memory exhausted}
10419 message. What can I do?
10420 @end display
10421
10422 This question is already addressed elsewhere, @xref{Recursion,
10423 ,Recursive Rules}.
10424
10425 @node How Can I Reset the Parser
10426 @section How Can I Reset the Parser
10427
10428 The following phenomenon has several symptoms, resulting in the
10429 following typical questions:
10430
10431 @display
10432 I invoke @code{yyparse} several times, and on correct input it works
10433 properly; but when a parse error is found, all the other calls fail
10434 too. How can I reset the error flag of @code{yyparse}?
10435 @end display
10436
10437 @noindent
10438 or
10439
10440 @display
10441 My parser includes support for an @samp{#include}-like feature, in
10442 which case I run @code{yyparse} from @code{yyparse}. This fails
10443 although I did specify @samp{%define api.pure}.
10444 @end display
10445
10446 These problems typically come not from Bison itself, but from
10447 Lex-generated scanners. Because these scanners use large buffers for
10448 speed, they might not notice a change of input file. As a
10449 demonstration, consider the following source file,
10450 @file{first-line.l}:
10451
10452 @verbatim
10453 %{
10454 #include <stdio.h>
10455 #include <stdlib.h>
10456 %}
10457 %%
10458 .*\n ECHO; return 1;
10459 %%
10460 int
10461 yyparse (char const *file)
10462 {
10463 yyin = fopen (file, "r");
10464 if (!yyin)
10465 exit (2);
10466 /* One token only. */
10467 yylex ();
10468 if (fclose (yyin) != 0)
10469 exit (3);
10470 return 0;
10471 }
10472
10473 int
10474 main (void)
10475 {
10476 yyparse ("input");
10477 yyparse ("input");
10478 return 0;
10479 }
10480 @end verbatim
10481
10482 @noindent
10483 If the file @file{input} contains
10484
10485 @verbatim
10486 input:1: Hello,
10487 input:2: World!
10488 @end verbatim
10489
10490 @noindent
10491 then instead of getting the first line twice, you get:
10492
10493 @example
10494 $ @kbd{flex -ofirst-line.c first-line.l}
10495 $ @kbd{gcc -ofirst-line first-line.c -ll}
10496 $ @kbd{./first-line}
10497 input:1: Hello,
10498 input:2: World!
10499 @end example
10500
10501 Therefore, whenever you change @code{yyin}, you must tell the
10502 Lex-generated scanner to discard its current buffer and switch to the
10503 new one. This depends upon your implementation of Lex; see its
10504 documentation for more. For Flex, it suffices to call
10505 @samp{YY_FLUSH_BUFFER} after each change to @code{yyin}. If your
10506 Flex-generated scanner needs to read from several input streams to
10507 handle features like include files, you might consider using Flex
10508 functions like @samp{yy_switch_to_buffer} that manipulate multiple
10509 input buffers.
10510
10511 If your Flex-generated scanner uses start conditions (@pxref{Start
10512 conditions, , Start conditions, flex, The Flex Manual}), you might
10513 also want to reset the scanner's state, i.e., go back to the initial
10514 start condition, through a call to @samp{BEGIN (0)}.
10515
10516 @node Strings are Destroyed
10517 @section Strings are Destroyed
10518
10519 @display
10520 My parser seems to destroy old strings, or maybe it loses track of
10521 them. Instead of reporting @samp{"foo", "bar"}, it reports
10522 @samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
10523 @end display
10524
10525 This error is probably the single most frequent ``bug report'' sent to
10526 Bison lists, but is only concerned with a misunderstanding of the role
10527 of the scanner. Consider the following Lex code:
10528
10529 @verbatim
10530 %{
10531 #include <stdio.h>
10532 char *yylval = NULL;
10533 %}
10534 %%
10535 .* yylval = yytext; return 1;
10536 \n /* IGNORE */
10537 %%
10538 int
10539 main ()
10540 {
10541 /* Similar to using $1, $2 in a Bison action. */
10542 char *fst = (yylex (), yylval);
10543 char *snd = (yylex (), yylval);
10544 printf ("\"%s\", \"%s\"\n", fst, snd);
10545 return 0;
10546 }
10547 @end verbatim
10548
10549 If you compile and run this code, you get:
10550
10551 @example
10552 $ @kbd{flex -osplit-lines.c split-lines.l}
10553 $ @kbd{gcc -osplit-lines split-lines.c -ll}
10554 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
10555 "one
10556 two", "two"
10557 @end example
10558
10559 @noindent
10560 this is because @code{yytext} is a buffer provided for @emph{reading}
10561 in the action, but if you want to keep it, you have to duplicate it
10562 (e.g., using @code{strdup}). Note that the output may depend on how
10563 your implementation of Lex handles @code{yytext}. For instance, when
10564 given the Lex compatibility option @option{-l} (which triggers the
10565 option @samp{%array}) Flex generates a different behavior:
10566
10567 @example
10568 $ @kbd{flex -l -osplit-lines.c split-lines.l}
10569 $ @kbd{gcc -osplit-lines split-lines.c -ll}
10570 $ @kbd{printf 'one\ntwo\n' | ./split-lines}
10571 "two", "two"
10572 @end example
10573
10574
10575 @node Implementing Gotos/Loops
10576 @section Implementing Gotos/Loops
10577
10578 @display
10579 My simple calculator supports variables, assignments, and functions,
10580 but how can I implement gotos, or loops?
10581 @end display
10582
10583 Although very pedagogical, the examples included in the document blur
10584 the distinction to make between the parser---whose job is to recover
10585 the structure of a text and to transmit it to subsequent modules of
10586 the program---and the processing (such as the execution) of this
10587 structure. This works well with so called straight line programs,
10588 i.e., precisely those that have a straightforward execution model:
10589 execute simple instructions one after the others.
10590
10591 @cindex abstract syntax tree
10592 @cindex AST
10593 If you want a richer model, you will probably need to use the parser
10594 to construct a tree that does represent the structure it has
10595 recovered; this tree is usually called the @dfn{abstract syntax tree},
10596 or @dfn{AST} for short. Then, walking through this tree,
10597 traversing it in various ways, will enable treatments such as its
10598 execution or its translation, which will result in an interpreter or a
10599 compiler.
10600
10601 This topic is way beyond the scope of this manual, and the reader is
10602 invited to consult the dedicated literature.
10603
10604
10605 @node Multiple start-symbols
10606 @section Multiple start-symbols
10607
10608 @display
10609 I have several closely related grammars, and I would like to share their
10610 implementations. In fact, I could use a single grammar but with
10611 multiple entry points.
10612 @end display
10613
10614 Bison does not support multiple start-symbols, but there is a very
10615 simple means to simulate them. If @code{foo} and @code{bar} are the two
10616 pseudo start-symbols, then introduce two new tokens, say
10617 @code{START_FOO} and @code{START_BAR}, and use them as switches from the
10618 real start-symbol:
10619
10620 @example
10621 %token START_FOO START_BAR;
10622 %start start;
10623 start: START_FOO foo
10624 | START_BAR bar;
10625 @end example
10626
10627 These tokens prevents the introduction of new conflicts. As far as the
10628 parser goes, that is all that is needed.
10629
10630 Now the difficult part is ensuring that the scanner will send these
10631 tokens first. If your scanner is hand-written, that should be
10632 straightforward. If your scanner is generated by Lex, them there is
10633 simple means to do it: recall that anything between @samp{%@{ ... %@}}
10634 after the first @code{%%} is copied verbatim in the top of the generated
10635 @code{yylex} function. Make sure a variable @code{start_token} is
10636 available in the scanner (e.g., a global variable or using
10637 @code{%lex-param} etc.), and use the following:
10638
10639 @example
10640 /* @r{Prologue.} */
10641 %%
10642 %@{
10643 if (start_token)
10644 @{
10645 int t = start_token;
10646 start_token = 0;
10647 return t;
10648 @}
10649 %@}
10650 /* @r{The rules.} */
10651 @end example
10652
10653
10654 @node Secure? Conform?
10655 @section Secure? Conform?
10656
10657 @display
10658 Is Bison secure? Does it conform to POSIX?
10659 @end display
10660
10661 If you're looking for a guarantee or certification, we don't provide it.
10662 However, Bison is intended to be a reliable program that conforms to the
10663 POSIX specification for Yacc. If you run into problems,
10664 please send us a bug report.
10665
10666 @node I can't build Bison
10667 @section I can't build Bison
10668
10669 @display
10670 I can't build Bison because @command{make} complains that
10671 @code{msgfmt} is not found.
10672 What should I do?
10673 @end display
10674
10675 Like most GNU packages with internationalization support, that feature
10676 is turned on by default. If you have problems building in the @file{po}
10677 subdirectory, it indicates that your system's internationalization
10678 support is lacking. You can re-configure Bison with
10679 @option{--disable-nls} to turn off this support, or you can install GNU
10680 gettext from @url{ftp://ftp.gnu.org/gnu/gettext/} and re-configure
10681 Bison. See the file @file{ABOUT-NLS} for more information.
10682
10683
10684 @node Where can I find help?
10685 @section Where can I find help?
10686
10687 @display
10688 I'm having trouble using Bison. Where can I find help?
10689 @end display
10690
10691 First, read this fine manual. Beyond that, you can send mail to
10692 @email{help-bison@@gnu.org}. This mailing list is intended to be
10693 populated with people who are willing to answer questions about using
10694 and installing Bison. Please keep in mind that (most of) the people on
10695 the list have aspects of their lives which are not related to Bison (!),
10696 so you may not receive an answer to your question right away. This can
10697 be frustrating, but please try not to honk them off; remember that any
10698 help they provide is purely voluntary and out of the kindness of their
10699 hearts.
10700
10701 @node Bug Reports
10702 @section Bug Reports
10703
10704 @display
10705 I found a bug. What should I include in the bug report?
10706 @end display
10707
10708 Before you send a bug report, make sure you are using the latest
10709 version. Check @url{ftp://ftp.gnu.org/pub/gnu/bison/} or one of its
10710 mirrors. Be sure to include the version number in your bug report. If
10711 the bug is present in the latest version but not in a previous version,
10712 try to determine the most recent version which did not contain the bug.
10713
10714 If the bug is parser-related, you should include the smallest grammar
10715 you can which demonstrates the bug. The grammar file should also be
10716 complete (i.e., I should be able to run it through Bison without having
10717 to edit or add anything). The smaller and simpler the grammar, the
10718 easier it will be to fix the bug.
10719
10720 Include information about your compilation environment, including your
10721 operating system's name and version and your compiler's name and
10722 version. If you have trouble compiling, you should also include a
10723 transcript of the build session, starting with the invocation of
10724 `configure'. Depending on the nature of the bug, you may be asked to
10725 send additional files as well (such as `config.h' or `config.cache').
10726
10727 Patches are most welcome, but not required. That is, do not hesitate to
10728 send a bug report just because you can not provide a fix.
10729
10730 Send bug reports to @email{bug-bison@@gnu.org}.
10731
10732 @node More Languages
10733 @section More Languages
10734
10735 @display
10736 Will Bison ever have C++ and Java support? How about @var{insert your
10737 favorite language here}?
10738 @end display
10739
10740 C++ and Java support is there now, and is documented. We'd love to add other
10741 languages; contributions are welcome.
10742
10743 @node Beta Testing
10744 @section Beta Testing
10745
10746 @display
10747 What is involved in being a beta tester?
10748 @end display
10749
10750 It's not terribly involved. Basically, you would download a test
10751 release, compile it, and use it to build and run a parser or two. After
10752 that, you would submit either a bug report or a message saying that
10753 everything is okay. It is important to report successes as well as
10754 failures because test releases eventually become mainstream releases,
10755 but only if they are adequately tested. If no one tests, development is
10756 essentially halted.
10757
10758 Beta testers are particularly needed for operating systems to which the
10759 developers do not have easy access. They currently have easy access to
10760 recent GNU/Linux and Solaris versions. Reports about other operating
10761 systems are especially welcome.
10762
10763 @node Mailing Lists
10764 @section Mailing Lists
10765
10766 @display
10767 How do I join the help-bison and bug-bison mailing lists?
10768 @end display
10769
10770 See @url{http://lists.gnu.org/}.
10771
10772 @c ================================================= Table of Symbols
10773
10774 @node Table of Symbols
10775 @appendix Bison Symbols
10776 @cindex Bison symbols, table of
10777 @cindex symbols in Bison, table of
10778
10779 @deffn {Variable} @@$
10780 In an action, the location of the left-hand side of the rule.
10781 @xref{Locations, , Locations Overview}.
10782 @end deffn
10783
10784 @deffn {Variable} @@@var{n}
10785 In an action, the location of the @var{n}-th symbol of the right-hand
10786 side of the rule. @xref{Locations, , Locations Overview}.
10787 @end deffn
10788
10789 @deffn {Variable} @@@var{name}
10790 In an action, the location of a symbol addressed by name.
10791 @xref{Locations, , Locations Overview}.
10792 @end deffn
10793
10794 @deffn {Variable} @@[@var{name}]
10795 In an action, the location of a symbol addressed by name.
10796 @xref{Locations, , Locations Overview}.
10797 @end deffn
10798
10799 @deffn {Variable} $$
10800 In an action, the semantic value of the left-hand side of the rule.
10801 @xref{Actions}.
10802 @end deffn
10803
10804 @deffn {Variable} $@var{n}
10805 In an action, the semantic value of the @var{n}-th symbol of the
10806 right-hand side of the rule. @xref{Actions}.
10807 @end deffn
10808
10809 @deffn {Variable} $@var{name}
10810 In an action, the semantic value of a symbol addressed by name.
10811 @xref{Actions}.
10812 @end deffn
10813
10814 @deffn {Variable} $[@var{name}]
10815 In an action, the semantic value of a symbol addressed by name.
10816 @xref{Actions}.
10817 @end deffn
10818
10819 @deffn {Delimiter} %%
10820 Delimiter used to separate the grammar rule section from the
10821 Bison declarations section or the epilogue.
10822 @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
10823 @end deffn
10824
10825 @c Don't insert spaces, or check the DVI output.
10826 @deffn {Delimiter} %@{@var{code}%@}
10827 All code listed between @samp{%@{} and @samp{%@}} is copied verbatim
10828 to the parser implementation file. Such code forms the prologue of
10829 the grammar file. @xref{Grammar Outline, ,Outline of a Bison
10830 Grammar}.
10831 @end deffn
10832
10833 @deffn {Directive} %?@{@var{expression}@}
10834 Predicate actions. This is a type of action clause that may appear in
10835 rules. The expression is evaluated, and if false, causes a syntax error. In
10836 GLR parsers during nondeterministic operation,
10837 this silently causes an alternative parse to die. During deterministic
10838 operation, it is the same as the effect of YYERROR.
10839 @xref{Semantic Predicates}.
10840
10841 This feature is experimental.
10842 More user feedback will help to determine whether it should become a permanent
10843 feature.
10844 @end deffn
10845
10846 @deffn {Construct} /*@dots{}*/
10847 Comment delimiters, as in C.
10848 @end deffn
10849
10850 @deffn {Delimiter} :
10851 Separates a rule's result from its components. @xref{Rules, ,Syntax of
10852 Grammar Rules}.
10853 @end deffn
10854
10855 @deffn {Delimiter} ;
10856 Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
10857 @end deffn
10858
10859 @deffn {Delimiter} |
10860 Separates alternate rules for the same result nonterminal.
10861 @xref{Rules, ,Syntax of Grammar Rules}.
10862 @end deffn
10863
10864 @deffn {Directive} <*>
10865 Used to define a default tagged @code{%destructor} or default tagged
10866 @code{%printer}.
10867
10868 This feature is experimental.
10869 More user feedback will help to determine whether it should become a permanent
10870 feature.
10871
10872 @xref{Destructor Decl, , Freeing Discarded Symbols}.
10873 @end deffn
10874
10875 @deffn {Directive} <>
10876 Used to define a default tagless @code{%destructor} or default tagless
10877 @code{%printer}.
10878
10879 This feature is experimental.
10880 More user feedback will help to determine whether it should become a permanent
10881 feature.
10882
10883 @xref{Destructor Decl, , Freeing Discarded Symbols}.
10884 @end deffn
10885
10886 @deffn {Symbol} $accept
10887 The predefined nonterminal whose only rule is @samp{$accept: @var{start}
10888 $end}, where @var{start} is the start symbol. @xref{Start Decl, , The
10889 Start-Symbol}. It cannot be used in the grammar.
10890 @end deffn
10891
10892 @deffn {Directive} %code @{@var{code}@}
10893 @deffnx {Directive} %code @var{qualifier} @{@var{code}@}
10894 Insert @var{code} verbatim into the output parser source at the
10895 default location or at the location specified by @var{qualifier}.
10896 @xref{%code Summary}.
10897 @end deffn
10898
10899 @deffn {Directive} %debug
10900 Equip the parser for debugging. @xref{Decl Summary}.
10901 @end deffn
10902
10903 @ifset defaultprec
10904 @deffn {Directive} %default-prec
10905 Assign a precedence to rules that lack an explicit @samp{%prec}
10906 modifier. @xref{Contextual Precedence, ,Context-Dependent
10907 Precedence}.
10908 @end deffn
10909 @end ifset
10910
10911 @deffn {Directive} %define @var{define-variable}
10912 @deffnx {Directive} %define @var{define-variable} @var{value}
10913 @deffnx {Directive} %define @var{define-variable} "@var{value}"
10914 Define a variable to adjust Bison's behavior. @xref{%define Summary}.
10915 @end deffn
10916
10917 @deffn {Directive} %defines
10918 Bison declaration to create a parser header file, which is usually
10919 meant for the scanner. @xref{Decl Summary}.
10920 @end deffn
10921
10922 @deffn {Directive} %defines @var{defines-file}
10923 Same as above, but save in the file @var{defines-file}.
10924 @xref{Decl Summary}.
10925 @end deffn
10926
10927 @deffn {Directive} %destructor
10928 Specify how the parser should reclaim the memory associated to
10929 discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
10930 @end deffn
10931
10932 @deffn {Directive} %dprec
10933 Bison declaration to assign a precedence to a rule that is used at parse
10934 time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
10935 GLR Parsers}.
10936 @end deffn
10937
10938 @deffn {Symbol} $end
10939 The predefined token marking the end of the token stream. It cannot be
10940 used in the grammar.
10941 @end deffn
10942
10943 @deffn {Symbol} error
10944 A token name reserved for error recovery. This token may be used in
10945 grammar rules so as to allow the Bison parser to recognize an error in
10946 the grammar without halting the process. In effect, a sentence
10947 containing an error may be recognized as valid. On a syntax error, the
10948 token @code{error} becomes the current lookahead token. Actions
10949 corresponding to @code{error} are then executed, and the lookahead
10950 token is reset to the token that originally caused the violation.
10951 @xref{Error Recovery}.
10952 @end deffn
10953
10954 @deffn {Directive} %error-verbose
10955 An obsolete directive standing for @samp{%define parse.error verbose}.
10956 @end deffn
10957
10958 @deffn {Directive} %file-prefix "@var{prefix}"
10959 Bison declaration to set the prefix of the output files. @xref{Decl
10960 Summary}.
10961 @end deffn
10962
10963 @deffn {Directive} %glr-parser
10964 Bison declaration to produce a GLR parser. @xref{GLR
10965 Parsers, ,Writing GLR Parsers}.
10966 @end deffn
10967
10968 @deffn {Directive} %initial-action
10969 Run user code before parsing. @xref{Initial Action Decl, , Performing Actions before Parsing}.
10970 @end deffn
10971
10972 @deffn {Directive} %language
10973 Specify the programming language for the generated parser.
10974 @xref{Decl Summary}.
10975 @end deffn
10976
10977 @deffn {Directive} %left
10978 Bison declaration to assign precedence and left associativity to token(s).
10979 @xref{Precedence Decl, ,Operator Precedence}.
10980 @end deffn
10981
10982 @deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
10983 Bison declaration to specifying additional arguments that
10984 @code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
10985 for Pure Parsers}.
10986 @end deffn
10987
10988 @deffn {Directive} %merge
10989 Bison declaration to assign a merging function to a rule. If there is a
10990 reduce/reduce conflict with a rule having the same merging function, the
10991 function is applied to the two semantic values to get a single result.
10992 @xref{GLR Parsers, ,Writing GLR Parsers}.
10993 @end deffn
10994
10995 @deffn {Directive} %name-prefix "@var{prefix}"
10996 Bison declaration to rename the external symbols. @xref{Decl Summary}.
10997 @end deffn
10998
10999 @ifset defaultprec
11000 @deffn {Directive} %no-default-prec
11001 Do not assign a precedence to rules that lack an explicit @samp{%prec}
11002 modifier. @xref{Contextual Precedence, ,Context-Dependent
11003 Precedence}.
11004 @end deffn
11005 @end ifset
11006
11007 @deffn {Directive} %no-lines
11008 Bison declaration to avoid generating @code{#line} directives in the
11009 parser implementation file. @xref{Decl Summary}.
11010 @end deffn
11011
11012 @deffn {Directive} %nonassoc
11013 Bison declaration to assign precedence and nonassociativity to token(s).
11014 @xref{Precedence Decl, ,Operator Precedence}.
11015 @end deffn
11016
11017 @deffn {Directive} %output "@var{file}"
11018 Bison declaration to set the name of the parser implementation file.
11019 @xref{Decl Summary}.
11020 @end deffn
11021
11022 @deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
11023 Bison declaration to specify additional arguments that both
11024 @code{yylex} and @code{yyparse} should accept. @xref{Parser Function,, The
11025 Parser Function @code{yyparse}}.
11026 @end deffn
11027
11028 @deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
11029 Bison declaration to specify additional arguments that @code{yyparse}
11030 should accept. @xref{Parser Function,, The Parser Function @code{yyparse}}.
11031 @end deffn
11032
11033 @deffn {Directive} %prec
11034 Bison declaration to assign a precedence to a specific rule.
11035 @xref{Contextual Precedence, ,Context-Dependent Precedence}.
11036 @end deffn
11037
11038 @deffn {Directive} %precedence
11039 Bison declaration to assign precedence to token(s), but no associativity
11040 @xref{Precedence Decl, ,Operator Precedence}.
11041 @end deffn
11042
11043 @deffn {Directive} %pure-parser
11044 Deprecated version of @samp{%define api.pure} (@pxref{%define
11045 Summary,,api.pure}), for which Bison is more careful to warn about
11046 unreasonable usage.
11047 @end deffn
11048
11049 @deffn {Directive} %require "@var{version}"
11050 Require version @var{version} or higher of Bison. @xref{Require Decl, ,
11051 Require a Version of Bison}.
11052 @end deffn
11053
11054 @deffn {Directive} %right
11055 Bison declaration to assign precedence and right associativity to token(s).
11056 @xref{Precedence Decl, ,Operator Precedence}.
11057 @end deffn
11058
11059 @deffn {Directive} %skeleton
11060 Specify the skeleton to use; usually for development.
11061 @xref{Decl Summary}.
11062 @end deffn
11063
11064 @deffn {Directive} %start
11065 Bison declaration to specify the start symbol. @xref{Start Decl, ,The
11066 Start-Symbol}.
11067 @end deffn
11068
11069 @deffn {Directive} %token
11070 Bison declaration to declare token(s) without specifying precedence.
11071 @xref{Token Decl, ,Token Type Names}.
11072 @end deffn
11073
11074 @deffn {Directive} %token-table
11075 Bison declaration to include a token name table in the parser
11076 implementation file. @xref{Decl Summary}.
11077 @end deffn
11078
11079 @deffn {Directive} %type
11080 Bison declaration to declare nonterminals. @xref{Type Decl,
11081 ,Nonterminal Symbols}.
11082 @end deffn
11083
11084 @deffn {Symbol} $undefined
11085 The predefined token onto which all undefined values returned by
11086 @code{yylex} are mapped. It cannot be used in the grammar, rather, use
11087 @code{error}.
11088 @end deffn
11089
11090 @deffn {Directive} %union
11091 Bison declaration to specify several possible data types for semantic
11092 values. @xref{Union Decl, ,The Collection of Value Types}.
11093 @end deffn
11094
11095 @deffn {Macro} YYABORT
11096 Macro to pretend that an unrecoverable syntax error has occurred, by
11097 making @code{yyparse} return 1 immediately. The error reporting
11098 function @code{yyerror} is not called. @xref{Parser Function, ,The
11099 Parser Function @code{yyparse}}.
11100
11101 For Java parsers, this functionality is invoked using @code{return YYABORT;}
11102 instead.
11103 @end deffn
11104
11105 @deffn {Macro} YYACCEPT
11106 Macro to pretend that a complete utterance of the language has been
11107 read, by making @code{yyparse} return 0 immediately.
11108 @xref{Parser Function, ,The Parser Function @code{yyparse}}.
11109
11110 For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
11111 instead.
11112 @end deffn
11113
11114 @deffn {Macro} YYBACKUP
11115 Macro to discard a value from the parser stack and fake a lookahead
11116 token. @xref{Action Features, ,Special Features for Use in Actions}.
11117 @end deffn
11118
11119 @deffn {Variable} yychar
11120 External integer variable that contains the integer value of the
11121 lookahead token. (In a pure parser, it is a local variable within
11122 @code{yyparse}.) Error-recovery rule actions may examine this variable.
11123 @xref{Action Features, ,Special Features for Use in Actions}.
11124 @end deffn
11125
11126 @deffn {Variable} yyclearin
11127 Macro used in error-recovery rule actions. It clears the previous
11128 lookahead token. @xref{Error Recovery}.
11129 @end deffn
11130
11131 @deffn {Macro} YYDEBUG
11132 Macro to define to equip the parser with tracing code. @xref{Tracing,
11133 ,Tracing Your Parser}.
11134 @end deffn
11135
11136 @deffn {Variable} yydebug
11137 External integer variable set to zero by default. If @code{yydebug}
11138 is given a nonzero value, the parser will output information on input
11139 symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
11140 @end deffn
11141
11142 @deffn {Macro} yyerrok
11143 Macro to cause parser to recover immediately to its normal mode
11144 after a syntax error. @xref{Error Recovery}.
11145 @end deffn
11146
11147 @deffn {Macro} YYERROR
11148 Macro to pretend that a syntax error has just been detected: call
11149 @code{yyerror} and then perform normal error recovery if possible
11150 (@pxref{Error Recovery}), or (if recovery is impossible) make
11151 @code{yyparse} return 1. @xref{Error Recovery}.
11152
11153 For Java parsers, this functionality is invoked using @code{return YYERROR;}
11154 instead.
11155 @end deffn
11156
11157 @deffn {Function} yyerror
11158 User-supplied function to be called by @code{yyparse} on error.
11159 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
11160 @end deffn
11161
11162 @deffn {Macro} YYERROR_VERBOSE
11163 An obsolete macro used in the @file{yacc.c} skeleton, that you define
11164 with @code{#define} in the prologue to request verbose, specific error
11165 message strings when @code{yyerror} is called. It doesn't matter what
11166 definition you use for @code{YYERROR_VERBOSE}, just whether you define
11167 it. Using @samp{%define parse.error verbose} is preferred
11168 (@pxref{Error Reporting, ,The Error Reporting Function @code{yyerror}}).
11169 @end deffn
11170
11171 @deffn {Macro} YYINITDEPTH
11172 Macro for specifying the initial size of the parser stack.
11173 @xref{Memory Management}.
11174 @end deffn
11175
11176 @deffn {Function} yylex
11177 User-supplied lexical analyzer function, called with no arguments to get
11178 the next token. @xref{Lexical, ,The Lexical Analyzer Function
11179 @code{yylex}}.
11180 @end deffn
11181
11182 @deffn {Macro} YYLEX_PARAM
11183 An obsolete macro for specifying an extra argument (or list of extra
11184 arguments) for @code{yyparse} to pass to @code{yylex}. The use of this
11185 macro is deprecated, and is supported only for Yacc like parsers.
11186 @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
11187 @end deffn
11188
11189 @deffn {Variable} yylloc
11190 External variable in which @code{yylex} should place the line and column
11191 numbers associated with a token. (In a pure parser, it is a local
11192 variable within @code{yyparse}, and its address is passed to
11193 @code{yylex}.)
11194 You can ignore this variable if you don't use the @samp{@@} feature in the
11195 grammar actions.
11196 @xref{Token Locations, ,Textual Locations of Tokens}.
11197 In semantic actions, it stores the location of the lookahead token.
11198 @xref{Actions and Locations, ,Actions and Locations}.
11199 @end deffn
11200
11201 @deffn {Type} YYLTYPE
11202 Data type of @code{yylloc}; by default, a structure with four
11203 members. @xref{Location Type, , Data Types of Locations}.
11204 @end deffn
11205
11206 @deffn {Variable} yylval
11207 External variable in which @code{yylex} should place the semantic
11208 value associated with a token. (In a pure parser, it is a local
11209 variable within @code{yyparse}, and its address is passed to
11210 @code{yylex}.)
11211 @xref{Token Values, ,Semantic Values of Tokens}.
11212 In semantic actions, it stores the semantic value of the lookahead token.
11213 @xref{Actions, ,Actions}.
11214 @end deffn
11215
11216 @deffn {Macro} YYMAXDEPTH
11217 Macro for specifying the maximum size of the parser stack. @xref{Memory
11218 Management}.
11219 @end deffn
11220
11221 @deffn {Variable} yynerrs
11222 Global variable which Bison increments each time it reports a syntax error.
11223 (In a pure parser, it is a local variable within @code{yyparse}. In a
11224 pure push parser, it is a member of yypstate.)
11225 @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
11226 @end deffn
11227
11228 @deffn {Function} yyparse
11229 The parser function produced by Bison; call this function to start
11230 parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
11231 @end deffn
11232
11233 @deffn {Function} yypstate_delete
11234 The function to delete a parser instance, produced by Bison in push mode;
11235 call this function to delete the memory associated with a parser.
11236 @xref{Parser Delete Function, ,The Parser Delete Function
11237 @code{yypstate_delete}}.
11238 (The current push parsing interface is experimental and may evolve.
11239 More user feedback will help to stabilize it.)
11240 @end deffn
11241
11242 @deffn {Function} yypstate_new
11243 The function to create a parser instance, produced by Bison in push mode;
11244 call this function to create a new parser.
11245 @xref{Parser Create Function, ,The Parser Create Function
11246 @code{yypstate_new}}.
11247 (The current push parsing interface is experimental and may evolve.
11248 More user feedback will help to stabilize it.)
11249 @end deffn
11250
11251 @deffn {Function} yypull_parse
11252 The parser function produced by Bison in push mode; call this function to
11253 parse the rest of the input stream.
11254 @xref{Pull Parser Function, ,The Pull Parser Function
11255 @code{yypull_parse}}.
11256 (The current push parsing interface is experimental and may evolve.
11257 More user feedback will help to stabilize it.)
11258 @end deffn
11259
11260 @deffn {Function} yypush_parse
11261 The parser function produced by Bison in push mode; call this function to
11262 parse a single token. @xref{Push Parser Function, ,The Push Parser Function
11263 @code{yypush_parse}}.
11264 (The current push parsing interface is experimental and may evolve.
11265 More user feedback will help to stabilize it.)
11266 @end deffn
11267
11268 @deffn {Macro} YYPARSE_PARAM
11269 An obsolete macro for specifying the name of a parameter that
11270 @code{yyparse} should accept. The use of this macro is deprecated, and
11271 is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
11272 Conventions for Pure Parsers}.
11273 @end deffn
11274
11275 @deffn {Macro} YYRECOVERING
11276 The expression @code{YYRECOVERING ()} yields 1 when the parser
11277 is recovering from a syntax error, and 0 otherwise.
11278 @xref{Action Features, ,Special Features for Use in Actions}.
11279 @end deffn
11280
11281 @deffn {Macro} YYSTACK_USE_ALLOCA
11282 Macro used to control the use of @code{alloca} when the
11283 deterministic parser in C needs to extend its stacks. If defined to 0,
11284 the parser will use @code{malloc} to extend its stacks. If defined to
11285 1, the parser will use @code{alloca}. Values other than 0 and 1 are
11286 reserved for future Bison extensions. If not defined,
11287 @code{YYSTACK_USE_ALLOCA} defaults to 0.
11288
11289 In the all-too-common case where your code may run on a host with a
11290 limited stack and with unreliable stack-overflow checking, you should
11291 set @code{YYMAXDEPTH} to a value that cannot possibly result in
11292 unchecked stack overflow on any of your target hosts when
11293 @code{alloca} is called. You can inspect the code that Bison
11294 generates in order to determine the proper numeric values. This will
11295 require some expertise in low-level implementation details.
11296 @end deffn
11297
11298 @deffn {Type} YYSTYPE
11299 Data type of semantic values; @code{int} by default.
11300 @xref{Value Type, ,Data Types of Semantic Values}.
11301 @end deffn
11302
11303 @node Glossary
11304 @appendix Glossary
11305 @cindex glossary
11306
11307 @table @asis
11308 @item Accepting State
11309 A state whose only action is the accept action.
11310 The accepting state is thus a consistent state.
11311 @xref{Understanding,,}.
11312
11313 @item Backus-Naur Form (BNF; also called ``Backus Normal Form'')
11314 Formal method of specifying context-free grammars originally proposed
11315 by John Backus, and slightly improved by Peter Naur in his 1960-01-02
11316 committee document contributing to what became the Algol 60 report.
11317 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11318
11319 @item Consistent State
11320 A state containing only one possible action. @xref{%define
11321 Summary,,lr.default-reductions}.
11322
11323 @item Context-free grammars
11324 Grammars specified as rules that can be applied regardless of context.
11325 Thus, if there is a rule which says that an integer can be used as an
11326 expression, integers are allowed @emph{anywhere} an expression is
11327 permitted. @xref{Language and Grammar, ,Languages and Context-Free
11328 Grammars}.
11329
11330 @item Default Reduction
11331 The reduction that a parser should perform if the current parser state
11332 contains no other action for the lookahead token. In permitted parser
11333 states, Bison declares the reduction with the largest lookahead set to
11334 be the default reduction and removes that lookahead set.
11335 @xref{%define Summary,,lr.default-reductions}.
11336
11337 @item Dynamic allocation
11338 Allocation of memory that occurs during execution, rather than at
11339 compile time or on entry to a function.
11340
11341 @item Empty string
11342 Analogous to the empty set in set theory, the empty string is a
11343 character string of length zero.
11344
11345 @item Finite-state stack machine
11346 A ``machine'' that has discrete states in which it is said to exist at
11347 each instant in time. As input to the machine is processed, the
11348 machine moves from state to state as specified by the logic of the
11349 machine. In the case of the parser, the input is the language being
11350 parsed, and the states correspond to various stages in the grammar
11351 rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
11352
11353 @item Generalized LR (GLR)
11354 A parsing algorithm that can handle all context-free grammars, including those
11355 that are not LR(1). It resolves situations that Bison's
11356 deterministic parsing
11357 algorithm cannot by effectively splitting off multiple parsers, trying all
11358 possible parsers, and discarding those that fail in the light of additional
11359 right context. @xref{Generalized LR Parsing, ,Generalized
11360 LR Parsing}.
11361
11362 @item Grouping
11363 A language construct that is (in general) grammatically divisible;
11364 for example, `expression' or `declaration' in C@.
11365 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11366
11367 @item IELR(1)
11368 A minimal LR(1) parser table generation algorithm. That is, given any
11369 context-free grammar, IELR(1) generates parser tables with the full
11370 language recognition power of canonical LR(1) but with nearly the same
11371 number of parser states as LALR(1). This reduction in parser states
11372 is often an order of magnitude. More importantly, because canonical
11373 LR(1)'s extra parser states may contain duplicate conflicts in the
11374 case of non-LR(1) grammars, the number of conflicts for IELR(1) is
11375 often an order of magnitude less as well. This can significantly
11376 reduce the complexity of developing of a grammar. @xref{%define
11377 Summary,,lr.type}.
11378
11379 @item Infix operator
11380 An arithmetic operator that is placed between the operands on which it
11381 performs some operation.
11382
11383 @item Input stream
11384 A continuous flow of data between devices or programs.
11385
11386 @item LAC (Lookahead Correction)
11387 A parsing mechanism that fixes the problem of delayed syntax error
11388 detection, which is caused by LR state merging, default reductions,
11389 and the use of @code{%nonassoc}. Delayed syntax error detection
11390 results in unexpected semantic actions, initiation of error recovery
11391 in the wrong syntactic context, and an incorrect list of expected
11392 tokens in a verbose syntax error message. @xref{%define
11393 Summary,,parse.lac}.
11394
11395 @item Language construct
11396 One of the typical usage schemas of the language. For example, one of
11397 the constructs of the C language is the @code{if} statement.
11398 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11399
11400 @item Left associativity
11401 Operators having left associativity are analyzed from left to right:
11402 @samp{a+b+c} first computes @samp{a+b} and then combines with
11403 @samp{c}. @xref{Precedence, ,Operator Precedence}.
11404
11405 @item Left recursion
11406 A rule whose result symbol is also its first component symbol; for
11407 example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
11408 Rules}.
11409
11410 @item Left-to-right parsing
11411 Parsing a sentence of a language by analyzing it token by token from
11412 left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
11413
11414 @item Lexical analyzer (scanner)
11415 A function that reads an input stream and returns tokens one by one.
11416 @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
11417
11418 @item Lexical tie-in
11419 A flag, set by actions in the grammar rules, which alters the way
11420 tokens are parsed. @xref{Lexical Tie-ins}.
11421
11422 @item Literal string token
11423 A token which consists of two or more fixed characters. @xref{Symbols}.
11424
11425 @item Lookahead token
11426 A token already read but not yet shifted. @xref{Lookahead, ,Lookahead
11427 Tokens}.
11428
11429 @item LALR(1)
11430 The class of context-free grammars that Bison (like most other parser
11431 generators) can handle by default; a subset of LR(1).
11432 @xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
11433
11434 @item LR(1)
11435 The class of context-free grammars in which at most one token of
11436 lookahead is needed to disambiguate the parsing of any piece of input.
11437
11438 @item Nonterminal symbol
11439 A grammar symbol standing for a grammatical construct that can
11440 be expressed through rules in terms of smaller constructs; in other
11441 words, a construct that is not a token. @xref{Symbols}.
11442
11443 @item Parser
11444 A function that recognizes valid sentences of a language by analyzing
11445 the syntax structure of a set of tokens passed to it from a lexical
11446 analyzer.
11447
11448 @item Postfix operator
11449 An arithmetic operator that is placed after the operands upon which it
11450 performs some operation.
11451
11452 @item Reduction
11453 Replacing a string of nonterminals and/or terminals with a single
11454 nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
11455 Parser Algorithm}.
11456
11457 @item Reentrant
11458 A reentrant subprogram is a subprogram which can be in invoked any
11459 number of times in parallel, without interference between the various
11460 invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
11461
11462 @item Reverse polish notation
11463 A language in which all operators are postfix operators.
11464
11465 @item Right recursion
11466 A rule whose result symbol is also its last component symbol; for
11467 example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
11468 Rules}.
11469
11470 @item Semantics
11471 In computer languages, the semantics are specified by the actions
11472 taken for each instance of the language, i.e., the meaning of
11473 each statement. @xref{Semantics, ,Defining Language Semantics}.
11474
11475 @item Shift
11476 A parser is said to shift when it makes the choice of analyzing
11477 further input from the stream rather than reducing immediately some
11478 already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
11479
11480 @item Single-character literal
11481 A single character that is recognized and interpreted as is.
11482 @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
11483
11484 @item Start symbol
11485 The nonterminal symbol that stands for a complete valid utterance in
11486 the language being parsed. The start symbol is usually listed as the
11487 first nonterminal symbol in a language specification.
11488 @xref{Start Decl, ,The Start-Symbol}.
11489
11490 @item Symbol table
11491 A data structure where symbol names and associated data are stored
11492 during parsing to allow for recognition and use of existing
11493 information in repeated uses of a symbol. @xref{Multi-function Calc}.
11494
11495 @item Syntax error
11496 An error encountered during parsing of an input stream due to invalid
11497 syntax. @xref{Error Recovery}.
11498
11499 @item Token
11500 A basic, grammatically indivisible unit of a language. The symbol
11501 that describes a token in the grammar is a terminal symbol.
11502 The input of the Bison parser is a stream of tokens which comes from
11503 the lexical analyzer. @xref{Symbols}.
11504
11505 @item Terminal symbol
11506 A grammar symbol that has no rules in the grammar and therefore is
11507 grammatically indivisible. The piece of text it represents is a token.
11508 @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11509 @end table
11510
11511 @node Copying This Manual
11512 @appendix Copying This Manual
11513 @include fdl.texi
11514
11515 @node Bibliography
11516 @unnumbered Bibliography
11517
11518 @table @asis
11519 @item [Denny 2008]
11520 Joel E. Denny and Brian A. Malloy, IELR(1): Practical LR(1) Parser Tables
11521 for Non-LR(1) Grammars with Conflict Resolution, in @cite{Proceedings of the
11522 2008 ACM Symposium on Applied Computing} (SAC'08), ACM, New York, NY, USA,
11523 pp.@: 240--245. @uref{http://dx.doi.org/10.1145/1363686.1363747}
11524
11525 @item [Denny 2010 May]
11526 Joel E. Denny, PSLR(1): Pseudo-Scannerless Minimal LR(1) for the
11527 Deterministic Parsing of Composite Languages, Ph.D. Dissertation, Clemson
11528 University, Clemson, SC, USA (May 2010).
11529 @uref{http://proquest.umi.com/pqdlink?did=2041473591&Fmt=7&clientId=79356&RQT=309&VName=PQD}
11530
11531 @item [Denny 2010 November]
11532 Joel E. Denny and Brian A. Malloy, The IELR(1) Algorithm for Generating
11533 Minimal LR(1) Parser Tables for Non-LR(1) Grammars with Conflict Resolution,
11534 in @cite{Science of Computer Programming}, Vol.@: 75, Issue 11 (November
11535 2010), pp.@: 943--979. @uref{http://dx.doi.org/10.1016/j.scico.2009.08.001}
11536
11537 @item [DeRemer 1982]
11538 Frank DeRemer and Thomas Pennello, Efficient Computation of LALR(1)
11539 Look-Ahead Sets, in @cite{ACM Transactions on Programming Languages and
11540 Systems}, Vol.@: 4, No.@: 4 (October 1982), pp.@:
11541 615--649. @uref{http://dx.doi.org/10.1145/69622.357187}
11542
11543 @item [Knuth 1965]
11544 Donald E. Knuth, On the Translation of Languages from Left to Right, in
11545 @cite{Information and Control}, Vol.@: 8, Issue 6 (December 1965), pp.@:
11546 607--639. @uref{http://dx.doi.org/10.1016/S0019-9958(65)90426-2}
11547
11548 @item [Scott 2000]
11549 Elizabeth Scott, Adrian Johnstone, and Shamsa Sadaf Hussain,
11550 @cite{Tomita-Style Generalised LR Parsers}, Royal Holloway, University of
11551 London, Department of Computer Science, TR-00-12 (December 2000).
11552 @uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps}
11553 @end table
11554
11555 @node Index
11556 @unnumbered Index
11557
11558 @printindex cp
11559
11560 @bye
11561
11562 @c LocalWords: texinfo setfilename settitle setchapternewpage finalout texi FSF
11563 @c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex FSF's
11564 @c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry Naur
11565 @c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa Multi
11566 @c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc multi
11567 @c LocalWords: rpcalc Lexer Expr ltcalc mfcalc yylex defaultprec Donnelly Gotos
11568 @c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref yypush
11569 @c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex lr
11570 @c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init stmtMerge POSIX
11571 @c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG yypull
11572 @c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit nonfree
11573 @c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok rr
11574 @c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln Stallman Destructor
11575 @c LocalWords: smallexample symrec val tptr FNCT fnctptr func struct sym enum
11576 @c LocalWords: fnct putsym getsym fname arith fncts atan ptr malloc sizeof Lex
11577 @c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum DOTDOT
11578 @c LocalWords: ptypes itype YYPRINT trigraphs yytname expseq vindex dtype Unary
11579 @c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs nonterminal
11580 @c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES reentrant
11581 @c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param yypstate
11582 @c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP subrange
11583 @c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword loc
11584 @c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH inline
11585 @c LocalWords: YYINITDEPTH stmnts ref stmnt initdcl maybeasm notype Lookahead
11586 @c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args Autoconf
11587 @c LocalWords: infile ypp yxx outfile itemx tex leaderfill Troubleshouting sqrt
11588 @c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll lookahead
11589 @c LocalWords: nbar yytext fst snd osplit ntwo strdup AST Troublereporting th
11590 @c LocalWords: YYSTACK DVI fdl printindex IELR nondeterministic nonterminals ps
11591 @c LocalWords: subexpressions declarator nondeferred config libintl postfix LAC
11592 @c LocalWords: preprocessor nonpositive unary nonnumeric typedef extern rhs
11593 @c LocalWords: yytokentype destructor multicharacter nonnull EBCDIC
11594 @c LocalWords: lvalue nonnegative XNUM CHR chr TAGLESS tagless stdout api TOK
11595 @c LocalWords: destructors Reentrancy nonreentrant subgrammar nonassociative
11596 @c LocalWords: deffnx namespace xml goto lalr ielr runtime lex yacc yyps env
11597 @c LocalWords: yystate variadic Unshift NLS gettext po UTF Automake LOCALEDIR
11598 @c LocalWords: YYENABLE bindtextdomain Makefile DEFS CPPFLAGS DBISON DeRemer
11599 @c LocalWords: autoreconf Pennello multisets nondeterminism Generalised baz
11600 @c LocalWords: redeclare automata Dparse localedir datadir XSLT midrule Wno
11601 @c LocalWords: Graphviz multitable headitem hh basename Doxygen fno
11602 @c LocalWords: doxygen ival sval deftypemethod deallocate pos deftypemethodx
11603 @c LocalWords: Ctor defcv defcvx arg accessors arithmetics CPP ifndef CALCXX
11604 @c LocalWords: lexer's calcxx bool LPAREN RPAREN deallocation cerrno climits
11605 @c LocalWords: cstdlib Debian undef yywrap unput noyywrap nounput zA yyleng
11606 @c LocalWords: errno strtol ERANGE str strerror iostream argc argv Javadoc
11607 @c LocalWords: bytecode initializers superclass stype ASTNode autoboxing nls
11608 @c LocalWords: toString deftypeivar deftypeivarx deftypeop YYParser strictfp
11609 @c LocalWords: superclasses boolean getErrorVerbose setErrorVerbose deftypecv
11610 @c LocalWords: getDebugStream setDebugStream getDebugLevel setDebugLevel url
11611 @c LocalWords: bisonVersion deftypecvx bisonSkeleton getStartPos getEndPos
11612 @c LocalWords: getLVal defvar deftypefn deftypefnx gotos msgfmt Corbett
11613 @c LocalWords: subdirectory Solaris nonassociativity
11614
11615 @c Local Variables:
11616 @c ispell-dictionary: "american"
11617 @c fill-column: 76
11618 @c End: