]> git.saurik.com Git - bison.git/blame - doc/bison.texinfo
doc: clean up naming of various Bison files.
[bison.git] / doc / bison.texinfo
CommitLineData
bfa74976
RS
1\input texinfo @c -*-texinfo-*-
2@comment %**start of header
3@setfilename bison.info
df1af54c
JT
4@include version.texi
5@settitle Bison @value{VERSION}
bfa74976
RS
6@setchapternewpage odd
7
5378c3e7 8@finalout
5378c3e7 9
13863333 10@c SMALL BOOK version
bfa74976 11@c This edition has been formatted so that you can format and print it in
13863333 12@c the smallbook format.
bfa74976
RS
13@c @smallbook
14
91d2c560
PE
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
8c5b881d 19@ifnotinfo
bfa74976
RS
20@syncodeindex fn cp
21@syncodeindex vr cp
22@syncodeindex tp cp
8c5b881d 23@end ifnotinfo
bfa74976
RS
24@ifinfo
25@synindex fn cp
26@synindex vr cp
27@synindex tp cp
28@end ifinfo
29@comment %**end of header
30
fae437e8 31@copying
bd773d73 32
8a4281b9
JD
33This manual (@value{UPDATED}) is for GNU Bison (version
34@value{VERSION}), the GNU parser generator.
fae437e8 35
575619af
JD
36Copyright @copyright{} 1988-1993, 1995, 1998-2011 Free Software
37Foundation, Inc.
fae437e8
AD
38
39@quotation
40Permission is granted to copy, distribute and/or modify this document
8a4281b9 41under the terms of the GNU Free Documentation License,
804e83b2 42Version 1.3 or any later version published by the Free Software
c827f760 43Foundation; with no Invariant Sections, with the Front-Cover texts
8a4281b9 44being ``A GNU Manual,'' and with the Back-Cover Texts as in
c827f760 45(a) below. A copy of the license is included in the section entitled
8a4281b9 46``GNU Free Documentation License.''
c827f760 47
389c8cfd 48(a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
8a4281b9
JD
49modify this GNU manual. Buying copies from the FSF
50supports it in developing GNU and promoting software
389c8cfd 51freedom.''
fae437e8
AD
52@end quotation
53@end copying
54
e62f1a89 55@dircategory Software development
fae437e8 56@direntry
8a4281b9 57* bison: (bison). GNU parser generator (Yacc replacement).
fae437e8 58@end direntry
bfa74976 59
bfa74976
RS
60@titlepage
61@title Bison
c827f760 62@subtitle The Yacc-compatible Parser Generator
df1af54c 63@subtitle @value{UPDATED}, Bison Version @value{VERSION}
bfa74976
RS
64
65@author by Charles Donnelly and Richard Stallman
66
67@page
68@vskip 0pt plus 1filll
fae437e8 69@insertcopying
bfa74976
RS
70@sp 2
71Published by the Free Software Foundation @*
0fb669f9
PE
7251 Franklin Street, Fifth Floor @*
73Boston, MA 02110-1301 USA @*
9ecbd125 74Printed copies are available from the Free Software Foundation.@*
8a4281b9 75ISBN 1-882114-44-2
bfa74976
RS
76@sp 2
77Cover art by Etienne Suvasa.
78@end titlepage
d5796688
JT
79
80@contents
bfa74976 81
342b8b6e
AD
82@ifnottex
83@node Top
84@top Bison
fae437e8 85@insertcopying
342b8b6e 86@end ifnottex
bfa74976
RS
87
88@menu
13863333
AD
89* Introduction::
90* Conditions::
8a4281b9 91* Copying:: The GNU General Public License says
f5f419de 92 how you can copy and share Bison.
bfa74976
RS
93
94Tutorial sections:
f5f419de
DJ
95* Concepts:: Basic concepts for understanding Bison.
96* Examples:: Three simple explained examples of using Bison.
bfa74976
RS
97
98Reference sections:
f5f419de
DJ
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.
bfa74976 103* Context Dependency:: What to do if your language syntax is too
f5f419de
DJ
104 messy for Bison to handle straightforwardly.
105* Debugging:: Understanding or debugging Bison parsers.
ff7571c0 106* Invocation:: How to run Bison (to produce the parser implementation).
f5f419de
DJ
107* Other Languages:: Creating C++ and Java parsers.
108* FAQ:: Frequently Asked Questions
109* Table of Symbols:: All the keywords of the Bison language are explained.
110* Glossary:: Basic concepts are explained.
111* Copying This Manual:: License for copying this manual.
112* Index:: Cross-references to the text.
bfa74976 113
93dd49ab
PE
114@detailmenu
115 --- The Detailed Node Listing ---
bfa74976
RS
116
117The Concepts of Bison
118
f5f419de
DJ
119* Language and Grammar:: Languages and context-free grammars,
120 as mathematical ideas.
121* Grammar in Bison:: How we represent grammars for Bison's sake.
122* Semantic Values:: Each token or syntactic grouping can have
123 a semantic value (the value of an integer,
124 the name of an identifier, etc.).
125* Semantic Actions:: Each rule can have an action containing C code.
126* GLR Parsers:: Writing parsers for general context-free languages.
127* Locations Overview:: Tracking Locations.
128* Bison Parser:: What are Bison's input and output,
129 how is the output used?
130* Stages:: Stages in writing and running Bison grammars.
131* Grammar Layout:: Overall structure of a Bison grammar file.
bfa74976 132
8a4281b9 133Writing GLR Parsers
fa7e68c3 134
8a4281b9
JD
135* Simple GLR Parsers:: Using GLR parsers on unambiguous grammars.
136* Merging GLR Parses:: Using GLR parsers to resolve ambiguities.
20be2f92 137* GLR Semantic Actions:: Considerations for semantic values and deferred actions.
ca2a6d15 138* Semantic Predicates:: Controlling a parse with arbitrary computations.
8a4281b9 139* Compiler Requirements:: GLR parsers require a modern C compiler.
fa7e68c3 140
bfa74976
RS
141Examples
142
f5f419de
DJ
143* RPN Calc:: Reverse polish notation calculator;
144 a first example with no operator precedence.
145* Infix Calc:: Infix (algebraic) notation calculator.
146 Operator precedence is introduced.
bfa74976 147* Simple Error Recovery:: Continuing after syntax errors.
342b8b6e 148* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
f5f419de
DJ
149* Multi-function Calc:: Calculator with memory and trig functions.
150 It uses multiple data-types for semantic values.
151* Exercises:: Ideas for improving the multi-function calculator.
bfa74976
RS
152
153Reverse Polish Notation Calculator
154
f5f419de
DJ
155* Rpcalc Declarations:: Prologue (declarations) for rpcalc.
156* Rpcalc Rules:: Grammar Rules for rpcalc, with explanation.
157* Rpcalc Lexer:: The lexical analyzer.
158* Rpcalc Main:: The controlling function.
159* Rpcalc Error:: The error reporting function.
160* Rpcalc Generate:: Running Bison on the grammar file.
161* Rpcalc Compile:: Run the C compiler on the output code.
bfa74976
RS
162
163Grammar Rules for @code{rpcalc}
164
13863333
AD
165* Rpcalc Input::
166* Rpcalc Line::
167* Rpcalc Expr::
bfa74976 168
342b8b6e
AD
169Location Tracking Calculator: @code{ltcalc}
170
f5f419de
DJ
171* Ltcalc Declarations:: Bison and C declarations for ltcalc.
172* Ltcalc Rules:: Grammar rules for ltcalc, with explanations.
173* Ltcalc Lexer:: The lexical analyzer.
342b8b6e 174
bfa74976
RS
175Multi-Function Calculator: @code{mfcalc}
176
f5f419de
DJ
177* Mfcalc Declarations:: Bison declarations for multi-function calculator.
178* Mfcalc Rules:: Grammar rules for the calculator.
179* Mfcalc Symbol Table:: Symbol table management subroutines.
bfa74976
RS
180
181Bison Grammar Files
182
183* Grammar Outline:: Overall layout of the grammar file.
184* Symbols:: Terminal and nonterminal symbols.
185* Rules:: How to write grammar rules.
186* Recursion:: Writing recursive rules.
187* Semantics:: Semantic values and actions.
93dd49ab 188* Locations:: Locations and actions.
bfa74976
RS
189* Declarations:: All kinds of Bison declarations are described here.
190* Multiple Parsers:: Putting more than one Bison parser in one program.
191
192Outline of a Bison Grammar
193
f5f419de 194* Prologue:: Syntax and usage of the prologue.
2cbe6b7f 195* Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
f5f419de
DJ
196* Bison Declarations:: Syntax and usage of the Bison declarations section.
197* Grammar Rules:: Syntax and usage of the grammar rules section.
198* Epilogue:: Syntax and usage of the epilogue.
bfa74976
RS
199
200Defining Language Semantics
201
202* Value Type:: Specifying one data type for all semantic values.
203* Multiple Types:: Specifying several alternative data types.
204* Actions:: An action is the semantic definition of a grammar rule.
205* Action Types:: Specifying data types for actions to operate on.
206* Mid-Rule Actions:: Most actions go at the end of a rule.
207 This says when, why and how to use the exceptional
208 action in the middle of a rule.
d013372c 209* Named References:: Using named references in actions.
bfa74976 210
93dd49ab
PE
211Tracking Locations
212
213* Location Type:: Specifying a data type for locations.
214* Actions and Locations:: Using locations in actions.
215* Location Default Action:: Defining a general way to compute locations.
216
bfa74976
RS
217Bison Declarations
218
b50d2359 219* Require Decl:: Requiring a Bison version.
bfa74976
RS
220* Token Decl:: Declaring terminal symbols.
221* Precedence Decl:: Declaring terminals with precedence and associativity.
222* Union Decl:: Declaring the set of all semantic value types.
223* Type Decl:: Declaring the choice of type for a nonterminal symbol.
18d192f0 224* Initial Action Decl:: Code run before parsing starts.
72f889cc 225* Destructor Decl:: Declaring how symbols are freed.
d6328241 226* Expect Decl:: Suppressing warnings about parsing conflicts.
bfa74976
RS
227* Start Decl:: Specifying the start symbol.
228* Pure Decl:: Requesting a reentrant parser.
9987d1b3 229* Push Decl:: Requesting a push parser.
bfa74976
RS
230* Decl Summary:: Table of all Bison declarations.
231
232Parser C-Language Interface
233
f5f419de
DJ
234* Parser Function:: How to call @code{yyparse} and what it returns.
235* Push Parser Function:: How to call @code{yypush_parse} and what it returns.
236* Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
237* Parser Create Function:: How to call @code{yypstate_new} and what it returns.
238* Parser Delete Function:: How to call @code{yypstate_delete} and what it returns.
239* Lexical:: You must supply a function @code{yylex}
240 which reads tokens.
241* Error Reporting:: You must supply a function @code{yyerror}.
242* Action Features:: Special features for use in actions.
243* Internationalization:: How to let the parser speak in the user's
244 native language.
bfa74976
RS
245
246The Lexical Analyzer Function @code{yylex}
247
248* Calling Convention:: How @code{yyparse} calls @code{yylex}.
f5f419de
DJ
249* Token Values:: How @code{yylex} must return the semantic value
250 of the token it has read.
251* Token Locations:: How @code{yylex} must return the text location
252 (line number, etc.) of the token, if the
253 actions want that.
254* Pure Calling:: How the calling convention differs in a pure parser
255 (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
bfa74976 256
13863333 257The Bison Parser Algorithm
bfa74976 258
742e4900 259* Lookahead:: Parser looks one token ahead when deciding what to do.
bfa74976
RS
260* Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
261* Precedence:: Operator precedence works by resolving conflicts.
262* Contextual Precedence:: When an operator's precedence depends on context.
263* Parser States:: The parser is a finite-state-machine with stack.
264* Reduce/Reduce:: When two rules are applicable in the same situation.
f5f419de 265* Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
676385e2 266* Generalized LR Parsing:: Parsing arbitrary context-free grammars.
1a059451 267* Memory Management:: What happens when memory is exhausted. How to avoid it.
bfa74976
RS
268
269Operator Precedence
270
271* Why Precedence:: An example showing why precedence is needed.
d78f0ac9
AD
272* Using Precedence:: How to specify precedence and associativity.
273* Precedence Only:: How to specify precedence only.
bfa74976
RS
274* Precedence Examples:: How these features are used in the previous example.
275* How Precedence:: How they work.
276
277Handling Context Dependencies
278
279* Semantic Tokens:: Token parsing can depend on the semantic context.
280* Lexical Tie-ins:: Token parsing can depend on the syntactic context.
281* Tie-in Recovery:: Lexical tie-ins have implications for how
282 error recovery rules must be written.
283
93dd49ab 284Debugging Your Parser
ec3bc396
AD
285
286* Understanding:: Understanding the structure of your parser.
287* Tracing:: Tracing the execution of your parser.
288
bfa74976
RS
289Invoking Bison
290
13863333 291* Bison Options:: All the options described in detail,
c827f760 292 in alphabetical order by short options.
bfa74976 293* Option Cross Key:: Alphabetical list of long options.
93dd49ab 294* Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
f2b5126e 295
8405b70c 296Parsers Written In Other Languages
12545799
AD
297
298* C++ Parsers:: The interface to generate C++ parser classes
8405b70c 299* Java Parsers:: The interface to generate Java parser classes
12545799
AD
300
301C++ Parsers
302
303* C++ Bison Interface:: Asking for C++ parser generation
304* C++ Semantic Values:: %union vs. C++
305* C++ Location Values:: The position and location classes
306* C++ Parser Interface:: Instantiating and running the parser
307* C++ Scanner Interface:: Exchanges between yylex and parse
8405b70c 308* A Complete C++ Example:: Demonstrating their use
12545799
AD
309
310A Complete C++ Example
311
312* Calc++ --- C++ Calculator:: The specifications
313* Calc++ Parsing Driver:: An active parsing context
314* Calc++ Parser:: A parser class
315* Calc++ Scanner:: A pure C++ Flex scanner
316* Calc++ Top Level:: Conducting the band
317
8405b70c
PB
318Java Parsers
319
f5f419de
DJ
320* Java Bison Interface:: Asking for Java parser generation
321* Java Semantic Values:: %type and %token vs. Java
322* Java Location Values:: The position and location classes
323* Java Parser Interface:: Instantiating and running the parser
324* Java Scanner Interface:: Specifying the scanner for the parser
325* Java Action Features:: Special features for use in actions
326* Java Differences:: Differences between C/C++ and Java Grammars
327* Java Declarations Summary:: List of Bison declarations used with Java
8405b70c 328
d1a1114f
AD
329Frequently Asked Questions
330
f5f419de
DJ
331* Memory Exhausted:: Breaking the Stack Limits
332* How Can I Reset the Parser:: @code{yyparse} Keeps some State
333* Strings are Destroyed:: @code{yylval} Loses Track of Strings
334* Implementing Gotos/Loops:: Control Flow in the Calculator
335* Multiple start-symbols:: Factoring closely related grammars
8a4281b9 336* Secure? Conform?:: Is Bison POSIX safe?
f5f419de
DJ
337* I can't build Bison:: Troubleshooting
338* Where can I find help?:: Troubleshouting
339* Bug Reports:: Troublereporting
340* More Languages:: Parsers in C++, Java, and so on
341* Beta Testing:: Experimenting development versions
342* Mailing Lists:: Meeting other Bison users
d1a1114f 343
f2b5126e
PB
344Copying This Manual
345
f5f419de 346* Copying This Manual:: License for copying this manual.
f2b5126e 347
342b8b6e 348@end detailmenu
bfa74976
RS
349@end menu
350
342b8b6e 351@node Introduction
bfa74976
RS
352@unnumbered Introduction
353@cindex introduction
354
6077da58 355@dfn{Bison} is a general-purpose parser generator that converts an
af28d414
JD
356annotated context-free grammar into a deterministic LR or generalized
357LR (GLR) parser employing LALR(1) parser tables. As an experimental
358feature, Bison can also generate IELR(1) or canonical LR(1) parser
359tables. Once you are proficient with Bison, you can use it to develop
360a wide range of language parsers, from those used in simple desk
361calculators to complex programming languages.
362
363Bison is upward compatible with Yacc: all properly-written Yacc
364grammars ought to work with Bison with no change. Anyone familiar
365with Yacc should be able to use Bison with little trouble. You need
366to be fluent in C or C++ programming in order to use Bison or to
367understand this manual. Java is also supported as an experimental
368feature.
369
370We begin with tutorial chapters that explain the basic concepts of
371using Bison and show three explained examples, each building on the
372last. If you don't know Bison or Yacc, start by reading these
373chapters. Reference chapters follow, which describe specific aspects
374of Bison in detail.
bfa74976 375
679e9935
JD
376Bison was written originally by Robert Corbett. Richard Stallman made
377it Yacc-compatible. Wilfred Hansen of Carnegie Mellon University
378added multi-character string literals and other features. Since then,
379Bison has grown more robust and evolved many other new features thanks
380to the hard work of a long list of volunteers. For details, see the
381@file{THANKS} and @file{ChangeLog} files included in the Bison
382distribution.
931c7513 383
df1af54c 384This edition corresponds to version @value{VERSION} of Bison.
bfa74976 385
342b8b6e 386@node Conditions
bfa74976
RS
387@unnumbered Conditions for Using Bison
388
193d7c70
PE
389The distribution terms for Bison-generated parsers permit using the
390parsers in nonfree programs. Before Bison version 2.2, these extra
8a4281b9 391permissions applied only when Bison was generating LALR(1)
193d7c70 392parsers in C@. And before Bison version 1.24, Bison-generated
262aa8dd 393parsers could be used only in programs that were free software.
a31239f1 394
8a4281b9 395The other GNU programming tools, such as the GNU C
c827f760 396compiler, have never
9ecbd125 397had such a requirement. They could always be used for nonfree
a31239f1
RS
398software. The reason Bison was different was not due to a special
399policy decision; it resulted from applying the usual General Public
400License to all of the Bison source code.
401
ff7571c0
JD
402The main output of the Bison utility---the Bison parser implementation
403file---contains a verbatim copy of a sizable piece of Bison, which is
404the code for the parser's implementation. (The actions from your
405grammar are inserted into this implementation at one point, but most
406of the rest of the implementation is not changed.) When we applied
407the GPL terms to the skeleton code for the parser's implementation,
a31239f1
RS
408the effect was to restrict the use of Bison output to free software.
409
410We didn't change the terms because of sympathy for people who want to
411make software proprietary. @strong{Software should be free.} But we
412concluded that limiting Bison's use to free software was doing little to
413encourage people to make other software free. So we decided to make the
414practical conditions for using Bison match the practical conditions for
8a4281b9 415using the other GNU tools.
bfa74976 416
193d7c70
PE
417This exception applies when Bison is generating code for a parser.
418You can tell whether the exception applies to a Bison output file by
419inspecting the file for text beginning with ``As a special
420exception@dots{}''. The text spells out the exact terms of the
421exception.
262aa8dd 422
f16b0819
PE
423@node Copying
424@unnumbered GNU GENERAL PUBLIC LICENSE
425@include gpl-3.0.texi
bfa74976 426
342b8b6e 427@node Concepts
bfa74976
RS
428@chapter The Concepts of Bison
429
430This chapter introduces many of the basic concepts without which the
431details of Bison will not make sense. If you do not already know how to
432use Bison or Yacc, we suggest you start by reading this chapter carefully.
433
434@menu
f5f419de
DJ
435* Language and Grammar:: Languages and context-free grammars,
436 as mathematical ideas.
437* Grammar in Bison:: How we represent grammars for Bison's sake.
438* Semantic Values:: Each token or syntactic grouping can have
439 a semantic value (the value of an integer,
440 the name of an identifier, etc.).
441* Semantic Actions:: Each rule can have an action containing C code.
442* GLR Parsers:: Writing parsers for general context-free languages.
443* Locations Overview:: Tracking Locations.
444* Bison Parser:: What are Bison's input and output,
445 how is the output used?
446* Stages:: Stages in writing and running Bison grammars.
447* Grammar Layout:: Overall structure of a Bison grammar file.
bfa74976
RS
448@end menu
449
342b8b6e 450@node Language and Grammar
bfa74976
RS
451@section Languages and Context-Free Grammars
452
bfa74976
RS
453@cindex context-free grammar
454@cindex grammar, context-free
455In order for Bison to parse a language, it must be described by a
456@dfn{context-free grammar}. This means that you specify one or more
457@dfn{syntactic groupings} and give rules for constructing them from their
458parts. For example, in the C language, one kind of grouping is called an
459`expression'. One rule for making an expression might be, ``An expression
460can be made of a minus sign and another expression''. Another would be,
461``An expression can be an integer''. As you can see, rules are often
462recursive, but there must be at least one rule which leads out of the
463recursion.
464
8a4281b9 465@cindex BNF
bfa74976
RS
466@cindex Backus-Naur form
467The most common formal system for presenting such rules for humans to read
8a4281b9 468is @dfn{Backus-Naur Form} or ``BNF'', which was developed in
c827f760 469order to specify the language Algol 60. Any grammar expressed in
8a4281b9
JD
470BNF is a context-free grammar. The input to Bison is
471essentially machine-readable BNF.
bfa74976 472
8a4281b9
JD
473@cindex LALR(1) grammars
474@cindex IELR(1) grammars
475@cindex LR(1) grammars
eb45ef3b
JD
476There are various important subclasses of context-free grammars.
477Although it can handle almost all context-free grammars, Bison is
8a4281b9 478optimized for what are called LR(1) grammars.
eb45ef3b
JD
479In brief, in these grammars, it must be possible to tell how to parse
480any portion of an input string with just a single token of lookahead.
481For historical reasons, Bison by default is limited by the additional
8a4281b9 482restrictions of LALR(1), which is hard to explain simply.
c827f760
PE
483@xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}, for
484more information on this.
f1b238df 485As an experimental feature, you can escape these additional restrictions by
8a4281b9 486requesting IELR(1) or canonical LR(1) parser tables.
eb45ef3b 487@xref{Decl Summary,,lr.type}, to learn how.
bfa74976 488
8a4281b9
JD
489@cindex GLR parsing
490@cindex generalized LR (GLR) parsing
676385e2 491@cindex ambiguous grammars
9d9b8b70 492@cindex nondeterministic parsing
9501dc6e 493
8a4281b9 494Parsers for LR(1) grammars are @dfn{deterministic}, meaning
9501dc6e
AD
495roughly that the next grammar rule to apply at any point in the input is
496uniquely determined by the preceding input and a fixed, finite portion
742e4900 497(called a @dfn{lookahead}) of the remaining input. A context-free
9501dc6e 498grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
e4f85c39 499apply the grammar rules to get the same inputs. Even unambiguous
9d9b8b70 500grammars can be @dfn{nondeterministic}, meaning that no fixed
742e4900 501lookahead always suffices to determine the next grammar rule to apply.
9501dc6e 502With the proper declarations, Bison is also able to parse these more
8a4281b9
JD
503general context-free grammars, using a technique known as GLR
504parsing (for Generalized LR). Bison's GLR parsers
9501dc6e
AD
505are able to handle any context-free grammar for which the number of
506possible parses of any given string is finite.
676385e2 507
bfa74976
RS
508@cindex symbols (abstract)
509@cindex token
510@cindex syntactic grouping
511@cindex grouping, syntactic
9501dc6e
AD
512In the formal grammatical rules for a language, each kind of syntactic
513unit or grouping is named by a @dfn{symbol}. Those which are built by
514grouping smaller constructs according to grammatical rules are called
bfa74976
RS
515@dfn{nonterminal symbols}; those which can't be subdivided are called
516@dfn{terminal symbols} or @dfn{token types}. We call a piece of input
517corresponding to a single terminal symbol a @dfn{token}, and a piece
e0c471a9 518corresponding to a single nonterminal symbol a @dfn{grouping}.
bfa74976
RS
519
520We can use the C language as an example of what symbols, terminal and
9501dc6e
AD
521nonterminal, mean. The tokens of C are identifiers, constants (numeric
522and string), and the various keywords, arithmetic operators and
523punctuation marks. So the terminal symbols of a grammar for C include
524`identifier', `number', `string', plus one symbol for each keyword,
525operator or punctuation mark: `if', `return', `const', `static', `int',
526`char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
527(These tokens can be subdivided into characters, but that is a matter of
bfa74976
RS
528lexicography, not grammar.)
529
530Here is a simple C function subdivided into tokens:
531
9edcd895
AD
532@ifinfo
533@example
534int /* @r{keyword `int'} */
14d4662b 535square (int x) /* @r{identifier, open-paren, keyword `int',}
9edcd895
AD
536 @r{identifier, close-paren} */
537@{ /* @r{open-brace} */
aa08666d
AD
538 return x * x; /* @r{keyword `return', identifier, asterisk,}
539 @r{identifier, semicolon} */
9edcd895
AD
540@} /* @r{close-brace} */
541@end example
542@end ifinfo
543@ifnotinfo
bfa74976
RS
544@example
545int /* @r{keyword `int'} */
14d4662b 546square (int x) /* @r{identifier, open-paren, keyword `int', identifier, close-paren} */
bfa74976 547@{ /* @r{open-brace} */
9edcd895 548 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
bfa74976
RS
549@} /* @r{close-brace} */
550@end example
9edcd895 551@end ifnotinfo
bfa74976
RS
552
553The syntactic groupings of C include the expression, the statement, the
554declaration, and the function definition. These are represented in the
555grammar of C by nonterminal symbols `expression', `statement',
556`declaration' and `function definition'. The full grammar uses dozens of
557additional language constructs, each with its own nonterminal symbol, in
558order to express the meanings of these four. The example above is a
559function definition; it contains one declaration, and one statement. In
560the statement, each @samp{x} is an expression and so is @samp{x * x}.
561
562Each nonterminal symbol must have grammatical rules showing how it is made
563out of simpler constructs. For example, one kind of C statement is the
564@code{return} statement; this would be described with a grammar rule which
565reads informally as follows:
566
567@quotation
568A `statement' can be made of a `return' keyword, an `expression' and a
569`semicolon'.
570@end quotation
571
572@noindent
573There would be many other rules for `statement', one for each kind of
574statement in C.
575
576@cindex start symbol
577One nonterminal symbol must be distinguished as the special one which
578defines a complete utterance in the language. It is called the @dfn{start
579symbol}. In a compiler, this means a complete input program. In the C
580language, the nonterminal symbol `sequence of definitions and declarations'
581plays this role.
582
583For example, @samp{1 + 2} is a valid C expression---a valid part of a C
584program---but it is not valid as an @emph{entire} C program. In the
585context-free grammar of C, this follows from the fact that `expression' is
586not the start symbol.
587
588The Bison parser reads a sequence of tokens as its input, and groups the
589tokens using the grammar rules. If the input is valid, the end result is
590that the entire token sequence reduces to a single grouping whose symbol is
591the grammar's start symbol. If we use a grammar for C, the entire input
592must be a `sequence of definitions and declarations'. If not, the parser
593reports a syntax error.
594
342b8b6e 595@node Grammar in Bison
bfa74976
RS
596@section From Formal Rules to Bison Input
597@cindex Bison grammar
598@cindex grammar, Bison
599@cindex formal grammar
600
601A formal grammar is a mathematical construct. To define the language
602for Bison, you must write a file expressing the grammar in Bison syntax:
603a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
604
605A nonterminal symbol in the formal grammar is represented in Bison input
c827f760 606as an identifier, like an identifier in C@. By convention, it should be
bfa74976
RS
607in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
608
609The Bison representation for a terminal symbol is also called a @dfn{token
610type}. Token types as well can be represented as C-like identifiers. By
611convention, these identifiers should be upper case to distinguish them from
612nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
613@code{RETURN}. A terminal symbol that stands for a particular keyword in
614the language should be named after that keyword converted to upper case.
615The terminal symbol @code{error} is reserved for error recovery.
931c7513 616@xref{Symbols}.
bfa74976
RS
617
618A terminal symbol can also be represented as a character literal, just like
619a C character constant. You should do this whenever a token is just a
620single character (parenthesis, plus-sign, etc.): use that same character in
621a literal as the terminal symbol for that token.
622
931c7513
RS
623A third way to represent a terminal symbol is with a C string constant
624containing several characters. @xref{Symbols}, for more information.
625
bfa74976
RS
626The grammar rules also have an expression in Bison syntax. For example,
627here is the Bison rule for a C @code{return} statement. The semicolon in
628quotes is a literal character token, representing part of the C syntax for
629the statement; the naked semicolon, and the colon, are Bison punctuation
630used in every rule.
631
632@example
633stmt: RETURN expr ';'
634 ;
635@end example
636
637@noindent
638@xref{Rules, ,Syntax of Grammar Rules}.
639
342b8b6e 640@node Semantic Values
bfa74976
RS
641@section Semantic Values
642@cindex semantic value
643@cindex value, semantic
644
645A formal grammar selects tokens only by their classifications: for example,
646if a rule mentions the terminal symbol `integer constant', it means that
647@emph{any} integer constant is grammatically valid in that position. The
648precise value of the constant is irrelevant to how to parse the input: if
649@samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
e0c471a9 650grammatical.
bfa74976
RS
651
652But the precise value is very important for what the input means once it is
653parsed. A compiler is useless if it fails to distinguish between 4, 1 and
6543989 as constants in the program! Therefore, each token in a Bison grammar
c827f760
PE
655has both a token type and a @dfn{semantic value}. @xref{Semantics,
656,Defining Language Semantics},
bfa74976
RS
657for details.
658
659The token type is a terminal symbol defined in the grammar, such as
660@code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
661you need to know to decide where the token may validly appear and how to
662group it with other tokens. The grammar rules know nothing about tokens
e0c471a9 663except their types.
bfa74976
RS
664
665The semantic value has all the rest of the information about the
666meaning of the token, such as the value of an integer, or the name of an
667identifier. (A token such as @code{','} which is just punctuation doesn't
668need to have any semantic value.)
669
670For example, an input token might be classified as token type
671@code{INTEGER} and have the semantic value 4. Another input token might
672have the same token type @code{INTEGER} but value 3989. When a grammar
673rule says that @code{INTEGER} is allowed, either of these tokens is
674acceptable because each is an @code{INTEGER}. When the parser accepts the
675token, it keeps track of the token's semantic value.
676
677Each grouping can also have a semantic value as well as its nonterminal
678symbol. For example, in a calculator, an expression typically has a
679semantic value that is a number. In a compiler for a programming
680language, an expression typically has a semantic value that is a tree
681structure describing the meaning of the expression.
682
342b8b6e 683@node Semantic Actions
bfa74976
RS
684@section Semantic Actions
685@cindex semantic actions
686@cindex actions, semantic
687
688In order to be useful, a program must do more than parse input; it must
689also produce some output based on the input. In a Bison grammar, a grammar
690rule can have an @dfn{action} made up of C statements. Each time the
691parser recognizes a match for that rule, the action is executed.
692@xref{Actions}.
13863333 693
bfa74976
RS
694Most of the time, the purpose of an action is to compute the semantic value
695of the whole construct from the semantic values of its parts. For example,
696suppose we have a rule which says an expression can be the sum of two
697expressions. When the parser recognizes such a sum, each of the
698subexpressions has a semantic value which describes how it was built up.
699The action for this rule should create a similar sort of value for the
700newly recognized larger expression.
701
702For example, here is a rule that says an expression can be the sum of
703two subexpressions:
704
705@example
706expr: expr '+' expr @{ $$ = $1 + $3; @}
707 ;
708@end example
709
710@noindent
711The action says how to produce the semantic value of the sum expression
712from the values of the two subexpressions.
713
676385e2 714@node GLR Parsers
8a4281b9
JD
715@section Writing GLR Parsers
716@cindex GLR parsing
717@cindex generalized LR (GLR) parsing
676385e2
PH
718@findex %glr-parser
719@cindex conflicts
720@cindex shift/reduce conflicts
fa7e68c3 721@cindex reduce/reduce conflicts
676385e2 722
eb45ef3b 723In some grammars, Bison's deterministic
8a4281b9 724LR(1) parsing algorithm cannot decide whether to apply a
9501dc6e
AD
725certain grammar rule at a given point. That is, it may not be able to
726decide (on the basis of the input read so far) which of two possible
727reductions (applications of a grammar rule) applies, or whether to apply
728a reduction or read more of the input and apply a reduction later in the
729input. These are known respectively as @dfn{reduce/reduce} conflicts
730(@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
731(@pxref{Shift/Reduce}).
732
8a4281b9 733To use a grammar that is not easily modified to be LR(1), a
9501dc6e 734more general parsing algorithm is sometimes necessary. If you include
676385e2 735@code{%glr-parser} among the Bison declarations in your file
8a4281b9
JD
736(@pxref{Grammar Outline}), the result is a Generalized LR
737(GLR) parser. These parsers handle Bison grammars that
9501dc6e 738contain no unresolved conflicts (i.e., after applying precedence
eb45ef3b 739declarations) identically to deterministic parsers. However, when
9501dc6e 740faced with unresolved shift/reduce and reduce/reduce conflicts,
8a4281b9 741GLR parsers use the simple expedient of doing both,
9501dc6e
AD
742effectively cloning the parser to follow both possibilities. Each of
743the resulting parsers can again split, so that at any given time, there
744can be any number of possible parses being explored. The parsers
676385e2
PH
745proceed in lockstep; that is, all of them consume (shift) a given input
746symbol before any of them proceed to the next. Each of the cloned
747parsers eventually meets one of two possible fates: either it runs into
748a parsing error, in which case it simply vanishes, or it merges with
749another parser, because the two of them have reduced the input to an
750identical set of symbols.
751
752During the time that there are multiple parsers, semantic actions are
753recorded, but not performed. When a parser disappears, its recorded
754semantic actions disappear as well, and are never performed. When a
755reduction makes two parsers identical, causing them to merge, Bison
756records both sets of semantic actions. Whenever the last two parsers
757merge, reverting to the single-parser case, Bison resolves all the
758outstanding actions either by precedences given to the grammar rules
759involved, or by performing both actions, and then calling a designated
760user-defined function on the resulting values to produce an arbitrary
761merged result.
762
fa7e68c3 763@menu
8a4281b9
JD
764* Simple GLR Parsers:: Using GLR parsers on unambiguous grammars.
765* Merging GLR Parses:: Using GLR parsers to resolve ambiguities.
20be2f92 766* GLR Semantic Actions:: Considerations for semantic values and deferred actions.
ca2a6d15 767* Semantic Predicates:: Controlling a parse with arbitrary computations.
8a4281b9 768* Compiler Requirements:: GLR parsers require a modern C compiler.
fa7e68c3
PE
769@end menu
770
771@node Simple GLR Parsers
8a4281b9
JD
772@subsection Using GLR on Unambiguous Grammars
773@cindex GLR parsing, unambiguous grammars
774@cindex generalized LR (GLR) parsing, unambiguous grammars
fa7e68c3
PE
775@findex %glr-parser
776@findex %expect-rr
777@cindex conflicts
778@cindex reduce/reduce conflicts
779@cindex shift/reduce conflicts
780
8a4281b9
JD
781In the simplest cases, you can use the GLR algorithm
782to parse grammars that are unambiguous but fail to be LR(1).
eb45ef3b 783Such grammars typically require more than one symbol of lookahead.
fa7e68c3
PE
784
785Consider a problem that
786arises in the declaration of enumerated and subrange types in the
787programming language Pascal. Here are some examples:
788
789@example
790type subrange = lo .. hi;
791type enum = (a, b, c);
792@end example
793
794@noindent
795The original language standard allows only numeric
796literals and constant identifiers for the subrange bounds (@samp{lo}
8a4281b9 797and @samp{hi}), but Extended Pascal (ISO/IEC
fa7e68c3
PE
79810206) and many other
799Pascal implementations allow arbitrary expressions there. This gives
800rise to the following situation, containing a superfluous pair of
801parentheses:
802
803@example
804type subrange = (a) .. b;
805@end example
806
807@noindent
808Compare this to the following declaration of an enumerated
809type with only one value:
810
811@example
812type enum = (a);
813@end example
814
815@noindent
816(These declarations are contrived, but they are syntactically
817valid, and more-complicated cases can come up in practical programs.)
818
819These two declarations look identical until the @samp{..} token.
8a4281b9 820With normal LR(1) one-token lookahead it is not
fa7e68c3
PE
821possible to decide between the two forms when the identifier
822@samp{a} is parsed. It is, however, desirable
823for a parser to decide this, since in the latter case
824@samp{a} must become a new identifier to represent the enumeration
825value, while in the former case @samp{a} must be evaluated with its
826current meaning, which may be a constant or even a function call.
827
828You could parse @samp{(a)} as an ``unspecified identifier in parentheses'',
829to be resolved later, but this typically requires substantial
830contortions in both semantic actions and large parts of the
831grammar, where the parentheses are nested in the recursive rules for
832expressions.
833
834You might think of using the lexer to distinguish between the two
835forms by returning different tokens for currently defined and
836undefined identifiers. But if these declarations occur in a local
837scope, and @samp{a} is defined in an outer scope, then both forms
838are possible---either locally redefining @samp{a}, or using the
839value of @samp{a} from the outer scope. So this approach cannot
840work.
841
e757bb10 842A simple solution to this problem is to declare the parser to
8a4281b9
JD
843use the GLR algorithm.
844When the GLR parser reaches the critical state, it
fa7e68c3
PE
845merely splits into two branches and pursues both syntax rules
846simultaneously. Sooner or later, one of them runs into a parsing
847error. If there is a @samp{..} token before the next
848@samp{;}, the rule for enumerated types fails since it cannot
849accept @samp{..} anywhere; otherwise, the subrange type rule
850fails since it requires a @samp{..} token. So one of the branches
851fails silently, and the other one continues normally, performing
852all the intermediate actions that were postponed during the split.
853
854If the input is syntactically incorrect, both branches fail and the parser
855reports a syntax error as usual.
856
857The effect of all this is that the parser seems to ``guess'' the
858correct branch to take, or in other words, it seems to use more
8a4281b9
JD
859lookahead than the underlying LR(1) algorithm actually allows
860for. In this example, LR(2) would suffice, but also some cases
861that are not LR(@math{k}) for any @math{k} can be handled this way.
fa7e68c3 862
8a4281b9 863In general, a GLR parser can take quadratic or cubic worst-case time,
fa7e68c3
PE
864and the current Bison parser even takes exponential time and space
865for some grammars. In practice, this rarely happens, and for many
866grammars it is possible to prove that it cannot happen.
867The present example contains only one conflict between two
868rules, and the type-declaration context containing the conflict
869cannot be nested. So the number of
870branches that can exist at any time is limited by the constant 2,
871and the parsing time is still linear.
872
873Here is a Bison grammar corresponding to the example above. It
874parses a vastly simplified form of Pascal type declarations.
875
876@example
877%token TYPE DOTDOT ID
878
879@group
880%left '+' '-'
881%left '*' '/'
882@end group
883
884%%
885
886@group
887type_decl : TYPE ID '=' type ';'
888 ;
889@end group
890
891@group
892type : '(' id_list ')'
893 | expr DOTDOT expr
894 ;
895@end group
896
897@group
898id_list : ID
899 | id_list ',' ID
900 ;
901@end group
902
903@group
904expr : '(' expr ')'
905 | expr '+' expr
906 | expr '-' expr
907 | expr '*' expr
908 | expr '/' expr
909 | ID
910 ;
911@end group
912@end example
913
8a4281b9 914When used as a normal LR(1) grammar, Bison correctly complains
fa7e68c3
PE
915about one reduce/reduce conflict. In the conflicting situation the
916parser chooses one of the alternatives, arbitrarily the one
917declared first. Therefore the following correct input is not
918recognized:
919
920@example
921type t = (a) .. b;
922@end example
923
8a4281b9 924The parser can be turned into a GLR parser, while also telling Bison
ff7571c0
JD
925to be silent about the one known reduce/reduce conflict, by adding
926these two declarations to the Bison grammar file (before the first
fa7e68c3
PE
927@samp{%%}):
928
929@example
930%glr-parser
931%expect-rr 1
932@end example
933
934@noindent
935No change in the grammar itself is required. Now the
936parser recognizes all valid declarations, according to the
937limited syntax above, transparently. In fact, the user does not even
938notice when the parser splits.
939
8a4281b9 940So here we have a case where we can use the benefits of GLR,
f8e1c9e5
AD
941almost without disadvantages. Even in simple cases like this, however,
942there are at least two potential problems to beware. First, always
8a4281b9
JD
943analyze the conflicts reported by Bison to make sure that GLR
944splitting is only done where it is intended. A GLR parser
f8e1c9e5 945splitting inadvertently may cause problems less obvious than an
8a4281b9 946LR parser statically choosing the wrong alternative in a
f8e1c9e5
AD
947conflict. Second, consider interactions with the lexer (@pxref{Semantic
948Tokens}) with great care. Since a split parser consumes tokens without
949performing any actions during the split, the lexer cannot obtain
950information via parser actions. Some cases of lexer interactions can be
8a4281b9 951eliminated by using GLR to shift the complications from the
f8e1c9e5
AD
952lexer to the parser. You must check the remaining cases for
953correctness.
954
955In our example, it would be safe for the lexer to return tokens based on
956their current meanings in some symbol table, because no new symbols are
957defined in the middle of a type declaration. Though it is possible for
958a parser to define the enumeration constants as they are parsed, before
959the type declaration is completed, it actually makes no difference since
960they cannot be used within the same enumerated type declaration.
fa7e68c3
PE
961
962@node Merging GLR Parses
8a4281b9
JD
963@subsection Using GLR to Resolve Ambiguities
964@cindex GLR parsing, ambiguous grammars
965@cindex generalized LR (GLR) parsing, ambiguous grammars
fa7e68c3
PE
966@findex %dprec
967@findex %merge
968@cindex conflicts
969@cindex reduce/reduce conflicts
970
2a8d363a 971Let's consider an example, vastly simplified from a C++ grammar.
676385e2
PH
972
973@example
974%@{
38a92d50
PE
975 #include <stdio.h>
976 #define YYSTYPE char const *
977 int yylex (void);
978 void yyerror (char const *);
676385e2
PH
979%@}
980
981%token TYPENAME ID
982
983%right '='
984%left '+'
985
986%glr-parser
987
988%%
989
fae437e8 990prog :
676385e2
PH
991 | prog stmt @{ printf ("\n"); @}
992 ;
993
994stmt : expr ';' %dprec 1
995 | decl %dprec 2
996 ;
997
2a8d363a 998expr : ID @{ printf ("%s ", $$); @}
fae437e8 999 | TYPENAME '(' expr ')'
2a8d363a
AD
1000 @{ printf ("%s <cast> ", $1); @}
1001 | expr '+' expr @{ printf ("+ "); @}
1002 | expr '=' expr @{ printf ("= "); @}
676385e2
PH
1003 ;
1004
fae437e8 1005decl : TYPENAME declarator ';'
2a8d363a 1006 @{ printf ("%s <declare> ", $1); @}
676385e2 1007 | TYPENAME declarator '=' expr ';'
2a8d363a 1008 @{ printf ("%s <init-declare> ", $1); @}
676385e2
PH
1009 ;
1010
2a8d363a 1011declarator : ID @{ printf ("\"%s\" ", $1); @}
676385e2
PH
1012 | '(' declarator ')'
1013 ;
1014@end example
1015
1016@noindent
1017This models a problematic part of the C++ grammar---the ambiguity between
1018certain declarations and statements. For example,
1019
1020@example
1021T (x) = y+z;
1022@end example
1023
1024@noindent
1025parses as either an @code{expr} or a @code{stmt}
c827f760
PE
1026(assuming that @samp{T} is recognized as a @code{TYPENAME} and
1027@samp{x} as an @code{ID}).
676385e2 1028Bison detects this as a reduce/reduce conflict between the rules
fae437e8 1029@code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
e757bb10 1030time it encounters @code{x} in the example above. Since this is a
8a4281b9 1031GLR parser, it therefore splits the problem into two parses, one for
fa7e68c3
PE
1032each choice of resolving the reduce/reduce conflict.
1033Unlike the example from the previous section (@pxref{Simple GLR Parsers}),
1034however, neither of these parses ``dies,'' because the grammar as it stands is
e757bb10
AD
1035ambiguous. One of the parsers eventually reduces @code{stmt : expr ';'} and
1036the other reduces @code{stmt : decl}, after which both parsers are in an
1037identical state: they've seen @samp{prog stmt} and have the same unprocessed
1038input remaining. We say that these parses have @dfn{merged.}
fa7e68c3 1039
8a4281b9 1040At this point, the GLR parser requires a specification in the
fa7e68c3
PE
1041grammar of how to choose between the competing parses.
1042In the example above, the two @code{%dprec}
e757bb10 1043declarations specify that Bison is to give precedence
fa7e68c3 1044to the parse that interprets the example as a
676385e2
PH
1045@code{decl}, which implies that @code{x} is a declarator.
1046The parser therefore prints
1047
1048@example
fae437e8 1049"x" y z + T <init-declare>
676385e2
PH
1050@end example
1051
fa7e68c3
PE
1052The @code{%dprec} declarations only come into play when more than one
1053parse survives. Consider a different input string for this parser:
676385e2
PH
1054
1055@example
1056T (x) + y;
1057@end example
1058
1059@noindent
8a4281b9 1060This is another example of using GLR to parse an unambiguous
fa7e68c3 1061construct, as shown in the previous section (@pxref{Simple GLR Parsers}).
676385e2
PH
1062Here, there is no ambiguity (this cannot be parsed as a declaration).
1063However, at the time the Bison parser encounters @code{x}, it does not
1064have enough information to resolve the reduce/reduce conflict (again,
1065between @code{x} as an @code{expr} or a @code{declarator}). In this
fa7e68c3 1066case, no precedence declaration is used. Again, the parser splits
676385e2
PH
1067into two, one assuming that @code{x} is an @code{expr}, and the other
1068assuming @code{x} is a @code{declarator}. The second of these parsers
1069then vanishes when it sees @code{+}, and the parser prints
1070
1071@example
fae437e8 1072x T <cast> y +
676385e2
PH
1073@end example
1074
1075Suppose that instead of resolving the ambiguity, you wanted to see all
fa7e68c3 1076the possibilities. For this purpose, you must merge the semantic
676385e2
PH
1077actions of the two possible parsers, rather than choosing one over the
1078other. To do so, you could change the declaration of @code{stmt} as
1079follows:
1080
1081@example
1082stmt : expr ';' %merge <stmtMerge>
1083 | decl %merge <stmtMerge>
1084 ;
1085@end example
1086
1087@noindent
676385e2
PH
1088and define the @code{stmtMerge} function as:
1089
1090@example
38a92d50
PE
1091static YYSTYPE
1092stmtMerge (YYSTYPE x0, YYSTYPE x1)
676385e2
PH
1093@{
1094 printf ("<OR> ");
1095 return "";
1096@}
1097@end example
1098
1099@noindent
1100with an accompanying forward declaration
1101in the C declarations at the beginning of the file:
1102
1103@example
1104%@{
38a92d50 1105 #define YYSTYPE char const *
676385e2
PH
1106 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
1107%@}
1108@end example
1109
1110@noindent
fa7e68c3
PE
1111With these declarations, the resulting parser parses the first example
1112as both an @code{expr} and a @code{decl}, and prints
676385e2
PH
1113
1114@example
fae437e8 1115"x" y z + T <init-declare> x T <cast> y z + = <OR>
676385e2
PH
1116@end example
1117
fa7e68c3 1118Bison requires that all of the
e757bb10 1119productions that participate in any particular merge have identical
fa7e68c3
PE
1120@samp{%merge} clauses. Otherwise, the ambiguity would be unresolvable,
1121and the parser will report an error during any parse that results in
1122the offending merge.
9501dc6e 1123
32c29292
JD
1124@node GLR Semantic Actions
1125@subsection GLR Semantic Actions
1126
8a4281b9 1127The nature of GLR parsing and the structure of the generated
20be2f92
PH
1128parsers give rise to certain restrictions on semantic values and actions.
1129
1130@subsubsection Deferred semantic actions
32c29292
JD
1131@cindex deferred semantic actions
1132By definition, a deferred semantic action is not performed at the same time as
1133the associated reduction.
1134This raises caveats for several Bison features you might use in a semantic
8a4281b9 1135action in a GLR parser.
32c29292
JD
1136
1137@vindex yychar
8a4281b9 1138@cindex GLR parsers and @code{yychar}
32c29292 1139@vindex yylval
8a4281b9 1140@cindex GLR parsers and @code{yylval}
32c29292 1141@vindex yylloc
8a4281b9 1142@cindex GLR parsers and @code{yylloc}
32c29292 1143In any semantic action, you can examine @code{yychar} to determine the type of
742e4900 1144the lookahead token present at the time of the associated reduction.
32c29292
JD
1145After checking that @code{yychar} is not set to @code{YYEMPTY} or @code{YYEOF},
1146you can then examine @code{yylval} and @code{yylloc} to determine the
742e4900 1147lookahead token's semantic value and location, if any.
32c29292
JD
1148In a nondeferred semantic action, you can also modify any of these variables to
1149influence syntax analysis.
742e4900 1150@xref{Lookahead, ,Lookahead Tokens}.
32c29292
JD
1151
1152@findex yyclearin
8a4281b9 1153@cindex GLR parsers and @code{yyclearin}
32c29292
JD
1154In a deferred semantic action, it's too late to influence syntax analysis.
1155In this case, @code{yychar}, @code{yylval}, and @code{yylloc} are set to
1156shallow copies of the values they had at the time of the associated reduction.
1157For this reason alone, modifying them is dangerous.
1158Moreover, the result of modifying them is undefined and subject to change with
1159future versions of Bison.
1160For example, if a semantic action might be deferred, you should never write it
1161to invoke @code{yyclearin} (@pxref{Action Features}) or to attempt to free
1162memory referenced by @code{yylval}.
1163
20be2f92 1164@subsubsection YYERROR
32c29292 1165@findex YYERROR
8a4281b9 1166@cindex GLR parsers and @code{YYERROR}
32c29292 1167Another Bison feature requiring special consideration is @code{YYERROR}
8710fc41 1168(@pxref{Action Features}), which you can invoke in a semantic action to
32c29292 1169initiate error recovery.
8a4281b9 1170During deterministic GLR operation, the effect of @code{YYERROR} is
eb45ef3b 1171the same as its effect in a deterministic parser.
20be2f92
PH
1172The effect in a deferred action is similar, but the precise point of the
1173error is undefined; instead, the parser reverts to deterministic operation,
1174selecting an unspecified stack on which to continue with a syntax error.
1175In a semantic predicate (see @ref{Semantic Predicates}) during nondeterministic
1176parsing, @code{YYERROR} silently prunes
1177the parse that invoked the test.
1178
1179@subsubsection Restrictions on semantic values and locations
8a4281b9 1180GLR parsers require that you use POD (Plain Old Data) types for
20be2f92
PH
1181semantic values and location types when using the generated parsers as
1182C++ code.
8710fc41 1183
ca2a6d15
PH
1184@node Semantic Predicates
1185@subsection Controlling a Parse with Arbitrary Predicates
1186@findex %?
8a4281b9 1187@cindex Semantic predicates in GLR parsers
ca2a6d15
PH
1188
1189In addition to the @code{%dprec} and @code{%merge} directives,
8a4281b9 1190GLR parsers
ca2a6d15
PH
1191allow you to reject parses on the basis of arbitrary computations executed
1192in user code, without having Bison treat this rejection as an error
1193if there are alternative parses. (This feature is experimental and may
1194evolve. We welcome user feedback.) For example,
1195
1196@smallexample
1197widget :
1198 %?@{ new_syntax @} "widget" id new_args @{ $$ = f($3, $4); @}
1199 | %?@{ !new_syntax @} "widget" id old_args @{ $$ = f($3, $4); @}
1200 ;
1201@end smallexample
1202
1203@noindent
1204is one way to allow the same parser to handle two different syntaxes for
1205widgets. The clause preceded by @code{%?} is treated like an ordinary
1206action, except that its text is treated as an expression and is always
1207evaluated immediately (even when in nondeterministic mode). If the
1208expression yields 0 (false), the clause is treated as a syntax error,
1209which, in a nondeterministic parser, causes the stack in which it is reduced
1210to die. In a deterministic parser, it acts like YYERROR.
1211
1212As the example shows, predicates otherwise look like semantic actions, and
1213therefore you must be take them into account when determining the numbers
1214to use for denoting the semantic values of right-hand side symbols.
1215Predicate actions, however, have no defined value, and may not be given
1216labels.
1217
1218There is a subtle difference between semantic predicates and ordinary
1219actions in nondeterministic mode, since the latter are deferred.
1220For example, we could try to rewrite the previous example as
1221
1222@smallexample
1223widget :
1224 @{ if (!new_syntax) YYERROR; @} "widget" id new_args @{ $$ = f($3, $4); @}
1225 | @{ if (new_syntax) YYERROR; @} "widget" id old_args @{ $$ = f($3, $4); @}
1226 ;
1227@end smallexample
1228
1229@noindent
1230(reversing the sense of the predicate tests to cause an error when they are
1231false). However, this
1232does @emph{not} have the same effect if @code{new_args} and @code{old_args}
1233have overlapping syntax.
1234Since the mid-rule actions testing @code{new_syntax} are deferred,
8a4281b9 1235a GLR parser first encounters the unresolved ambiguous reduction
ca2a6d15
PH
1236for cases where @code{new_args} and @code{old_args} recognize the same string
1237@emph{before} performing the tests of @code{new_syntax}. It therefore
1238reports an error.
1239
1240Finally, be careful in writing predicates: deferred actions have not been
1241evaluated, so that using them in a predicate will have undefined effects.
1242
fa7e68c3 1243@node Compiler Requirements
8a4281b9 1244@subsection Considerations when Compiling GLR Parsers
fa7e68c3 1245@cindex @code{inline}
8a4281b9 1246@cindex GLR parsers and @code{inline}
fa7e68c3 1247
8a4281b9 1248The GLR parsers require a compiler for ISO C89 or
38a92d50
PE
1249later. In addition, they use the @code{inline} keyword, which is not
1250C89, but is C99 and is a common extension in pre-C99 compilers. It is
1251up to the user of these parsers to handle
9501dc6e
AD
1252portability issues. For instance, if using Autoconf and the Autoconf
1253macro @code{AC_C_INLINE}, a mere
1254
1255@example
1256%@{
38a92d50 1257 #include <config.h>
9501dc6e
AD
1258%@}
1259@end example
1260
1261@noindent
1262will suffice. Otherwise, we suggest
1263
1264@example
1265%@{
38a92d50
PE
1266 #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
1267 #define inline
1268 #endif
9501dc6e
AD
1269%@}
1270@end example
676385e2 1271
342b8b6e 1272@node Locations Overview
847bf1f5
AD
1273@section Locations
1274@cindex location
95923bd6
AD
1275@cindex textual location
1276@cindex location, textual
847bf1f5
AD
1277
1278Many applications, like interpreters or compilers, have to produce verbose
72d2299c 1279and useful error messages. To achieve this, one must be able to keep track of
95923bd6 1280the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
847bf1f5
AD
1281Bison provides a mechanism for handling these locations.
1282
72d2299c 1283Each token has a semantic value. In a similar fashion, each token has an
847bf1f5 1284associated location, but the type of locations is the same for all tokens and
72d2299c 1285groupings. Moreover, the output parser is equipped with a default data
847bf1f5
AD
1286structure for storing locations (@pxref{Locations}, for more details).
1287
1288Like semantic values, locations can be reached in actions using a dedicated
72d2299c 1289set of constructs. In the example above, the location of the whole grouping
847bf1f5
AD
1290is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
1291@code{@@3}.
1292
1293When a rule is matched, a default action is used to compute the semantic value
72d2299c
PE
1294of its left hand side (@pxref{Actions}). In the same way, another default
1295action is used for locations. However, the action for locations is general
847bf1f5 1296enough for most cases, meaning there is usually no need to describe for each
72d2299c 1297rule how @code{@@$} should be formed. When building a new location for a given
847bf1f5
AD
1298grouping, the default behavior of the output parser is to take the beginning
1299of the first symbol, and the end of the last symbol.
1300
342b8b6e 1301@node Bison Parser
ff7571c0 1302@section Bison Output: the Parser Implementation File
bfa74976
RS
1303@cindex Bison parser
1304@cindex Bison utility
1305@cindex lexical analyzer, purpose
1306@cindex parser
1307
ff7571c0
JD
1308When you run Bison, you give it a Bison grammar file as input. The
1309most important output is a C source file that implements a parser for
1310the language described by the grammar. This parser is called a
1311@dfn{Bison parser}, and this file is called a @dfn{Bison parser
1312implementation file}. Keep in mind that the Bison utility and the
1313Bison parser are two distinct programs: the Bison utility is a program
1314whose output is the Bison parser implementation file that becomes part
1315of your program.
bfa74976
RS
1316
1317The job of the Bison parser is to group tokens into groupings according to
1318the grammar rules---for example, to build identifiers and operators into
1319expressions. As it does this, it runs the actions for the grammar rules it
1320uses.
1321
704a47c4
AD
1322The tokens come from a function called the @dfn{lexical analyzer} that
1323you must supply in some fashion (such as by writing it in C). The Bison
1324parser calls the lexical analyzer each time it wants a new token. It
1325doesn't know what is ``inside'' the tokens (though their semantic values
1326may reflect this). Typically the lexical analyzer makes the tokens by
1327parsing characters of text, but Bison does not depend on this.
1328@xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
bfa74976 1329
ff7571c0
JD
1330The Bison parser implementation file is C code which defines a
1331function named @code{yyparse} which implements that grammar. This
1332function does not make a complete C program: you must supply some
1333additional functions. One is the lexical analyzer. Another is an
1334error-reporting function which the parser calls to report an error.
1335In addition, a complete C program must start with a function called
1336@code{main}; you have to provide this, and arrange for it to call
1337@code{yyparse} or the parser will never run. @xref{Interface, ,Parser
1338C-Language Interface}.
bfa74976 1339
f7ab6a50 1340Aside from the token type names and the symbols in the actions you
ff7571c0
JD
1341write, all symbols defined in the Bison parser implementation file
1342itself begin with @samp{yy} or @samp{YY}. This includes interface
1343functions such as the lexical analyzer function @code{yylex}, the
1344error reporting function @code{yyerror} and the parser function
1345@code{yyparse} itself. This also includes numerous identifiers used
1346for internal purposes. Therefore, you should avoid using C
1347identifiers starting with @samp{yy} or @samp{YY} in the Bison grammar
1348file except for the ones defined in this manual. Also, you should
1349avoid using the C identifiers @samp{malloc} and @samp{free} for
1350anything other than their usual meanings.
1351
1352In some cases the Bison parser implementation file includes system
1353headers, and in those cases your code should respect the identifiers
1354reserved by those headers. On some non-GNU hosts, @code{<alloca.h>},
1355@code{<malloc.h>}, @code{<stddef.h>}, and @code{<stdlib.h>} are
1356included as needed to declare memory allocators and related types.
1357@code{<libintl.h>} is included if message translation is in use
1358(@pxref{Internationalization}). Other system headers may be included
1359if you define @code{YYDEBUG} to a nonzero value (@pxref{Tracing,
1360,Tracing Your Parser}).
7093d0f5 1361
342b8b6e 1362@node Stages
bfa74976
RS
1363@section Stages in Using Bison
1364@cindex stages in using Bison
1365@cindex using Bison
1366
1367The actual language-design process using Bison, from grammar specification
1368to a working compiler or interpreter, has these parts:
1369
1370@enumerate
1371@item
1372Formally specify the grammar in a form recognized by Bison
704a47c4
AD
1373(@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
1374in the language, describe the action that is to be taken when an
1375instance of that rule is recognized. The action is described by a
1376sequence of C statements.
bfa74976
RS
1377
1378@item
704a47c4
AD
1379Write a lexical analyzer to process input and pass tokens to the parser.
1380The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
1381Lexical Analyzer Function @code{yylex}}). It could also be produced
1382using Lex, but the use of Lex is not discussed in this manual.
bfa74976
RS
1383
1384@item
1385Write a controlling function that calls the Bison-produced parser.
1386
1387@item
1388Write error-reporting routines.
1389@end enumerate
1390
1391To turn this source code as written into a runnable program, you
1392must follow these steps:
1393
1394@enumerate
1395@item
1396Run Bison on the grammar to produce the parser.
1397
1398@item
1399Compile the code output by Bison, as well as any other source files.
1400
1401@item
1402Link the object files to produce the finished product.
1403@end enumerate
1404
342b8b6e 1405@node Grammar Layout
bfa74976
RS
1406@section The Overall Layout of a Bison Grammar
1407@cindex grammar file
1408@cindex file format
1409@cindex format of grammar file
1410@cindex layout of Bison grammar
1411
1412The input file for the Bison utility is a @dfn{Bison grammar file}. The
1413general form of a Bison grammar file is as follows:
1414
1415@example
1416%@{
08e49d20 1417@var{Prologue}
bfa74976
RS
1418%@}
1419
1420@var{Bison declarations}
1421
1422%%
1423@var{Grammar rules}
1424%%
08e49d20 1425@var{Epilogue}
bfa74976
RS
1426@end example
1427
1428@noindent
1429The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
1430in every Bison grammar file to separate the sections.
1431
72d2299c 1432The prologue may define types and variables used in the actions. You can
342b8b6e 1433also use preprocessor commands to define macros used there, and use
bfa74976 1434@code{#include} to include header files that do any of these things.
38a92d50
PE
1435You need to declare the lexical analyzer @code{yylex} and the error
1436printer @code{yyerror} here, along with any other global identifiers
1437used by the actions in the grammar rules.
bfa74976
RS
1438
1439The Bison declarations declare the names of the terminal and nonterminal
1440symbols, and may also describe operator precedence and the data types of
1441semantic values of various symbols.
1442
1443The grammar rules define how to construct each nonterminal symbol from its
1444parts.
1445
38a92d50
PE
1446The epilogue can contain any code you want to use. Often the
1447definitions of functions declared in the prologue go here. In a
1448simple program, all the rest of the program can go here.
bfa74976 1449
342b8b6e 1450@node Examples
bfa74976
RS
1451@chapter Examples
1452@cindex simple examples
1453@cindex examples, simple
1454
1455Now we show and explain three sample programs written using Bison: a
1456reverse polish notation calculator, an algebraic (infix) notation
1457calculator, and a multi-function calculator. All three have been tested
1458under BSD Unix 4.3; each produces a usable, though limited, interactive
1459desk-top calculator.
1460
1461These examples are simple, but Bison grammars for real programming
aa08666d
AD
1462languages are written the same way. You can copy these examples into a
1463source file to try them.
bfa74976
RS
1464
1465@menu
f5f419de
DJ
1466* RPN Calc:: Reverse polish notation calculator;
1467 a first example with no operator precedence.
1468* Infix Calc:: Infix (algebraic) notation calculator.
1469 Operator precedence is introduced.
bfa74976 1470* Simple Error Recovery:: Continuing after syntax errors.
342b8b6e 1471* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
f5f419de
DJ
1472* Multi-function Calc:: Calculator with memory and trig functions.
1473 It uses multiple data-types for semantic values.
1474* Exercises:: Ideas for improving the multi-function calculator.
bfa74976
RS
1475@end menu
1476
342b8b6e 1477@node RPN Calc
bfa74976
RS
1478@section Reverse Polish Notation Calculator
1479@cindex reverse polish notation
1480@cindex polish notation calculator
1481@cindex @code{rpcalc}
1482@cindex calculator, simple
1483
1484The first example is that of a simple double-precision @dfn{reverse polish
1485notation} calculator (a calculator using postfix operators). This example
1486provides a good starting point, since operator precedence is not an issue.
1487The second example will illustrate how operator precedence is handled.
1488
1489The source code for this calculator is named @file{rpcalc.y}. The
ff7571c0 1490@samp{.y} extension is a convention used for Bison grammar files.
bfa74976
RS
1491
1492@menu
f5f419de
DJ
1493* Rpcalc Declarations:: Prologue (declarations) for rpcalc.
1494* Rpcalc Rules:: Grammar Rules for rpcalc, with explanation.
1495* Rpcalc Lexer:: The lexical analyzer.
1496* Rpcalc Main:: The controlling function.
1497* Rpcalc Error:: The error reporting function.
1498* Rpcalc Generate:: Running Bison on the grammar file.
1499* Rpcalc Compile:: Run the C compiler on the output code.
bfa74976
RS
1500@end menu
1501
f5f419de 1502@node Rpcalc Declarations
bfa74976
RS
1503@subsection Declarations for @code{rpcalc}
1504
1505Here are the C and Bison declarations for the reverse polish notation
1506calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1507
1508@example
72d2299c 1509/* Reverse polish notation calculator. */
bfa74976
RS
1510
1511%@{
38a92d50
PE
1512 #define YYSTYPE double
1513 #include <math.h>
1514 int yylex (void);
1515 void yyerror (char const *);
bfa74976
RS
1516%@}
1517
1518%token NUM
1519
72d2299c 1520%% /* Grammar rules and actions follow. */
bfa74976
RS
1521@end example
1522
75f5aaea 1523The declarations section (@pxref{Prologue, , The prologue}) contains two
38a92d50 1524preprocessor directives and two forward declarations.
bfa74976
RS
1525
1526The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1964ad8c
AD
1527specifying the C data type for semantic values of both tokens and
1528groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1529Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1530don't define it, @code{int} is the default. Because we specify
1531@code{double}, each token and each expression has an associated value,
1532which is a floating point number.
bfa74976
RS
1533
1534The @code{#include} directive is used to declare the exponentiation
1535function @code{pow}.
1536
38a92d50
PE
1537The forward declarations for @code{yylex} and @code{yyerror} are
1538needed because the C language requires that functions be declared
1539before they are used. These functions will be defined in the
1540epilogue, but the parser calls them so they must be declared in the
1541prologue.
1542
704a47c4
AD
1543The second section, Bison declarations, provides information to Bison
1544about the token types (@pxref{Bison Declarations, ,The Bison
1545Declarations Section}). Each terminal symbol that is not a
1546single-character literal must be declared here. (Single-character
bfa74976
RS
1547literals normally don't need to be declared.) In this example, all the
1548arithmetic operators are designated by single-character literals, so the
1549only terminal symbol that needs to be declared is @code{NUM}, the token
1550type for numeric constants.
1551
342b8b6e 1552@node Rpcalc Rules
bfa74976
RS
1553@subsection Grammar Rules for @code{rpcalc}
1554
1555Here are the grammar rules for the reverse polish notation calculator.
1556
1557@example
1558input: /* empty */
1559 | input line
1560;
1561
1562line: '\n'
18b519c0 1563 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
bfa74976
RS
1564;
1565
18b519c0
AD
1566exp: NUM @{ $$ = $1; @}
1567 | exp exp '+' @{ $$ = $1 + $2; @}
1568 | exp exp '-' @{ $$ = $1 - $2; @}
1569 | exp exp '*' @{ $$ = $1 * $2; @}
1570 | exp exp '/' @{ $$ = $1 / $2; @}
1571 /* Exponentiation */
1572 | exp exp '^' @{ $$ = pow ($1, $2); @}
1573 /* Unary minus */
1574 | exp 'n' @{ $$ = -$1; @}
bfa74976
RS
1575;
1576%%
1577@end example
1578
1579The groupings of the rpcalc ``language'' defined here are the expression
1580(given the name @code{exp}), the line of input (@code{line}), and the
1581complete input transcript (@code{input}). Each of these nonterminal
8c5b881d 1582symbols has several alternate rules, joined by the vertical bar @samp{|}
bfa74976
RS
1583which is read as ``or''. The following sections explain what these rules
1584mean.
1585
1586The semantics of the language is determined by the actions taken when a
1587grouping is recognized. The actions are the C code that appears inside
1588braces. @xref{Actions}.
1589
1590You must specify these actions in C, but Bison provides the means for
1591passing semantic values between the rules. In each action, the
1592pseudo-variable @code{$$} stands for the semantic value for the grouping
1593that the rule is going to construct. Assigning a value to @code{$$} is the
1594main job of most actions. The semantic values of the components of the
1595rule are referred to as @code{$1}, @code{$2}, and so on.
1596
1597@menu
13863333
AD
1598* Rpcalc Input::
1599* Rpcalc Line::
1600* Rpcalc Expr::
bfa74976
RS
1601@end menu
1602
342b8b6e 1603@node Rpcalc Input
bfa74976
RS
1604@subsubsection Explanation of @code{input}
1605
1606Consider the definition of @code{input}:
1607
1608@example
1609input: /* empty */
1610 | input line
1611;
1612@end example
1613
1614This definition reads as follows: ``A complete input is either an empty
1615string, or a complete input followed by an input line''. Notice that
1616``complete input'' is defined in terms of itself. This definition is said
1617to be @dfn{left recursive} since @code{input} appears always as the
1618leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1619
1620The first alternative is empty because there are no symbols between the
1621colon and the first @samp{|}; this means that @code{input} can match an
1622empty string of input (no tokens). We write the rules this way because it
1623is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1624It's conventional to put an empty alternative first and write the comment
1625@samp{/* empty */} in it.
1626
1627The second alternate rule (@code{input line}) handles all nontrivial input.
1628It means, ``After reading any number of lines, read one more line if
1629possible.'' The left recursion makes this rule into a loop. Since the
1630first alternative matches empty input, the loop can be executed zero or
1631more times.
1632
1633The parser function @code{yyparse} continues to process input until a
1634grammatical error is seen or the lexical analyzer says there are no more
72d2299c 1635input tokens; we will arrange for the latter to happen at end-of-input.
bfa74976 1636
342b8b6e 1637@node Rpcalc Line
bfa74976
RS
1638@subsubsection Explanation of @code{line}
1639
1640Now consider the definition of @code{line}:
1641
1642@example
1643line: '\n'
1644 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1645;
1646@end example
1647
1648The first alternative is a token which is a newline character; this means
1649that rpcalc accepts a blank line (and ignores it, since there is no
1650action). The second alternative is an expression followed by a newline.
1651This is the alternative that makes rpcalc useful. The semantic value of
1652the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1653question is the first symbol in the alternative. The action prints this
1654value, which is the result of the computation the user asked for.
1655
1656This action is unusual because it does not assign a value to @code{$$}. As
1657a consequence, the semantic value associated with the @code{line} is
1658uninitialized (its value will be unpredictable). This would be a bug if
1659that value were ever used, but we don't use it: once rpcalc has printed the
1660value of the user's input line, that value is no longer needed.
1661
342b8b6e 1662@node Rpcalc Expr
bfa74976
RS
1663@subsubsection Explanation of @code{expr}
1664
1665The @code{exp} grouping has several rules, one for each kind of expression.
1666The first rule handles the simplest expressions: those that are just numbers.
1667The second handles an addition-expression, which looks like two expressions
1668followed by a plus-sign. The third handles subtraction, and so on.
1669
1670@example
1671exp: NUM
1672 | exp exp '+' @{ $$ = $1 + $2; @}
1673 | exp exp '-' @{ $$ = $1 - $2; @}
1674 @dots{}
1675 ;
1676@end example
1677
1678We have used @samp{|} to join all the rules for @code{exp}, but we could
1679equally well have written them separately:
1680
1681@example
1682exp: NUM ;
1683exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1684exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1685 @dots{}
1686@end example
1687
1688Most of the rules have actions that compute the value of the expression in
1689terms of the value of its parts. For example, in the rule for addition,
1690@code{$1} refers to the first component @code{exp} and @code{$2} refers to
1691the second one. The third component, @code{'+'}, has no meaningful
1692associated semantic value, but if it had one you could refer to it as
1693@code{$3}. When @code{yyparse} recognizes a sum expression using this
1694rule, the sum of the two subexpressions' values is produced as the value of
1695the entire expression. @xref{Actions}.
1696
1697You don't have to give an action for every rule. When a rule has no
1698action, Bison by default copies the value of @code{$1} into @code{$$}.
1699This is what happens in the first rule (the one that uses @code{NUM}).
1700
1701The formatting shown here is the recommended convention, but Bison does
72d2299c 1702not require it. You can add or change white space as much as you wish.
bfa74976
RS
1703For example, this:
1704
1705@example
99a9344e 1706exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} ;
bfa74976
RS
1707@end example
1708
1709@noindent
1710means the same thing as this:
1711
1712@example
1713exp: NUM
1714 | exp exp '+' @{ $$ = $1 + $2; @}
1715 | @dots{}
99a9344e 1716;
bfa74976
RS
1717@end example
1718
1719@noindent
1720The latter, however, is much more readable.
1721
342b8b6e 1722@node Rpcalc Lexer
bfa74976
RS
1723@subsection The @code{rpcalc} Lexical Analyzer
1724@cindex writing a lexical analyzer
1725@cindex lexical analyzer, writing
1726
704a47c4
AD
1727The lexical analyzer's job is low-level parsing: converting characters
1728or sequences of characters into tokens. The Bison parser gets its
1729tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1730Analyzer Function @code{yylex}}.
bfa74976 1731
8a4281b9 1732Only a simple lexical analyzer is needed for the RPN
c827f760 1733calculator. This
bfa74976
RS
1734lexical analyzer skips blanks and tabs, then reads in numbers as
1735@code{double} and returns them as @code{NUM} tokens. Any other character
1736that isn't part of a number is a separate token. Note that the token-code
1737for such a single-character token is the character itself.
1738
1739The return value of the lexical analyzer function is a numeric code which
1740represents a token type. The same text used in Bison rules to stand for
1741this token type is also a C expression for the numeric code for the type.
1742This works in two ways. If the token type is a character literal, then its
e966383b 1743numeric code is that of the character; you can use the same
bfa74976
RS
1744character literal in the lexical analyzer to express the number. If the
1745token type is an identifier, that identifier is defined by Bison as a C
1746macro whose definition is the appropriate number. In this example,
1747therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1748
1964ad8c
AD
1749The semantic value of the token (if it has one) is stored into the
1750global variable @code{yylval}, which is where the Bison parser will look
1751for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
f5f419de 1752defined at the beginning of the grammar; @pxref{Rpcalc Declarations,
1964ad8c 1753,Declarations for @code{rpcalc}}.)
bfa74976 1754
72d2299c
PE
1755A token type code of zero is returned if the end-of-input is encountered.
1756(Bison recognizes any nonpositive value as indicating end-of-input.)
bfa74976
RS
1757
1758Here is the code for the lexical analyzer:
1759
1760@example
1761@group
72d2299c 1762/* The lexical analyzer returns a double floating point
e966383b 1763 number on the stack and the token NUM, or the numeric code
72d2299c
PE
1764 of the character read if not a number. It skips all blanks
1765 and tabs, and returns 0 for end-of-input. */
bfa74976
RS
1766
1767#include <ctype.h>
1768@end group
1769
1770@group
13863333
AD
1771int
1772yylex (void)
bfa74976
RS
1773@{
1774 int c;
1775
72d2299c 1776 /* Skip white space. */
13863333 1777 while ((c = getchar ()) == ' ' || c == '\t')
bfa74976
RS
1778 ;
1779@end group
1780@group
72d2299c 1781 /* Process numbers. */
13863333 1782 if (c == '.' || isdigit (c))
bfa74976
RS
1783 @{
1784 ungetc (c, stdin);
1785 scanf ("%lf", &yylval);
1786 return NUM;
1787 @}
1788@end group
1789@group
72d2299c 1790 /* Return end-of-input. */
13863333 1791 if (c == EOF)
bfa74976 1792 return 0;
72d2299c 1793 /* Return a single char. */
13863333 1794 return c;
bfa74976
RS
1795@}
1796@end group
1797@end example
1798
342b8b6e 1799@node Rpcalc Main
bfa74976
RS
1800@subsection The Controlling Function
1801@cindex controlling function
1802@cindex main function in simple example
1803
1804In keeping with the spirit of this example, the controlling function is
1805kept to the bare minimum. The only requirement is that it call
1806@code{yyparse} to start the process of parsing.
1807
1808@example
1809@group
13863333
AD
1810int
1811main (void)
bfa74976 1812@{
13863333 1813 return yyparse ();
bfa74976
RS
1814@}
1815@end group
1816@end example
1817
342b8b6e 1818@node Rpcalc Error
bfa74976
RS
1819@subsection The Error Reporting Routine
1820@cindex error reporting routine
1821
1822When @code{yyparse} detects a syntax error, it calls the error reporting
13863333 1823function @code{yyerror} to print an error message (usually but not
6e649e65 1824always @code{"syntax error"}). It is up to the programmer to supply
13863333
AD
1825@code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1826here is the definition we will use:
bfa74976
RS
1827
1828@example
1829@group
1830#include <stdio.h>
1831
38a92d50 1832/* Called by yyparse on error. */
13863333 1833void
38a92d50 1834yyerror (char const *s)
bfa74976 1835@{
4e03e201 1836 fprintf (stderr, "%s\n", s);
bfa74976
RS
1837@}
1838@end group
1839@end example
1840
1841After @code{yyerror} returns, the Bison parser may recover from the error
1842and continue parsing if the grammar contains a suitable error rule
1843(@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1844have not written any error rules in this example, so any invalid input will
1845cause the calculator program to exit. This is not clean behavior for a
9ecbd125 1846real calculator, but it is adequate for the first example.
bfa74976 1847
f5f419de 1848@node Rpcalc Generate
bfa74976
RS
1849@subsection Running Bison to Make the Parser
1850@cindex running Bison (introduction)
1851
ceed8467
AD
1852Before running Bison to produce a parser, we need to decide how to
1853arrange all the source code in one or more source files. For such a
ff7571c0
JD
1854simple example, the easiest thing is to put everything in one file,
1855the grammar file. The definitions of @code{yylex}, @code{yyerror} and
1856@code{main} go at the end, in the epilogue of the grammar file
75f5aaea 1857(@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
bfa74976
RS
1858
1859For a large project, you would probably have several source files, and use
1860@code{make} to arrange to recompile them.
1861
ff7571c0
JD
1862With all the source in the grammar file, you use the following command
1863to convert it into a parser implementation file:
bfa74976
RS
1864
1865@example
fa4d969f 1866bison @var{file}.y
bfa74976
RS
1867@end example
1868
1869@noindent
ff7571c0
JD
1870In this example, the grammar file is called @file{rpcalc.y} (for
1871``Reverse Polish @sc{calc}ulator''). Bison produces a parser
1872implementation file named @file{@var{file}.tab.c}, removing the
1873@samp{.y} from the grammar file name. The parser implementation file
1874contains the source code for @code{yyparse}. The additional functions
1875in the grammar file (@code{yylex}, @code{yyerror} and @code{main}) are
1876copied verbatim to the parser implementation file.
bfa74976 1877
342b8b6e 1878@node Rpcalc Compile
ff7571c0 1879@subsection Compiling the Parser Implementation File
bfa74976
RS
1880@cindex compiling the parser
1881
ff7571c0 1882Here is how to compile and run the parser implementation file:
bfa74976
RS
1883
1884@example
1885@group
1886# @r{List files in current directory.}
9edcd895 1887$ @kbd{ls}
bfa74976
RS
1888rpcalc.tab.c rpcalc.y
1889@end group
1890
1891@group
1892# @r{Compile the Bison parser.}
1893# @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
b56471a6 1894$ @kbd{cc -lm -o rpcalc rpcalc.tab.c}
bfa74976
RS
1895@end group
1896
1897@group
1898# @r{List files again.}
9edcd895 1899$ @kbd{ls}
bfa74976
RS
1900rpcalc rpcalc.tab.c rpcalc.y
1901@end group
1902@end example
1903
1904The file @file{rpcalc} now contains the executable code. Here is an
1905example session using @code{rpcalc}.
1906
1907@example
9edcd895
AD
1908$ @kbd{rpcalc}
1909@kbd{4 9 +}
bfa74976 191013
9edcd895 1911@kbd{3 7 + 3 4 5 *+-}
bfa74976 1912-13
9edcd895 1913@kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
bfa74976 191413
9edcd895 1915@kbd{5 6 / 4 n +}
bfa74976 1916-3.166666667
9edcd895 1917@kbd{3 4 ^} @r{Exponentiation}
bfa74976 191881
9edcd895
AD
1919@kbd{^D} @r{End-of-file indicator}
1920$
bfa74976
RS
1921@end example
1922
342b8b6e 1923@node Infix Calc
bfa74976
RS
1924@section Infix Notation Calculator: @code{calc}
1925@cindex infix notation calculator
1926@cindex @code{calc}
1927@cindex calculator, infix notation
1928
1929We now modify rpcalc to handle infix operators instead of postfix. Infix
1930notation involves the concept of operator precedence and the need for
1931parentheses nested to arbitrary depth. Here is the Bison code for
1932@file{calc.y}, an infix desk-top calculator.
1933
1934@example
38a92d50 1935/* Infix notation calculator. */
bfa74976
RS
1936
1937%@{
38a92d50
PE
1938 #define YYSTYPE double
1939 #include <math.h>
1940 #include <stdio.h>
1941 int yylex (void);
1942 void yyerror (char const *);
bfa74976
RS
1943%@}
1944
38a92d50 1945/* Bison declarations. */
bfa74976
RS
1946%token NUM
1947%left '-' '+'
1948%left '*' '/'
d78f0ac9
AD
1949%precedence NEG /* negation--unary minus */
1950%right '^' /* exponentiation */
bfa74976 1951
38a92d50
PE
1952%% /* The grammar follows. */
1953input: /* empty */
bfa74976
RS
1954 | input line
1955;
1956
1957line: '\n'
1958 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1959;
1960
1961exp: NUM @{ $$ = $1; @}
1962 | exp '+' exp @{ $$ = $1 + $3; @}
1963 | exp '-' exp @{ $$ = $1 - $3; @}
1964 | exp '*' exp @{ $$ = $1 * $3; @}
1965 | exp '/' exp @{ $$ = $1 / $3; @}
1966 | '-' exp %prec NEG @{ $$ = -$2; @}
1967 | exp '^' exp @{ $$ = pow ($1, $3); @}
1968 | '(' exp ')' @{ $$ = $2; @}
1969;
1970%%
1971@end example
1972
1973@noindent
ceed8467
AD
1974The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1975same as before.
bfa74976
RS
1976
1977There are two important new features shown in this code.
1978
1979In the second section (Bison declarations), @code{%left} declares token
1980types and says they are left-associative operators. The declarations
1981@code{%left} and @code{%right} (right associativity) take the place of
1982@code{%token} which is used to declare a token type name without
d78f0ac9 1983associativity/precedence. (These tokens are single-character literals, which
bfa74976 1984ordinarily don't need to be declared. We declare them here to specify
d78f0ac9 1985the associativity/precedence.)
bfa74976
RS
1986
1987Operator precedence is determined by the line ordering of the
1988declarations; the higher the line number of the declaration (lower on
1989the page or screen), the higher the precedence. Hence, exponentiation
1990has the highest precedence, unary minus (@code{NEG}) is next, followed
d78f0ac9
AD
1991by @samp{*} and @samp{/}, and so on. Unary minus is not associative,
1992only precedence matters (@code{%precedence}. @xref{Precedence, ,Operator
704a47c4 1993Precedence}.
bfa74976 1994
704a47c4
AD
1995The other important new feature is the @code{%prec} in the grammar
1996section for the unary minus operator. The @code{%prec} simply instructs
1997Bison that the rule @samp{| '-' exp} has the same precedence as
1998@code{NEG}---in this case the next-to-highest. @xref{Contextual
1999Precedence, ,Context-Dependent Precedence}.
bfa74976
RS
2000
2001Here is a sample run of @file{calc.y}:
2002
2003@need 500
2004@example
9edcd895
AD
2005$ @kbd{calc}
2006@kbd{4 + 4.5 - (34/(8*3+-3))}
bfa74976 20076.880952381
9edcd895 2008@kbd{-56 + 2}
bfa74976 2009-54
9edcd895 2010@kbd{3 ^ 2}
bfa74976
RS
20119
2012@end example
2013
342b8b6e 2014@node Simple Error Recovery
bfa74976
RS
2015@section Simple Error Recovery
2016@cindex error recovery, simple
2017
2018Up to this point, this manual has not addressed the issue of @dfn{error
2019recovery}---how to continue parsing after the parser detects a syntax
ceed8467
AD
2020error. All we have handled is error reporting with @code{yyerror}.
2021Recall that by default @code{yyparse} returns after calling
2022@code{yyerror}. This means that an erroneous input line causes the
2023calculator program to exit. Now we show how to rectify this deficiency.
bfa74976
RS
2024
2025The Bison language itself includes the reserved word @code{error}, which
2026may be included in the grammar rules. In the example below it has
2027been added to one of the alternatives for @code{line}:
2028
2029@example
2030@group
2031line: '\n'
2032 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2033 | error '\n' @{ yyerrok; @}
2034;
2035@end group
2036@end example
2037
ceed8467 2038This addition to the grammar allows for simple error recovery in the
6e649e65 2039event of a syntax error. If an expression that cannot be evaluated is
ceed8467
AD
2040read, the error will be recognized by the third rule for @code{line},
2041and parsing will continue. (The @code{yyerror} function is still called
2042upon to print its message as well.) The action executes the statement
2043@code{yyerrok}, a macro defined automatically by Bison; its meaning is
2044that error recovery is complete (@pxref{Error Recovery}). Note the
2045difference between @code{yyerrok} and @code{yyerror}; neither one is a
e0c471a9 2046misprint.
bfa74976
RS
2047
2048This form of error recovery deals with syntax errors. There are other
2049kinds of errors; for example, division by zero, which raises an exception
2050signal that is normally fatal. A real calculator program must handle this
2051signal and use @code{longjmp} to return to @code{main} and resume parsing
2052input lines; it would also have to discard the rest of the current line of
2053input. We won't discuss this issue further because it is not specific to
2054Bison programs.
2055
342b8b6e
AD
2056@node Location Tracking Calc
2057@section Location Tracking Calculator: @code{ltcalc}
2058@cindex location tracking calculator
2059@cindex @code{ltcalc}
2060@cindex calculator, location tracking
2061
9edcd895
AD
2062This example extends the infix notation calculator with location
2063tracking. This feature will be used to improve the error messages. For
2064the sake of clarity, this example is a simple integer calculator, since
2065most of the work needed to use locations will be done in the lexical
72d2299c 2066analyzer.
342b8b6e
AD
2067
2068@menu
f5f419de
DJ
2069* Ltcalc Declarations:: Bison and C declarations for ltcalc.
2070* Ltcalc Rules:: Grammar rules for ltcalc, with explanations.
2071* Ltcalc Lexer:: The lexical analyzer.
342b8b6e
AD
2072@end menu
2073
f5f419de 2074@node Ltcalc Declarations
342b8b6e
AD
2075@subsection Declarations for @code{ltcalc}
2076
9edcd895
AD
2077The C and Bison declarations for the location tracking calculator are
2078the same as the declarations for the infix notation calculator.
342b8b6e
AD
2079
2080@example
2081/* Location tracking calculator. */
2082
2083%@{
38a92d50
PE
2084 #define YYSTYPE int
2085 #include <math.h>
2086 int yylex (void);
2087 void yyerror (char const *);
342b8b6e
AD
2088%@}
2089
2090/* Bison declarations. */
2091%token NUM
2092
2093%left '-' '+'
2094%left '*' '/'
d78f0ac9 2095%precedence NEG
342b8b6e
AD
2096%right '^'
2097
38a92d50 2098%% /* The grammar follows. */
342b8b6e
AD
2099@end example
2100
9edcd895
AD
2101@noindent
2102Note there are no declarations specific to locations. Defining a data
2103type for storing locations is not needed: we will use the type provided
2104by default (@pxref{Location Type, ,Data Types of Locations}), which is a
2105four member structure with the following integer fields:
2106@code{first_line}, @code{first_column}, @code{last_line} and
cd48d21d
AD
2107@code{last_column}. By conventions, and in accordance with the GNU
2108Coding Standards and common practice, the line and column count both
2109start at 1.
342b8b6e
AD
2110
2111@node Ltcalc Rules
2112@subsection Grammar Rules for @code{ltcalc}
2113
9edcd895
AD
2114Whether handling locations or not has no effect on the syntax of your
2115language. Therefore, grammar rules for this example will be very close
2116to those of the previous example: we will only modify them to benefit
2117from the new information.
342b8b6e 2118
9edcd895
AD
2119Here, we will use locations to report divisions by zero, and locate the
2120wrong expressions or subexpressions.
342b8b6e
AD
2121
2122@example
2123@group
2124input : /* empty */
2125 | input line
2126;
2127@end group
2128
2129@group
2130line : '\n'
2131 | exp '\n' @{ printf ("%d\n", $1); @}
2132;
2133@end group
2134
2135@group
2136exp : NUM @{ $$ = $1; @}
2137 | exp '+' exp @{ $$ = $1 + $3; @}
2138 | exp '-' exp @{ $$ = $1 - $3; @}
2139 | exp '*' exp @{ $$ = $1 * $3; @}
2140@end group
342b8b6e 2141@group
9edcd895 2142 | exp '/' exp
342b8b6e
AD
2143 @{
2144 if ($3)
2145 $$ = $1 / $3;
2146 else
2147 @{
2148 $$ = 1;
9edcd895
AD
2149 fprintf (stderr, "%d.%d-%d.%d: division by zero",
2150 @@3.first_line, @@3.first_column,
2151 @@3.last_line, @@3.last_column);
342b8b6e
AD
2152 @}
2153 @}
2154@end group
2155@group
178e123e 2156 | '-' exp %prec NEG @{ $$ = -$2; @}
342b8b6e
AD
2157 | exp '^' exp @{ $$ = pow ($1, $3); @}
2158 | '(' exp ')' @{ $$ = $2; @}
2159@end group
2160@end example
2161
2162This code shows how to reach locations inside of semantic actions, by
2163using the pseudo-variables @code{@@@var{n}} for rule components, and the
2164pseudo-variable @code{@@$} for groupings.
2165
9edcd895
AD
2166We don't need to assign a value to @code{@@$}: the output parser does it
2167automatically. By default, before executing the C code of each action,
2168@code{@@$} is set to range from the beginning of @code{@@1} to the end
2169of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
2170can be redefined (@pxref{Location Default Action, , Default Action for
2171Locations}), and for very specific rules, @code{@@$} can be computed by
2172hand.
342b8b6e
AD
2173
2174@node Ltcalc Lexer
2175@subsection The @code{ltcalc} Lexical Analyzer.
2176
9edcd895 2177Until now, we relied on Bison's defaults to enable location
72d2299c 2178tracking. The next step is to rewrite the lexical analyzer, and make it
9edcd895
AD
2179able to feed the parser with the token locations, as it already does for
2180semantic values.
342b8b6e 2181
9edcd895
AD
2182To this end, we must take into account every single character of the
2183input text, to avoid the computed locations of being fuzzy or wrong:
342b8b6e
AD
2184
2185@example
2186@group
2187int
2188yylex (void)
2189@{
2190 int c;
18b519c0 2191@end group
342b8b6e 2192
18b519c0 2193@group
72d2299c 2194 /* Skip white space. */
342b8b6e
AD
2195 while ((c = getchar ()) == ' ' || c == '\t')
2196 ++yylloc.last_column;
18b519c0 2197@end group
342b8b6e 2198
18b519c0 2199@group
72d2299c 2200 /* Step. */
342b8b6e
AD
2201 yylloc.first_line = yylloc.last_line;
2202 yylloc.first_column = yylloc.last_column;
2203@end group
2204
2205@group
72d2299c 2206 /* Process numbers. */
342b8b6e
AD
2207 if (isdigit (c))
2208 @{
2209 yylval = c - '0';
2210 ++yylloc.last_column;
2211 while (isdigit (c = getchar ()))
2212 @{
2213 ++yylloc.last_column;
2214 yylval = yylval * 10 + c - '0';
2215 @}
2216 ungetc (c, stdin);
2217 return NUM;
2218 @}
2219@end group
2220
72d2299c 2221 /* Return end-of-input. */
342b8b6e
AD
2222 if (c == EOF)
2223 return 0;
2224
72d2299c 2225 /* Return a single char, and update location. */
342b8b6e
AD
2226 if (c == '\n')
2227 @{
2228 ++yylloc.last_line;
2229 yylloc.last_column = 0;
2230 @}
2231 else
2232 ++yylloc.last_column;
2233 return c;
2234@}
2235@end example
2236
9edcd895
AD
2237Basically, the lexical analyzer performs the same processing as before:
2238it skips blanks and tabs, and reads numbers or single-character tokens.
2239In addition, it updates @code{yylloc}, the global variable (of type
2240@code{YYLTYPE}) containing the token's location.
342b8b6e 2241
9edcd895 2242Now, each time this function returns a token, the parser has its number
72d2299c 2243as well as its semantic value, and its location in the text. The last
9edcd895
AD
2244needed change is to initialize @code{yylloc}, for example in the
2245controlling function:
342b8b6e
AD
2246
2247@example
9edcd895 2248@group
342b8b6e
AD
2249int
2250main (void)
2251@{
2252 yylloc.first_line = yylloc.last_line = 1;
2253 yylloc.first_column = yylloc.last_column = 0;
2254 return yyparse ();
2255@}
9edcd895 2256@end group
342b8b6e
AD
2257@end example
2258
9edcd895
AD
2259Remember that computing locations is not a matter of syntax. Every
2260character must be associated to a location update, whether it is in
2261valid input, in comments, in literal strings, and so on.
342b8b6e
AD
2262
2263@node Multi-function Calc
bfa74976
RS
2264@section Multi-Function Calculator: @code{mfcalc}
2265@cindex multi-function calculator
2266@cindex @code{mfcalc}
2267@cindex calculator, multi-function
2268
2269Now that the basics of Bison have been discussed, it is time to move on to
2270a more advanced problem. The above calculators provided only five
2271functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
2272be nice to have a calculator that provides other mathematical functions such
2273as @code{sin}, @code{cos}, etc.
2274
2275It is easy to add new operators to the infix calculator as long as they are
2276only single-character literals. The lexical analyzer @code{yylex} passes
9d9b8b70 2277back all nonnumeric characters as tokens, so new grammar rules suffice for
bfa74976
RS
2278adding a new operator. But we want something more flexible: built-in
2279functions whose syntax has this form:
2280
2281@example
2282@var{function_name} (@var{argument})
2283@end example
2284
2285@noindent
2286At the same time, we will add memory to the calculator, by allowing you
2287to create named variables, store values in them, and use them later.
2288Here is a sample session with the multi-function calculator:
2289
2290@example
9edcd895
AD
2291$ @kbd{mfcalc}
2292@kbd{pi = 3.141592653589}
bfa74976 22933.1415926536
9edcd895 2294@kbd{sin(pi)}
bfa74976 22950.0000000000
9edcd895 2296@kbd{alpha = beta1 = 2.3}
bfa74976 22972.3000000000
9edcd895 2298@kbd{alpha}
bfa74976 22992.3000000000
9edcd895 2300@kbd{ln(alpha)}
bfa74976 23010.8329091229
9edcd895 2302@kbd{exp(ln(beta1))}
bfa74976 23032.3000000000
9edcd895 2304$
bfa74976
RS
2305@end example
2306
2307Note that multiple assignment and nested function calls are permitted.
2308
2309@menu
f5f419de
DJ
2310* Mfcalc Declarations:: Bison declarations for multi-function calculator.
2311* Mfcalc Rules:: Grammar rules for the calculator.
2312* Mfcalc Symbol Table:: Symbol table management subroutines.
bfa74976
RS
2313@end menu
2314
f5f419de 2315@node Mfcalc Declarations
bfa74976
RS
2316@subsection Declarations for @code{mfcalc}
2317
2318Here are the C and Bison declarations for the multi-function calculator.
2319
2320@smallexample
18b519c0 2321@group
bfa74976 2322%@{
38a92d50
PE
2323 #include <math.h> /* For math functions, cos(), sin(), etc. */
2324 #include "calc.h" /* Contains definition of `symrec'. */
2325 int yylex (void);
2326 void yyerror (char const *);
bfa74976 2327%@}
18b519c0
AD
2328@end group
2329@group
bfa74976 2330%union @{
38a92d50
PE
2331 double val; /* For returning numbers. */
2332 symrec *tptr; /* For returning symbol-table pointers. */
bfa74976 2333@}
18b519c0 2334@end group
38a92d50
PE
2335%token <val> NUM /* Simple double precision number. */
2336%token <tptr> VAR FNCT /* Variable and Function. */
bfa74976
RS
2337%type <val> exp
2338
18b519c0 2339@group
bfa74976
RS
2340%right '='
2341%left '-' '+'
2342%left '*' '/'
d78f0ac9
AD
2343%precedence NEG /* negation--unary minus */
2344%right '^' /* exponentiation */
18b519c0 2345@end group
38a92d50 2346%% /* The grammar follows. */
bfa74976
RS
2347@end smallexample
2348
2349The above grammar introduces only two new features of the Bison language.
2350These features allow semantic values to have various data types
2351(@pxref{Multiple Types, ,More Than One Value Type}).
2352
2353The @code{%union} declaration specifies the entire list of possible types;
2354this is instead of defining @code{YYSTYPE}. The allowable types are now
2355double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
2356the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
2357
2358Since values can now have various types, it is necessary to associate a
2359type with each grammar symbol whose semantic value is used. These symbols
2360are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
2361declarations are augmented with information about their data type (placed
2362between angle brackets).
2363
704a47c4
AD
2364The Bison construct @code{%type} is used for declaring nonterminal
2365symbols, just as @code{%token} is used for declaring token types. We
2366have not used @code{%type} before because nonterminal symbols are
2367normally declared implicitly by the rules that define them. But
2368@code{exp} must be declared explicitly so we can specify its value type.
2369@xref{Type Decl, ,Nonterminal Symbols}.
bfa74976 2370
342b8b6e 2371@node Mfcalc Rules
bfa74976
RS
2372@subsection Grammar Rules for @code{mfcalc}
2373
2374Here are the grammar rules for the multi-function calculator.
2375Most of them are copied directly from @code{calc}; three rules,
2376those which mention @code{VAR} or @code{FNCT}, are new.
2377
2378@smallexample
18b519c0 2379@group
bfa74976
RS
2380input: /* empty */
2381 | input line
2382;
18b519c0 2383@end group
bfa74976 2384
18b519c0 2385@group
bfa74976
RS
2386line:
2387 '\n'
2388 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
2389 | error '\n' @{ yyerrok; @}
2390;
18b519c0 2391@end group
bfa74976 2392
18b519c0 2393@group
bfa74976
RS
2394exp: NUM @{ $$ = $1; @}
2395 | VAR @{ $$ = $1->value.var; @}
2396 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
2397 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
2398 | exp '+' exp @{ $$ = $1 + $3; @}
2399 | exp '-' exp @{ $$ = $1 - $3; @}
2400 | exp '*' exp @{ $$ = $1 * $3; @}
2401 | exp '/' exp @{ $$ = $1 / $3; @}
2402 | '-' exp %prec NEG @{ $$ = -$2; @}
2403 | exp '^' exp @{ $$ = pow ($1, $3); @}
2404 | '(' exp ')' @{ $$ = $2; @}
2405;
18b519c0 2406@end group
38a92d50 2407/* End of grammar. */
bfa74976
RS
2408%%
2409@end smallexample
2410
f5f419de 2411@node Mfcalc Symbol Table
bfa74976
RS
2412@subsection The @code{mfcalc} Symbol Table
2413@cindex symbol table example
2414
2415The multi-function calculator requires a symbol table to keep track of the
2416names and meanings of variables and functions. This doesn't affect the
2417grammar rules (except for the actions) or the Bison declarations, but it
2418requires some additional C functions for support.
2419
2420The symbol table itself consists of a linked list of records. Its
2421definition, which is kept in the header @file{calc.h}, is as follows. It
2422provides for either functions or variables to be placed in the table.
2423
2424@smallexample
2425@group
38a92d50 2426/* Function type. */
32dfccf8 2427typedef double (*func_t) (double);
72f889cc 2428@end group
32dfccf8 2429
72f889cc 2430@group
38a92d50 2431/* Data type for links in the chain of symbols. */
bfa74976
RS
2432struct symrec
2433@{
38a92d50 2434 char *name; /* name of symbol */
bfa74976 2435 int type; /* type of symbol: either VAR or FNCT */
32dfccf8
AD
2436 union
2437 @{
38a92d50
PE
2438 double var; /* value of a VAR */
2439 func_t fnctptr; /* value of a FNCT */
bfa74976 2440 @} value;
38a92d50 2441 struct symrec *next; /* link field */
bfa74976
RS
2442@};
2443@end group
2444
2445@group
2446typedef struct symrec symrec;
2447
38a92d50 2448/* The symbol table: a chain of `struct symrec'. */
bfa74976
RS
2449extern symrec *sym_table;
2450
a730d142 2451symrec *putsym (char const *, int);
38a92d50 2452symrec *getsym (char const *);
bfa74976
RS
2453@end group
2454@end smallexample
2455
2456The new version of @code{main} includes a call to @code{init_table}, a
2457function that initializes the symbol table. Here it is, and
2458@code{init_table} as well:
2459
2460@smallexample
bfa74976
RS
2461#include <stdio.h>
2462
18b519c0 2463@group
38a92d50 2464/* Called by yyparse on error. */
13863333 2465void
38a92d50 2466yyerror (char const *s)
bfa74976
RS
2467@{
2468 printf ("%s\n", s);
2469@}
18b519c0 2470@end group
bfa74976 2471
18b519c0 2472@group
bfa74976
RS
2473struct init
2474@{
38a92d50
PE
2475 char const *fname;
2476 double (*fnct) (double);
bfa74976
RS
2477@};
2478@end group
2479
2480@group
38a92d50 2481struct init const arith_fncts[] =
13863333 2482@{
32dfccf8
AD
2483 "sin", sin,
2484 "cos", cos,
13863333 2485 "atan", atan,
32dfccf8
AD
2486 "ln", log,
2487 "exp", exp,
13863333
AD
2488 "sqrt", sqrt,
2489 0, 0
2490@};
18b519c0 2491@end group
bfa74976 2492
18b519c0 2493@group
bfa74976 2494/* The symbol table: a chain of `struct symrec'. */
38a92d50 2495symrec *sym_table;
bfa74976
RS
2496@end group
2497
2498@group
72d2299c 2499/* Put arithmetic functions in table. */
13863333
AD
2500void
2501init_table (void)
bfa74976
RS
2502@{
2503 int i;
2504 symrec *ptr;
2505 for (i = 0; arith_fncts[i].fname != 0; i++)
2506 @{
2507 ptr = putsym (arith_fncts[i].fname, FNCT);
2508 ptr->value.fnctptr = arith_fncts[i].fnct;
2509 @}
2510@}
2511@end group
38a92d50
PE
2512
2513@group
2514int
2515main (void)
2516@{
2517 init_table ();
2518 return yyparse ();
2519@}
2520@end group
bfa74976
RS
2521@end smallexample
2522
2523By simply editing the initialization list and adding the necessary include
2524files, you can add additional functions to the calculator.
2525
2526Two important functions allow look-up and installation of symbols in the
2527symbol table. The function @code{putsym} is passed a name and the type
2528(@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2529linked to the front of the list, and a pointer to the object is returned.
2530The function @code{getsym} is passed the name of the symbol to look up. If
2531found, a pointer to that symbol is returned; otherwise zero is returned.
2532
2533@smallexample
2534symrec *
38a92d50 2535putsym (char const *sym_name, int sym_type)
bfa74976
RS
2536@{
2537 symrec *ptr;
2538 ptr = (symrec *) malloc (sizeof (symrec));
2539 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2540 strcpy (ptr->name,sym_name);
2541 ptr->type = sym_type;
72d2299c 2542 ptr->value.var = 0; /* Set value to 0 even if fctn. */
bfa74976
RS
2543 ptr->next = (struct symrec *)sym_table;
2544 sym_table = ptr;
2545 return ptr;
2546@}
2547
2548symrec *
38a92d50 2549getsym (char const *sym_name)
bfa74976
RS
2550@{
2551 symrec *ptr;
2552 for (ptr = sym_table; ptr != (symrec *) 0;
2553 ptr = (symrec *)ptr->next)
2554 if (strcmp (ptr->name,sym_name) == 0)
2555 return ptr;
2556 return 0;
2557@}
2558@end smallexample
2559
2560The function @code{yylex} must now recognize variables, numeric values, and
2561the single-character arithmetic operators. Strings of alphanumeric
9d9b8b70 2562characters with a leading letter are recognized as either variables or
bfa74976
RS
2563functions depending on what the symbol table says about them.
2564
2565The string is passed to @code{getsym} for look up in the symbol table. If
2566the name appears in the table, a pointer to its location and its type
2567(@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2568already in the table, then it is installed as a @code{VAR} using
2569@code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
e0c471a9 2570returned to @code{yyparse}.
bfa74976
RS
2571
2572No change is needed in the handling of numeric values and arithmetic
2573operators in @code{yylex}.
2574
2575@smallexample
2576@group
2577#include <ctype.h>
18b519c0 2578@end group
13863333 2579
18b519c0 2580@group
13863333
AD
2581int
2582yylex (void)
bfa74976
RS
2583@{
2584 int c;
2585
72d2299c 2586 /* Ignore white space, get first nonwhite character. */
bfa74976
RS
2587 while ((c = getchar ()) == ' ' || c == '\t');
2588
2589 if (c == EOF)
2590 return 0;
2591@end group
2592
2593@group
2594 /* Char starts a number => parse the number. */
2595 if (c == '.' || isdigit (c))
2596 @{
2597 ungetc (c, stdin);
2598 scanf ("%lf", &yylval.val);
2599 return NUM;
2600 @}
2601@end group
2602
2603@group
2604 /* Char starts an identifier => read the name. */
2605 if (isalpha (c))
2606 @{
2607 symrec *s;
2608 static char *symbuf = 0;
2609 static int length = 0;
2610 int i;
2611@end group
2612
2613@group
2614 /* Initially make the buffer long enough
2615 for a 40-character symbol name. */
2616 if (length == 0)
2617 length = 40, symbuf = (char *)malloc (length + 1);
2618
2619 i = 0;
2620 do
2621@end group
2622@group
2623 @{
2624 /* If buffer is full, make it bigger. */
2625 if (i == length)
2626 @{
2627 length *= 2;
18b519c0 2628 symbuf = (char *) realloc (symbuf, length + 1);
bfa74976
RS
2629 @}
2630 /* Add this character to the buffer. */
2631 symbuf[i++] = c;
2632 /* Get another character. */
2633 c = getchar ();
2634 @}
2635@end group
2636@group
72d2299c 2637 while (isalnum (c));
bfa74976
RS
2638
2639 ungetc (c, stdin);
2640 symbuf[i] = '\0';
2641@end group
2642
2643@group
2644 s = getsym (symbuf);
2645 if (s == 0)
2646 s = putsym (symbuf, VAR);
2647 yylval.tptr = s;
2648 return s->type;
2649 @}
2650
2651 /* Any other character is a token by itself. */
2652 return c;
2653@}
2654@end group
2655@end smallexample
2656
72d2299c 2657This program is both powerful and flexible. You may easily add new
704a47c4
AD
2658functions, and it is a simple job to modify this code to install
2659predefined variables such as @code{pi} or @code{e} as well.
bfa74976 2660
342b8b6e 2661@node Exercises
bfa74976
RS
2662@section Exercises
2663@cindex exercises
2664
2665@enumerate
2666@item
2667Add some new functions from @file{math.h} to the initialization list.
2668
2669@item
2670Add another array that contains constants and their values. Then
2671modify @code{init_table} to add these constants to the symbol table.
2672It will be easiest to give the constants type @code{VAR}.
2673
2674@item
2675Make the program report an error if the user refers to an
2676uninitialized variable in any way except to store a value in it.
2677@end enumerate
2678
342b8b6e 2679@node Grammar File
bfa74976
RS
2680@chapter Bison Grammar Files
2681
2682Bison takes as input a context-free grammar specification and produces a
2683C-language function that recognizes correct instances of the grammar.
2684
ff7571c0 2685The Bison grammar file conventionally has a name ending in @samp{.y}.
234a3be3 2686@xref{Invocation, ,Invoking Bison}.
bfa74976
RS
2687
2688@menu
2689* Grammar Outline:: Overall layout of the grammar file.
2690* Symbols:: Terminal and nonterminal symbols.
2691* Rules:: How to write grammar rules.
2692* Recursion:: Writing recursive rules.
2693* Semantics:: Semantic values and actions.
847bf1f5 2694* Locations:: Locations and actions.
bfa74976
RS
2695* Declarations:: All kinds of Bison declarations are described here.
2696* Multiple Parsers:: Putting more than one Bison parser in one program.
2697@end menu
2698
342b8b6e 2699@node Grammar Outline
bfa74976
RS
2700@section Outline of a Bison Grammar
2701
2702A Bison grammar file has four main sections, shown here with the
2703appropriate delimiters:
2704
2705@example
2706%@{
38a92d50 2707 @var{Prologue}
bfa74976
RS
2708%@}
2709
2710@var{Bison declarations}
2711
2712%%
2713@var{Grammar rules}
2714%%
2715
75f5aaea 2716@var{Epilogue}
bfa74976
RS
2717@end example
2718
2719Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
8a4281b9 2720As a GNU extension, @samp{//} introduces a comment that
2bfc2e2a 2721continues until end of line.
bfa74976
RS
2722
2723@menu
f5f419de 2724* Prologue:: Syntax and usage of the prologue.
2cbe6b7f 2725* Prologue Alternatives:: Syntax and usage of alternatives to the prologue.
f5f419de
DJ
2726* Bison Declarations:: Syntax and usage of the Bison declarations section.
2727* Grammar Rules:: Syntax and usage of the grammar rules section.
2728* Epilogue:: Syntax and usage of the epilogue.
bfa74976
RS
2729@end menu
2730
38a92d50 2731@node Prologue
75f5aaea
MA
2732@subsection The prologue
2733@cindex declarations section
2734@cindex Prologue
2735@cindex declarations
bfa74976 2736
f8e1c9e5
AD
2737The @var{Prologue} section contains macro definitions and declarations
2738of functions and variables that are used in the actions in the grammar
ff7571c0
JD
2739rules. These are copied to the beginning of the parser implementation
2740file so that they precede the definition of @code{yyparse}. You can
2741use @samp{#include} to get the declarations from a header file. If
2742you don't need any C declarations, you may omit the @samp{%@{} and
f8e1c9e5 2743@samp{%@}} delimiters that bracket this section.
bfa74976 2744
9c437126 2745The @var{Prologue} section is terminated by the first occurrence
287c78f6
PE
2746of @samp{%@}} that is outside a comment, a string literal, or a
2747character constant.
2748
c732d2c6
AD
2749You may have more than one @var{Prologue} section, intermixed with the
2750@var{Bison declarations}. This allows you to have C and Bison
2751declarations that refer to each other. For example, the @code{%union}
2752declaration may use types defined in a header file, and you may wish to
2753prototype functions that take arguments of type @code{YYSTYPE}. This
2754can be done with two @var{Prologue} blocks, one before and one after the
2755@code{%union} declaration.
2756
2757@smallexample
2758%@{
aef3da86 2759 #define _GNU_SOURCE
38a92d50
PE
2760 #include <stdio.h>
2761 #include "ptypes.h"
c732d2c6
AD
2762%@}
2763
2764%union @{
779e7ceb 2765 long int n;
c732d2c6
AD
2766 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2767@}
2768
2769%@{
38a92d50
PE
2770 static void print_token_value (FILE *, int, YYSTYPE);
2771 #define YYPRINT(F, N, L) print_token_value (F, N, L)
c732d2c6
AD
2772%@}
2773
2774@dots{}
2775@end smallexample
2776
aef3da86
PE
2777When in doubt, it is usually safer to put prologue code before all
2778Bison declarations, rather than after. For example, any definitions
2779of feature test macros like @code{_GNU_SOURCE} or
2780@code{_POSIX_C_SOURCE} should appear before all Bison declarations, as
2781feature test macros can affect the behavior of Bison-generated
2782@code{#include} directives.
2783
2cbe6b7f
JD
2784@node Prologue Alternatives
2785@subsection Prologue Alternatives
2786@cindex Prologue Alternatives
2787
136a0f76 2788@findex %code
16dc6a9e
JD
2789@findex %code requires
2790@findex %code provides
2791@findex %code top
85894313 2792
2cbe6b7f 2793The functionality of @var{Prologue} sections can often be subtle and
ff7571c0
JD
2794inflexible. As an alternative, Bison provides a @code{%code}
2795directive with an explicit qualifier field, which identifies the
2796purpose of the code and thus the location(s) where Bison should
2797generate it. For C/C++, the qualifier can be omitted for the default
2798location, or it can be one of @code{requires}, @code{provides},
2799@code{top}. @xref{Decl Summary,,%code}.
2cbe6b7f
JD
2800
2801Look again at the example of the previous section:
2802
2803@smallexample
2804%@{
2805 #define _GNU_SOURCE
2806 #include <stdio.h>
2807 #include "ptypes.h"
2808%@}
2809
2810%union @{
2811 long int n;
2812 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2813@}
2814
2815%@{
2816 static void print_token_value (FILE *, int, YYSTYPE);
2817 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2818%@}
2819
2820@dots{}
2821@end smallexample
2822
2823@noindent
ff7571c0
JD
2824Notice that there are two @var{Prologue} sections here, but there's a
2825subtle distinction between their functionality. For example, if you
2826decide to override Bison's default definition for @code{YYLTYPE}, in
2827which @var{Prologue} section should you write your new definition?
2828You should write it in the first since Bison will insert that code
2829into the parser implementation file @emph{before} the default
2830@code{YYLTYPE} definition. In which @var{Prologue} section should you
2831prototype an internal function, @code{trace_token}, that accepts
2832@code{YYLTYPE} and @code{yytokentype} as arguments? You should
2833prototype it in the second since Bison will insert that code
2cbe6b7f
JD
2834@emph{after} the @code{YYLTYPE} and @code{yytokentype} definitions.
2835
2836This distinction in functionality between the two @var{Prologue} sections is
2837established by the appearance of the @code{%union} between them.
a501eca9 2838This behavior raises a few questions.
2cbe6b7f
JD
2839First, why should the position of a @code{%union} affect definitions related to
2840@code{YYLTYPE} and @code{yytokentype}?
2841Second, what if there is no @code{%union}?
2842In that case, the second kind of @var{Prologue} section is not available.
2843This behavior is not intuitive.
2844
8e0a5e9e 2845To avoid this subtle @code{%union} dependency, rewrite the example using a
16dc6a9e 2846@code{%code top} and an unqualified @code{%code}.
2cbe6b7f
JD
2847Let's go ahead and add the new @code{YYLTYPE} definition and the
2848@code{trace_token} prototype at the same time:
2849
2850@smallexample
16dc6a9e 2851%code top @{
2cbe6b7f
JD
2852 #define _GNU_SOURCE
2853 #include <stdio.h>
8e0a5e9e
JD
2854
2855 /* WARNING: The following code really belongs
16dc6a9e 2856 * in a `%code requires'; see below. */
8e0a5e9e 2857
2cbe6b7f
JD
2858 #include "ptypes.h"
2859 #define YYLTYPE YYLTYPE
2860 typedef struct YYLTYPE
2861 @{
2862 int first_line;
2863 int first_column;
2864 int last_line;
2865 int last_column;
2866 char *filename;
2867 @} YYLTYPE;
2868@}
2869
2870%union @{
2871 long int n;
2872 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2873@}
2874
2875%code @{
2876 static void print_token_value (FILE *, int, YYSTYPE);
2877 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2878 static void trace_token (enum yytokentype token, YYLTYPE loc);
2879@}
2880
2881@dots{}
2882@end smallexample
2883
2884@noindent
16dc6a9e
JD
2885In this way, @code{%code top} and the unqualified @code{%code} achieve the same
2886functionality as the two kinds of @var{Prologue} sections, but it's always
8e0a5e9e 2887explicit which kind you intend.
2cbe6b7f
JD
2888Moreover, both kinds are always available even in the absence of @code{%union}.
2889
ff7571c0
JD
2890The @code{%code top} block above logically contains two parts. The
2891first two lines before the warning need to appear near the top of the
2892parser implementation file. The first line after the warning is
2893required by @code{YYSTYPE} and thus also needs to appear in the parser
2894implementation file. However, if you've instructed Bison to generate
2895a parser header file (@pxref{Decl Summary, ,%defines}), you probably
2896want that line to appear before the @code{YYSTYPE} definition in that
2897header file as well. The @code{YYLTYPE} definition should also appear
2898in the parser header file to override the default @code{YYLTYPE}
2899definition there.
2cbe6b7f 2900
16dc6a9e 2901In other words, in the @code{%code top} block above, all but the first two
8e0a5e9e
JD
2902lines are dependency code required by the @code{YYSTYPE} and @code{YYLTYPE}
2903definitions.
16dc6a9e 2904Thus, they belong in one or more @code{%code requires}:
9bc0dd67
JD
2905
2906@smallexample
16dc6a9e 2907%code top @{
2cbe6b7f
JD
2908 #define _GNU_SOURCE
2909 #include <stdio.h>
2910@}
2911
16dc6a9e 2912%code requires @{
9bc0dd67
JD
2913 #include "ptypes.h"
2914@}
2915%union @{
2916 long int n;
2917 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2918@}
2919
16dc6a9e 2920%code requires @{
2cbe6b7f
JD
2921 #define YYLTYPE YYLTYPE
2922 typedef struct YYLTYPE
2923 @{
2924 int first_line;
2925 int first_column;
2926 int last_line;
2927 int last_column;
2928 char *filename;
2929 @} YYLTYPE;
2930@}
2931
136a0f76 2932%code @{
2cbe6b7f
JD
2933 static void print_token_value (FILE *, int, YYSTYPE);
2934 #define YYPRINT(F, N, L) print_token_value (F, N, L)
2935 static void trace_token (enum yytokentype token, YYLTYPE loc);
2936@}
2937
2938@dots{}
2939@end smallexample
2940
2941@noindent
ff7571c0
JD
2942Now Bison will insert @code{#include "ptypes.h"} and the new
2943@code{YYLTYPE} definition before the Bison-generated @code{YYSTYPE}
2944and @code{YYLTYPE} definitions in both the parser implementation file
2945and the parser header file. (By the same reasoning, @code{%code
2946requires} would also be the appropriate place to write your own
2947definition for @code{YYSTYPE}.)
2948
2949When you are writing dependency code for @code{YYSTYPE} and
2950@code{YYLTYPE}, you should prefer @code{%code requires} over
2951@code{%code top} regardless of whether you instruct Bison to generate
2952a parser header file. When you are writing code that you need Bison
2953to insert only into the parser implementation file and that has no
2954special need to appear at the top of that file, you should prefer the
2955unqualified @code{%code} over @code{%code top}. These practices will
2956make the purpose of each block of your code explicit to Bison and to
2957other developers reading your grammar file. Following these
2958practices, we expect the unqualified @code{%code} and @code{%code
2959requires} to be the most important of the four @var{Prologue}
16dc6a9e 2960alternatives.
a501eca9 2961
ff7571c0
JD
2962At some point while developing your parser, you might decide to
2963provide @code{trace_token} to modules that are external to your
2964parser. Thus, you might wish for Bison to insert the prototype into
2965both the parser header file and the parser implementation file. Since
2966this function is not a dependency required by @code{YYSTYPE} or
8e0a5e9e 2967@code{YYLTYPE}, it doesn't make sense to move its prototype to a
ff7571c0
JD
2968@code{%code requires}. More importantly, since it depends upon
2969@code{YYLTYPE} and @code{yytokentype}, @code{%code requires} is not
2970sufficient. Instead, move its prototype from the unqualified
2971@code{%code} to a @code{%code provides}:
2cbe6b7f
JD
2972
2973@smallexample
16dc6a9e 2974%code top @{
2cbe6b7f 2975 #define _GNU_SOURCE
136a0f76 2976 #include <stdio.h>
2cbe6b7f 2977@}
136a0f76 2978
16dc6a9e 2979%code requires @{
2cbe6b7f
JD
2980 #include "ptypes.h"
2981@}
2982%union @{
2983 long int n;
2984 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2985@}
2986
16dc6a9e 2987%code requires @{
2cbe6b7f
JD
2988 #define YYLTYPE YYLTYPE
2989 typedef struct YYLTYPE
2990 @{
2991 int first_line;
2992 int first_column;
2993 int last_line;
2994 int last_column;
2995 char *filename;
2996 @} YYLTYPE;
2997@}
2998
16dc6a9e 2999%code provides @{
2cbe6b7f
JD
3000 void trace_token (enum yytokentype token, YYLTYPE loc);
3001@}
3002
3003%code @{
9bc0dd67
JD
3004 static void print_token_value (FILE *, int, YYSTYPE);
3005 #define YYPRINT(F, N, L) print_token_value (F, N, L)
34f98f46 3006@}
9bc0dd67
JD
3007
3008@dots{}
3009@end smallexample
3010
2cbe6b7f 3011@noindent
ff7571c0
JD
3012Bison will insert the @code{trace_token} prototype into both the
3013parser header file and the parser implementation file after the
3014definitions for @code{yytokentype}, @code{YYLTYPE}, and
3015@code{YYSTYPE}.
2cbe6b7f 3016
ff7571c0
JD
3017The above examples are careful to write directives in an order that
3018reflects the layout of the generated parser implementation and header
3019files: @code{%code top}, @code{%code requires}, @code{%code provides},
3020and then @code{%code}. While your grammar files may generally be
3021easier to read if you also follow this order, Bison does not require
3022it. Instead, Bison lets you choose an organization that makes sense
3023to you.
2cbe6b7f 3024
a501eca9 3025You may declare any of these directives multiple times in the grammar file.
2cbe6b7f
JD
3026In that case, Bison concatenates the contained code in declaration order.
3027This is the only way in which the position of one of these directives within
3028the grammar file affects its functionality.
3029
3030The result of the previous two properties is greater flexibility in how you may
3031organize your grammar file.
3032For example, you may organize semantic-type-related directives by semantic
3033type:
3034
3035@smallexample
16dc6a9e 3036%code requires @{ #include "type1.h" @}
2cbe6b7f
JD
3037%union @{ type1 field1; @}
3038%destructor @{ type1_free ($$); @} <field1>
3039%printer @{ type1_print ($$); @} <field1>
3040
16dc6a9e 3041%code requires @{ #include "type2.h" @}
2cbe6b7f
JD
3042%union @{ type2 field2; @}
3043%destructor @{ type2_free ($$); @} <field2>
3044%printer @{ type2_print ($$); @} <field2>
3045@end smallexample
3046
3047@noindent
3048You could even place each of the above directive groups in the rules section of
3049the grammar file next to the set of rules that uses the associated semantic
3050type.
61fee93e
JD
3051(In the rules section, you must terminate each of those directives with a
3052semicolon.)
2cbe6b7f
JD
3053And you don't have to worry that some directive (like a @code{%union}) in the
3054definitions section is going to adversely affect their functionality in some
3055counter-intuitive manner just because it comes first.
3056Such an organization is not possible using @var{Prologue} sections.
3057
a501eca9 3058This section has been concerned with explaining the advantages of the four
8e0a5e9e 3059@var{Prologue} alternatives over the original Yacc @var{Prologue}.
a501eca9
JD
3060However, in most cases when using these directives, you shouldn't need to
3061think about all the low-level ordering issues discussed here.
3062Instead, you should simply use these directives to label each block of your
3063code according to its purpose and let Bison handle the ordering.
3064@code{%code} is the most generic label.
16dc6a9e
JD
3065Move code to @code{%code requires}, @code{%code provides}, or @code{%code top}
3066as needed.
a501eca9 3067
342b8b6e 3068@node Bison Declarations
bfa74976
RS
3069@subsection The Bison Declarations Section
3070@cindex Bison declarations (introduction)
3071@cindex declarations, Bison (introduction)
3072
3073The @var{Bison declarations} section contains declarations that define
3074terminal and nonterminal symbols, specify precedence, and so on.
3075In some simple grammars you may not need any declarations.
3076@xref{Declarations, ,Bison Declarations}.
3077
342b8b6e 3078@node Grammar Rules
bfa74976
RS
3079@subsection The Grammar Rules Section
3080@cindex grammar rules section
3081@cindex rules section for grammar
3082
3083The @dfn{grammar rules} section contains one or more Bison grammar
3084rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
3085
3086There must always be at least one grammar rule, and the first
3087@samp{%%} (which precedes the grammar rules) may never be omitted even
3088if it is the first thing in the file.
3089
38a92d50 3090@node Epilogue
75f5aaea 3091@subsection The epilogue
bfa74976 3092@cindex additional C code section
75f5aaea 3093@cindex epilogue
bfa74976
RS
3094@cindex C code, section for additional
3095
ff7571c0
JD
3096The @var{Epilogue} is copied verbatim to the end of the parser
3097implementation file, just as the @var{Prologue} is copied to the
3098beginning. This is the most convenient place to put anything that you
3099want to have in the parser implementation file but which need not come
3100before the definition of @code{yyparse}. For example, the definitions
3101of @code{yylex} and @code{yyerror} often go here. Because C requires
3102functions to be declared before being used, you often need to declare
3103functions like @code{yylex} and @code{yyerror} in the Prologue, even
3104if you define them in the Epilogue. @xref{Interface, ,Parser
3105C-Language Interface}.
bfa74976
RS
3106
3107If the last section is empty, you may omit the @samp{%%} that separates it
3108from the grammar rules.
3109
f8e1c9e5
AD
3110The Bison parser itself contains many macros and identifiers whose names
3111start with @samp{yy} or @samp{YY}, so it is a good idea to avoid using
3112any such names (except those documented in this manual) in the epilogue
3113of the grammar file.
bfa74976 3114
342b8b6e 3115@node Symbols
bfa74976
RS
3116@section Symbols, Terminal and Nonterminal
3117@cindex nonterminal symbol
3118@cindex terminal symbol
3119@cindex token type
3120@cindex symbol
3121
3122@dfn{Symbols} in Bison grammars represent the grammatical classifications
3123of the language.
3124
3125A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
3126class of syntactically equivalent tokens. You use the symbol in grammar
3127rules to mean that a token in that class is allowed. The symbol is
3128represented in the Bison parser by a numeric code, and the @code{yylex}
f8e1c9e5
AD
3129function returns a token type code to indicate what kind of token has
3130been read. You don't need to know what the code value is; you can use
3131the symbol to stand for it.
bfa74976 3132
f8e1c9e5
AD
3133A @dfn{nonterminal symbol} stands for a class of syntactically
3134equivalent groupings. The symbol name is used in writing grammar rules.
3135By convention, it should be all lower case.
bfa74976 3136
82f3355e
JD
3137Symbol names can contain letters, underscores, periods, and non-initial
3138digits and dashes. Dashes in symbol names are a GNU extension, incompatible
3139with POSIX Yacc. Periods and dashes make symbol names less convenient to
3140use with named references, which require brackets around such names
3141(@pxref{Named References}). Terminal symbols that contain periods or dashes
3142make little sense: since they are not valid symbols (in most programming
3143languages) they are not exported as token names.
bfa74976 3144
931c7513 3145There are three ways of writing terminal symbols in the grammar:
bfa74976
RS
3146
3147@itemize @bullet
3148@item
3149A @dfn{named token type} is written with an identifier, like an
c827f760 3150identifier in C@. By convention, it should be all upper case. Each
bfa74976
RS
3151such name must be defined with a Bison declaration such as
3152@code{%token}. @xref{Token Decl, ,Token Type Names}.
3153
3154@item
3155@cindex character token
3156@cindex literal token
3157@cindex single-character literal
931c7513
RS
3158A @dfn{character token type} (or @dfn{literal character token}) is
3159written in the grammar using the same syntax used in C for character
3160constants; for example, @code{'+'} is a character token type. A
3161character token type doesn't need to be declared unless you need to
3162specify its semantic value data type (@pxref{Value Type, ,Data Types of
3163Semantic Values}), associativity, or precedence (@pxref{Precedence,
3164,Operator Precedence}).
bfa74976
RS
3165
3166By convention, a character token type is used only to represent a
3167token that consists of that particular character. Thus, the token
3168type @code{'+'} is used to represent the character @samp{+} as a
3169token. Nothing enforces this convention, but if you depart from it,
3170your program will confuse other readers.
3171
3172All the usual escape sequences used in character literals in C can be
3173used in Bison as well, but you must not use the null character as a
72d2299c
PE
3174character literal because its numeric code, zero, signifies
3175end-of-input (@pxref{Calling Convention, ,Calling Convention
2bfc2e2a
PE
3176for @code{yylex}}). Also, unlike standard C, trigraphs have no
3177special meaning in Bison character literals, nor is backslash-newline
3178allowed.
931c7513
RS
3179
3180@item
3181@cindex string token
3182@cindex literal string token
9ecbd125 3183@cindex multicharacter literal
931c7513
RS
3184A @dfn{literal string token} is written like a C string constant; for
3185example, @code{"<="} is a literal string token. A literal string token
3186doesn't need to be declared unless you need to specify its semantic
14ded682 3187value data type (@pxref{Value Type}), associativity, or precedence
931c7513
RS
3188(@pxref{Precedence}).
3189
3190You can associate the literal string token with a symbolic name as an
3191alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
3192Declarations}). If you don't do that, the lexical analyzer has to
3193retrieve the token number for the literal string token from the
3194@code{yytname} table (@pxref{Calling Convention}).
3195
c827f760 3196@strong{Warning}: literal string tokens do not work in Yacc.
931c7513
RS
3197
3198By convention, a literal string token is used only to represent a token
3199that consists of that particular string. Thus, you should use the token
3200type @code{"<="} to represent the string @samp{<=} as a token. Bison
9ecbd125 3201does not enforce this convention, but if you depart from it, people who
931c7513
RS
3202read your program will be confused.
3203
3204All the escape sequences used in string literals in C can be used in
92ac3705
PE
3205Bison as well, except that you must not use a null character within a
3206string literal. Also, unlike Standard C, trigraphs have no special
2bfc2e2a
PE
3207meaning in Bison string literals, nor is backslash-newline allowed. A
3208literal string token must contain two or more characters; for a token
3209containing just one character, use a character token (see above).
bfa74976
RS
3210@end itemize
3211
3212How you choose to write a terminal symbol has no effect on its
3213grammatical meaning. That depends only on where it appears in rules and
3214on when the parser function returns that symbol.
3215
72d2299c
PE
3216The value returned by @code{yylex} is always one of the terminal
3217symbols, except that a zero or negative value signifies end-of-input.
3218Whichever way you write the token type in the grammar rules, you write
3219it the same way in the definition of @code{yylex}. The numeric code
3220for a character token type is simply the positive numeric code of the
3221character, so @code{yylex} can use the identical value to generate the
3222requisite code, though you may need to convert it to @code{unsigned
3223char} to avoid sign-extension on hosts where @code{char} is signed.
ff7571c0
JD
3224Each named token type becomes a C macro in the parser implementation
3225file, so @code{yylex} can use the name to stand for the code. (This
3226is why periods don't make sense in terminal symbols.) @xref{Calling
3227Convention, ,Calling Convention for @code{yylex}}.
bfa74976
RS
3228
3229If @code{yylex} is defined in a separate file, you need to arrange for the
3230token-type macro definitions to be available there. Use the @samp{-d}
3231option when you run Bison, so that it will write these macro definitions
3232into a separate header file @file{@var{name}.tab.h} which you can include
3233in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
3234
72d2299c 3235If you want to write a grammar that is portable to any Standard C
9d9b8b70 3236host, you must use only nonnull character tokens taken from the basic
c827f760 3237execution character set of Standard C@. This set consists of the ten
72d2299c
PE
3238digits, the 52 lower- and upper-case English letters, and the
3239characters in the following C-language string:
3240
3241@example
3242"\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_@{|@}~"
3243@end example
3244
f8e1c9e5
AD
3245The @code{yylex} function and Bison must use a consistent character set
3246and encoding for character tokens. For example, if you run Bison in an
8a4281b9 3247ASCII environment, but then compile and run the resulting
f8e1c9e5 3248program in an environment that uses an incompatible character set like
8a4281b9
JD
3249EBCDIC, the resulting program may not work because the tables
3250generated by Bison will assume ASCII numeric values for
f8e1c9e5
AD
3251character tokens. It is standard practice for software distributions to
3252contain C source files that were generated by Bison in an
8a4281b9
JD
3253ASCII environment, so installers on platforms that are
3254incompatible with ASCII must rebuild those files before
f8e1c9e5 3255compiling them.
e966383b 3256
bfa74976
RS
3257The symbol @code{error} is a terminal symbol reserved for error recovery
3258(@pxref{Error Recovery}); you shouldn't use it for any other purpose.
23c5a174
AD
3259In particular, @code{yylex} should never return this value. The default
3260value of the error token is 256, unless you explicitly assigned 256 to
3261one of your tokens with a @code{%token} declaration.
bfa74976 3262
342b8b6e 3263@node Rules
bfa74976
RS
3264@section Syntax of Grammar Rules
3265@cindex rule syntax
3266@cindex grammar rule syntax
3267@cindex syntax of grammar rules
3268
3269A Bison grammar rule has the following general form:
3270
3271@example
e425e872 3272@group
bfa74976
RS
3273@var{result}: @var{components}@dots{}
3274 ;
e425e872 3275@end group
bfa74976
RS
3276@end example
3277
3278@noindent
9ecbd125 3279where @var{result} is the nonterminal symbol that this rule describes,
bfa74976 3280and @var{components} are various terminal and nonterminal symbols that
13863333 3281are put together by this rule (@pxref{Symbols}).
bfa74976
RS
3282
3283For example,
3284
3285@example
3286@group
3287exp: exp '+' exp
3288 ;
3289@end group
3290@end example
3291
3292@noindent
3293says that two groupings of type @code{exp}, with a @samp{+} token in between,
3294can be combined into a larger grouping of type @code{exp}.
3295
72d2299c
PE
3296White space in rules is significant only to separate symbols. You can add
3297extra white space as you wish.
bfa74976
RS
3298
3299Scattered among the components can be @var{actions} that determine
3300the semantics of the rule. An action looks like this:
3301
3302@example
3303@{@var{C statements}@}
3304@end example
3305
3306@noindent
287c78f6
PE
3307@cindex braced code
3308This is an example of @dfn{braced code}, that is, C code surrounded by
3309braces, much like a compound statement in C@. Braced code can contain
3310any sequence of C tokens, so long as its braces are balanced. Bison
3311does not check the braced code for correctness directly; it merely
ff7571c0
JD
3312copies the code to the parser implementation file, where the C
3313compiler can check it.
287c78f6
PE
3314
3315Within braced code, the balanced-brace count is not affected by braces
3316within comments, string literals, or character constants, but it is
3317affected by the C digraphs @samp{<%} and @samp{%>} that represent
3318braces. At the top level braced code must be terminated by @samp{@}}
3319and not by a digraph. Bison does not look for trigraphs, so if braced
3320code uses trigraphs you should ensure that they do not affect the
3321nesting of braces or the boundaries of comments, string literals, or
3322character constants.
3323
bfa74976
RS
3324Usually there is only one action and it follows the components.
3325@xref{Actions}.
3326
3327@findex |
3328Multiple rules for the same @var{result} can be written separately or can
3329be joined with the vertical-bar character @samp{|} as follows:
3330
bfa74976
RS
3331@example
3332@group
3333@var{result}: @var{rule1-components}@dots{}
3334 | @var{rule2-components}@dots{}
3335 @dots{}
3336 ;
3337@end group
3338@end example
bfa74976
RS
3339
3340@noindent
3341They are still considered distinct rules even when joined in this way.
3342
3343If @var{components} in a rule is empty, it means that @var{result} can
3344match the empty string. For example, here is how to define a
3345comma-separated sequence of zero or more @code{exp} groupings:
3346
3347@example
3348@group
3349expseq: /* empty */
3350 | expseq1
3351 ;
3352@end group
3353
3354@group
3355expseq1: exp
3356 | expseq1 ',' exp
3357 ;
3358@end group
3359@end example
3360
3361@noindent
3362It is customary to write a comment @samp{/* empty */} in each rule
3363with no components.
3364
342b8b6e 3365@node Recursion
bfa74976
RS
3366@section Recursive Rules
3367@cindex recursive rule
3368
f8e1c9e5
AD
3369A rule is called @dfn{recursive} when its @var{result} nonterminal
3370appears also on its right hand side. Nearly all Bison grammars need to
3371use recursion, because that is the only way to define a sequence of any
3372number of a particular thing. Consider this recursive definition of a
9ecbd125 3373comma-separated sequence of one or more expressions:
bfa74976
RS
3374
3375@example
3376@group
3377expseq1: exp
3378 | expseq1 ',' exp
3379 ;
3380@end group
3381@end example
3382
3383@cindex left recursion
3384@cindex right recursion
3385@noindent
3386Since the recursive use of @code{expseq1} is the leftmost symbol in the
3387right hand side, we call this @dfn{left recursion}. By contrast, here
3388the same construct is defined using @dfn{right recursion}:
3389
3390@example
3391@group
3392expseq1: exp
3393 | exp ',' expseq1
3394 ;
3395@end group
3396@end example
3397
3398@noindent
ec3bc396
AD
3399Any kind of sequence can be defined using either left recursion or right
3400recursion, but you should always use left recursion, because it can
3401parse a sequence of any number of elements with bounded stack space.
3402Right recursion uses up space on the Bison stack in proportion to the
3403number of elements in the sequence, because all the elements must be
3404shifted onto the stack before the rule can be applied even once.
3405@xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
3406of this.
bfa74976
RS
3407
3408@cindex mutual recursion
3409@dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
3410rule does not appear directly on its right hand side, but does appear
3411in rules for other nonterminals which do appear on its right hand
13863333 3412side.
bfa74976
RS
3413
3414For example:
3415
3416@example
3417@group
3418expr: primary
3419 | primary '+' primary
3420 ;
3421@end group
3422
3423@group
3424primary: constant
3425 | '(' expr ')'
3426 ;
3427@end group
3428@end example
3429
3430@noindent
3431defines two mutually-recursive nonterminals, since each refers to the
3432other.
3433
342b8b6e 3434@node Semantics
bfa74976
RS
3435@section Defining Language Semantics
3436@cindex defining language semantics
13863333 3437@cindex language semantics, defining
bfa74976
RS
3438
3439The grammar rules for a language determine only the syntax. The semantics
3440are determined by the semantic values associated with various tokens and
3441groupings, and by the actions taken when various groupings are recognized.
3442
3443For example, the calculator calculates properly because the value
3444associated with each expression is the proper number; it adds properly
3445because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
3446the numbers associated with @var{x} and @var{y}.
3447
3448@menu
3449* Value Type:: Specifying one data type for all semantic values.
3450* Multiple Types:: Specifying several alternative data types.
3451* Actions:: An action is the semantic definition of a grammar rule.
3452* Action Types:: Specifying data types for actions to operate on.
3453* Mid-Rule Actions:: Most actions go at the end of a rule.
3454 This says when, why and how to use the exceptional
3455 action in the middle of a rule.
d013372c 3456* Named References:: Using named references in actions.
bfa74976
RS
3457@end menu
3458
342b8b6e 3459@node Value Type
bfa74976
RS
3460@subsection Data Types of Semantic Values
3461@cindex semantic value type
3462@cindex value type, semantic
3463@cindex data types of semantic values
3464@cindex default data type
3465
3466In a simple program it may be sufficient to use the same data type for
3467the semantic values of all language constructs. This was true in the
8a4281b9 3468RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
1964ad8c 3469Notation Calculator}).
bfa74976 3470
ddc8ede1
PE
3471Bison normally uses the type @code{int} for semantic values if your
3472program uses the same data type for all language constructs. To
bfa74976
RS
3473specify some other type, define @code{YYSTYPE} as a macro, like this:
3474
3475@example
3476#define YYSTYPE double
3477@end example
3478
3479@noindent
50cce58e
PE
3480@code{YYSTYPE}'s replacement list should be a type name
3481that does not contain parentheses or square brackets.
342b8b6e 3482This macro definition must go in the prologue of the grammar file
75f5aaea 3483(@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
bfa74976 3484
342b8b6e 3485@node Multiple Types
bfa74976
RS
3486@subsection More Than One Value Type
3487
3488In most programs, you will need different data types for different kinds
3489of tokens and groupings. For example, a numeric constant may need type
f8e1c9e5
AD
3490@code{int} or @code{long int}, while a string constant needs type
3491@code{char *}, and an identifier might need a pointer to an entry in the
3492symbol table.
bfa74976
RS
3493
3494To use more than one data type for semantic values in one parser, Bison
3495requires you to do two things:
3496
3497@itemize @bullet
3498@item
ddc8ede1 3499Specify the entire collection of possible data types, either by using the
704a47c4 3500@code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
ddc8ede1
PE
3501Value Types}), or by using a @code{typedef} or a @code{#define} to
3502define @code{YYSTYPE} to be a union type whose member names are
3503the type tags.
bfa74976
RS
3504
3505@item
14ded682
AD
3506Choose one of those types for each symbol (terminal or nonterminal) for
3507which semantic values are used. This is done for tokens with the
3508@code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
3509and for groupings with the @code{%type} Bison declaration (@pxref{Type
3510Decl, ,Nonterminal Symbols}).
bfa74976
RS
3511@end itemize
3512
342b8b6e 3513@node Actions
bfa74976
RS
3514@subsection Actions
3515@cindex action
3516@vindex $$
3517@vindex $@var{n}
d013372c
AR
3518@vindex $@var{name}
3519@vindex $[@var{name}]
bfa74976
RS
3520
3521An action accompanies a syntactic rule and contains C code to be executed
3522each time an instance of that rule is recognized. The task of most actions
3523is to compute a semantic value for the grouping built by the rule from the
3524semantic values associated with tokens or smaller groupings.
3525
287c78f6
PE
3526An action consists of braced code containing C statements, and can be
3527placed at any position in the rule;
704a47c4
AD
3528it is executed at that position. Most rules have just one action at the
3529end of the rule, following all the components. Actions in the middle of
3530a rule are tricky and used only for special purposes (@pxref{Mid-Rule
3531Actions, ,Actions in Mid-Rule}).
bfa74976 3532
ff7571c0
JD
3533The C code in an action can refer to the semantic values of the
3534components matched by the rule with the construct @code{$@var{n}},
3535which stands for the value of the @var{n}th component. The semantic
3536value for the grouping being constructed is @code{$$}. In addition,
3537the semantic values of symbols can be accessed with the named
3538references construct @code{$@var{name}} or @code{$[@var{name}]}.
3539Bison translates both of these constructs into expressions of the
3540appropriate type when it copies the actions into the parser
3541implementation file. @code{$$} (or @code{$@var{name}}, when it stands
3542for the current grouping) is translated to a modifiable lvalue, so it
3543can be assigned to.
bfa74976
RS
3544
3545Here is a typical example:
3546
3547@example
3548@group
3549exp: @dots{}
3550 | exp '+' exp
3551 @{ $$ = $1 + $3; @}
3552@end group
3553@end example
3554
d013372c
AR
3555Or, in terms of named references:
3556
3557@example
3558@group
3559exp[result]: @dots{}
3560 | exp[left] '+' exp[right]
3561 @{ $result = $left + $right; @}
3562@end group
3563@end example
3564
bfa74976
RS
3565@noindent
3566This rule constructs an @code{exp} from two smaller @code{exp} groupings
3567connected by a plus-sign token. In the action, @code{$1} and @code{$3}
d013372c 3568(@code{$left} and @code{$right})
bfa74976
RS
3569refer to the semantic values of the two component @code{exp} groupings,
3570which are the first and third symbols on the right hand side of the rule.
d013372c
AR
3571The sum is stored into @code{$$} (@code{$result}) so that it becomes the
3572semantic value of
bfa74976
RS
3573the addition-expression just recognized by the rule. If there were a
3574useful semantic value associated with the @samp{+} token, it could be
e0c471a9 3575referred to as @code{$2}.
bfa74976 3576
d013372c
AR
3577@xref{Named References,,Using Named References}, for more information
3578about using the named references construct.
3579
3ded9a63
AD
3580Note that the vertical-bar character @samp{|} is really a rule
3581separator, and actions are attached to a single rule. This is a
3582difference with tools like Flex, for which @samp{|} stands for either
3583``or'', or ``the same action as that of the next rule''. In the
3584following example, the action is triggered only when @samp{b} is found:
3585
3586@example
3587@group
3588a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
3589@end group
3590@end example
3591
bfa74976
RS
3592@cindex default action
3593If you don't specify an action for a rule, Bison supplies a default:
72f889cc
AD
3594@w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule
3595becomes the value of the whole rule. Of course, the default action is
3596valid only if the two data types match. There is no meaningful default
3597action for an empty rule; every empty rule must have an explicit action
3598unless the rule's value does not matter.
bfa74976
RS
3599
3600@code{$@var{n}} with @var{n} zero or negative is allowed for reference
3601to tokens and groupings on the stack @emph{before} those that match the
3602current rule. This is a very risky practice, and to use it reliably
3603you must be certain of the context in which the rule is applied. Here
3604is a case in which you can use this reliably:
3605
3606@example
3607@group
3608foo: expr bar '+' expr @{ @dots{} @}
3609 | expr bar '-' expr @{ @dots{} @}
3610 ;
3611@end group
3612
3613@group
3614bar: /* empty */
3615 @{ previous_expr = $0; @}
3616 ;
3617@end group
3618@end example
3619
3620As long as @code{bar} is used only in the fashion shown here, @code{$0}
3621always refers to the @code{expr} which precedes @code{bar} in the
3622definition of @code{foo}.
3623
32c29292 3624@vindex yylval
742e4900 3625It is also possible to access the semantic value of the lookahead token, if
32c29292
JD
3626any, from a semantic action.
3627This semantic value is stored in @code{yylval}.
3628@xref{Action Features, ,Special Features for Use in Actions}.
3629
342b8b6e 3630@node Action Types
bfa74976
RS
3631@subsection Data Types of Values in Actions
3632@cindex action data types
3633@cindex data types in actions
3634
3635If you have chosen a single data type for semantic values, the @code{$$}
3636and @code{$@var{n}} constructs always have that data type.
3637
3638If you have used @code{%union} to specify a variety of data types, then you
3639must declare a choice among these types for each terminal or nonterminal
3640symbol that can have a semantic value. Then each time you use @code{$$} or
3641@code{$@var{n}}, its data type is determined by which symbol it refers to
e0c471a9 3642in the rule. In this example,
bfa74976
RS
3643
3644@example
3645@group
3646exp: @dots{}
3647 | exp '+' exp
3648 @{ $$ = $1 + $3; @}
3649@end group
3650@end example
3651
3652@noindent
3653@code{$1} and @code{$3} refer to instances of @code{exp}, so they all
3654have the data type declared for the nonterminal symbol @code{exp}. If
3655@code{$2} were used, it would have the data type declared for the
e0c471a9 3656terminal symbol @code{'+'}, whatever that might be.
bfa74976
RS
3657
3658Alternatively, you can specify the data type when you refer to the value,
3659by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
3660reference. For example, if you have defined types as shown here:
3661
3662@example
3663@group
3664%union @{
3665 int itype;
3666 double dtype;
3667@}
3668@end group
3669@end example
3670
3671@noindent
3672then you can write @code{$<itype>1} to refer to the first subunit of the
3673rule as an integer, or @code{$<dtype>1} to refer to it as a double.
3674
342b8b6e 3675@node Mid-Rule Actions
bfa74976
RS
3676@subsection Actions in Mid-Rule
3677@cindex actions in mid-rule
3678@cindex mid-rule actions
3679
3680Occasionally it is useful to put an action in the middle of a rule.
3681These actions are written just like usual end-of-rule actions, but they
3682are executed before the parser even recognizes the following components.
3683
3684A mid-rule action may refer to the components preceding it using
3685@code{$@var{n}}, but it may not refer to subsequent components because
3686it is run before they are parsed.
3687
3688The mid-rule action itself counts as one of the components of the rule.
3689This makes a difference when there is another action later in the same rule
3690(and usually there is another at the end): you have to count the actions
3691along with the symbols when working out which number @var{n} to use in
3692@code{$@var{n}}.
3693
3694The mid-rule action can also have a semantic value. The action can set
3695its value with an assignment to @code{$$}, and actions later in the rule
3696can refer to the value using @code{$@var{n}}. Since there is no symbol
3697to name the action, there is no way to declare a data type for the value
fdc6758b
MA
3698in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
3699specify a data type each time you refer to this value.
bfa74976
RS
3700
3701There is no way to set the value of the entire rule with a mid-rule
3702action, because assignments to @code{$$} do not have that effect. The
3703only way to set the value for the entire rule is with an ordinary action
3704at the end of the rule.
3705
3706Here is an example from a hypothetical compiler, handling a @code{let}
3707statement that looks like @samp{let (@var{variable}) @var{statement}} and
3708serves to create a variable named @var{variable} temporarily for the
3709duration of @var{statement}. To parse this construct, we must put
3710@var{variable} into the symbol table while @var{statement} is parsed, then
3711remove it afterward. Here is how it is done:
3712
3713@example
3714@group
3715stmt: LET '(' var ')'
3716 @{ $<context>$ = push_context ();
3717 declare_variable ($3); @}
3718 stmt @{ $$ = $6;
3719 pop_context ($<context>5); @}
3720@end group
3721@end example
3722
3723@noindent
3724As soon as @samp{let (@var{variable})} has been recognized, the first
3725action is run. It saves a copy of the current semantic context (the
3726list of accessible variables) as its semantic value, using alternative
3727@code{context} in the data-type union. Then it calls
3728@code{declare_variable} to add the new variable to that list. Once the
3729first action is finished, the embedded statement @code{stmt} can be
3730parsed. Note that the mid-rule action is component number 5, so the
3731@samp{stmt} is component number 6.
3732
3733After the embedded statement is parsed, its semantic value becomes the
3734value of the entire @code{let}-statement. Then the semantic value from the
3735earlier action is used to restore the prior list of variables. This
3736removes the temporary @code{let}-variable from the list so that it won't
3737appear to exist while the rest of the program is parsed.
3738
841a7737
JD
3739@findex %destructor
3740@cindex discarded symbols, mid-rule actions
3741@cindex error recovery, mid-rule actions
3742In the above example, if the parser initiates error recovery (@pxref{Error
3743Recovery}) while parsing the tokens in the embedded statement @code{stmt},
3744it might discard the previous semantic context @code{$<context>5} without
3745restoring it.
3746Thus, @code{$<context>5} needs a destructor (@pxref{Destructor Decl, , Freeing
3747Discarded Symbols}).
ec5479ce
JD
3748However, Bison currently provides no means to declare a destructor specific to
3749a particular mid-rule action's semantic value.
841a7737
JD
3750
3751One solution is to bury the mid-rule action inside a nonterminal symbol and to
3752declare a destructor for that symbol:
3753
3754@example
3755@group
3756%type <context> let
3757%destructor @{ pop_context ($$); @} let
3758
3759%%
3760
3761stmt: let stmt
3762 @{ $$ = $2;
3763 pop_context ($1); @}
3764 ;
3765
3766let: LET '(' var ')'
3767 @{ $$ = push_context ();
3768 declare_variable ($3); @}
3769 ;
3770
3771@end group
3772@end example
3773
3774@noindent
3775Note that the action is now at the end of its rule.
3776Any mid-rule action can be converted to an end-of-rule action in this way, and
3777this is what Bison actually does to implement mid-rule actions.
3778
bfa74976
RS
3779Taking action before a rule is completely recognized often leads to
3780conflicts since the parser must commit to a parse in order to execute the
3781action. For example, the following two rules, without mid-rule actions,
3782can coexist in a working parser because the parser can shift the open-brace
3783token and look at what follows before deciding whether there is a
3784declaration or not:
3785
3786@example
3787@group
3788compound: '@{' declarations statements '@}'
3789 | '@{' statements '@}'
3790 ;
3791@end group
3792@end example
3793
3794@noindent
3795But when we add a mid-rule action as follows, the rules become nonfunctional:
3796
3797@example
3798@group
3799compound: @{ prepare_for_local_variables (); @}
3800 '@{' declarations statements '@}'
3801@end group
3802@group
3803 | '@{' statements '@}'
3804 ;
3805@end group
3806@end example
3807
3808@noindent
3809Now the parser is forced to decide whether to run the mid-rule action
3810when it has read no farther than the open-brace. In other words, it
3811must commit to using one rule or the other, without sufficient
3812information to do it correctly. (The open-brace token is what is called
742e4900
JD
3813the @dfn{lookahead} token at this time, since the parser is still
3814deciding what to do about it. @xref{Lookahead, ,Lookahead Tokens}.)
bfa74976
RS
3815
3816You might think that you could correct the problem by putting identical
3817actions into the two rules, like this:
3818
3819@example
3820@group
3821compound: @{ prepare_for_local_variables (); @}
3822 '@{' declarations statements '@}'
3823 | @{ prepare_for_local_variables (); @}
3824 '@{' statements '@}'
3825 ;
3826@end group
3827@end example
3828
3829@noindent
3830But this does not help, because Bison does not realize that the two actions
3831are identical. (Bison never tries to understand the C code in an action.)
3832
3833If the grammar is such that a declaration can be distinguished from a
3834statement by the first token (which is true in C), then one solution which
3835does work is to put the action after the open-brace, like this:
3836
3837@example
3838@group
3839compound: '@{' @{ prepare_for_local_variables (); @}
3840 declarations statements '@}'
3841 | '@{' statements '@}'
3842 ;
3843@end group
3844@end example
3845
3846@noindent
3847Now the first token of the following declaration or statement,
3848which would in any case tell Bison which rule to use, can still do so.
3849
3850Another solution is to bury the action inside a nonterminal symbol which
3851serves as a subroutine:
3852
3853@example
3854@group
3855subroutine: /* empty */
3856 @{ prepare_for_local_variables (); @}
3857 ;
3858
3859@end group
3860
3861@group
3862compound: subroutine
3863 '@{' declarations statements '@}'
3864 | subroutine
3865 '@{' statements '@}'
3866 ;
3867@end group
3868@end example
3869
3870@noindent
3871Now Bison can execute the action in the rule for @code{subroutine} without
841a7737 3872deciding which rule for @code{compound} it will eventually use.
bfa74976 3873
d013372c
AR
3874@node Named References
3875@subsection Using Named References
3876@cindex named references
3877
3878While every semantic value can be accessed with positional references
3879@code{$@var{n}} and @code{$$}, it's often much more convenient to refer to
3880them by name. First of all, original symbol names may be used as named
3881references. For example:
3882
3883@example
3884@group
3885invocation: op '(' args ')'
3886 @{ $invocation = new_invocation ($op, $args, @@invocation); @}
3887@end group
3888@end example
3889
3890@noindent
3891The positional @code{$$}, @code{@@$}, @code{$n}, and @code{@@n} can be
3892mixed with @code{$name} and @code{@@name} arbitrarily. For example:
3893
3894@example
3895@group
3896invocation: op '(' args ')'
3897 @{ $$ = new_invocation ($op, $args, @@$); @}
3898@end group
3899@end example
3900
3901@noindent
3902However, sometimes regular symbol names are not sufficient due to
3903ambiguities:
3904
3905@example
3906@group
3907exp: exp '/' exp
3908 @{ $exp = $exp / $exp; @} // $exp is ambiguous.
3909
3910exp: exp '/' exp
3911 @{ $$ = $1 / $exp; @} // One usage is ambiguous.
3912
3913exp: exp '/' exp
3914 @{ $$ = $1 / $3; @} // No error.
3915@end group
3916@end example
3917
3918@noindent
3919When ambiguity occurs, explicitly declared names may be used for values and
3920locations. Explicit names are declared as a bracketed name after a symbol
3921appearance in rule definitions. For example:
3922@example
3923@group
3924exp[result]: exp[left] '/' exp[right]
3925 @{ $result = $left / $right; @}
3926@end group
3927@end example
3928
3929@noindent
3930Explicit names may be declared for RHS and for LHS symbols as well. In order
3931to access a semantic value generated by a mid-rule action, an explicit name
3932may also be declared by putting a bracketed name after the closing brace of
3933the mid-rule action code:
3934@example
3935@group
3936exp[res]: exp[x] '+' @{$left = $x;@}[left] exp[right]
3937 @{ $res = $left + $right; @}
3938@end group
3939@end example
3940
3941@noindent
3942
3943In references, in order to specify names containing dots and dashes, an explicit
3944bracketed syntax @code{$[name]} and @code{@@[name]} must be used:
3945@example
3946@group
3947if-stmt: IF '(' expr ')' THEN then.stmt ';'
3948 @{ $[if-stmt] = new_if_stmt ($expr, $[then.stmt]); @}
3949@end group
3950@end example
3951
3952It often happens that named references are followed by a dot, dash or other
3953C punctuation marks and operators. By default, Bison will read
3954@code{$name.suffix} as a reference to symbol value @code{$name} followed by
3955@samp{.suffix}, i.e., an access to the @samp{suffix} field of the semantic
3956value. In order to force Bison to recognize @code{name.suffix} in its entirety
3957as the name of a semantic value, bracketed syntax @code{$[name.suffix]}
3958must be used.
3959
3960
342b8b6e 3961@node Locations
847bf1f5
AD
3962@section Tracking Locations
3963@cindex location
95923bd6
AD
3964@cindex textual location
3965@cindex location, textual
847bf1f5
AD
3966
3967Though grammar rules and semantic actions are enough to write a fully
72d2299c 3968functional parser, it can be useful to process some additional information,
3e259915
MA
3969especially symbol locations.
3970
704a47c4
AD
3971The way locations are handled is defined by providing a data type, and
3972actions to take when rules are matched.
847bf1f5
AD
3973
3974@menu
3975* Location Type:: Specifying a data type for locations.
3976* Actions and Locations:: Using locations in actions.
3977* Location Default Action:: Defining a general way to compute locations.
3978@end menu
3979
342b8b6e 3980@node Location Type
847bf1f5
AD
3981@subsection Data Type of Locations
3982@cindex data type of locations
3983@cindex default location type
3984
3985Defining a data type for locations is much simpler than for semantic values,
3986since all tokens and groupings always use the same type.
3987
50cce58e
PE
3988You can specify the type of locations by defining a macro called
3989@code{YYLTYPE}, just as you can specify the semantic value type by
ddc8ede1 3990defining a @code{YYSTYPE} macro (@pxref{Value Type}).
847bf1f5
AD
3991When @code{YYLTYPE} is not defined, Bison uses a default structure type with
3992four members:
3993
3994@example
6273355b 3995typedef struct YYLTYPE
847bf1f5
AD
3996@{
3997 int first_line;
3998 int first_column;
3999 int last_line;
4000 int last_column;
6273355b 4001@} YYLTYPE;
847bf1f5
AD
4002@end example
4003
d59e456d
AD
4004When @code{YYLTYPE} is not defined, at the beginning of the parsing, Bison
4005initializes all these fields to 1 for @code{yylloc}. To initialize
4006@code{yylloc} with a custom location type (or to chose a different
4007initialization), use the @code{%initial-action} directive. @xref{Initial
4008Action Decl, , Performing Actions before Parsing}.
cd48d21d 4009
342b8b6e 4010@node Actions and Locations
847bf1f5
AD
4011@subsection Actions and Locations
4012@cindex location actions
4013@cindex actions, location
4014@vindex @@$
4015@vindex @@@var{n}
d013372c
AR
4016@vindex @@@var{name}
4017@vindex @@[@var{name}]
847bf1f5
AD
4018
4019Actions are not only useful for defining language semantics, but also for
4020describing the behavior of the output parser with locations.
4021
4022The most obvious way for building locations of syntactic groupings is very
72d2299c 4023similar to the way semantic values are computed. In a given rule, several
847bf1f5
AD
4024constructs can be used to access the locations of the elements being matched.
4025The location of the @var{n}th component of the right hand side is
4026@code{@@@var{n}}, while the location of the left hand side grouping is
4027@code{@@$}.
4028
d013372c
AR
4029In addition, the named references construct @code{@@@var{name}} and
4030@code{@@[@var{name}]} may also be used to address the symbol locations.
4031@xref{Named References,,Using Named References}, for more information
4032about using the named references construct.
4033
3e259915 4034Here is a basic example using the default data type for locations:
847bf1f5
AD
4035
4036@example
4037@group
4038exp: @dots{}
3e259915 4039 | exp '/' exp
847bf1f5 4040 @{
3e259915
MA
4041 @@$.first_column = @@1.first_column;
4042 @@$.first_line = @@1.first_line;
847bf1f5
AD
4043 @@$.last_column = @@3.last_column;
4044 @@$.last_line = @@3.last_line;
3e259915
MA
4045 if ($3)
4046 $$ = $1 / $3;
4047 else
4048 @{
4049 $$ = 1;
4e03e201
AD
4050 fprintf (stderr,
4051 "Division by zero, l%d,c%d-l%d,c%d",
4052 @@3.first_line, @@3.first_column,
4053 @@3.last_line, @@3.last_column);
3e259915 4054 @}
847bf1f5
AD
4055 @}
4056@end group
4057@end example
4058
3e259915 4059As for semantic values, there is a default action for locations that is
72d2299c 4060run each time a rule is matched. It sets the beginning of @code{@@$} to the
3e259915 4061beginning of the first symbol, and the end of @code{@@$} to the end of the
79282c6c 4062last symbol.
3e259915 4063
72d2299c 4064With this default action, the location tracking can be fully automatic. The
3e259915
MA
4065example above simply rewrites this way:
4066
4067@example
4068@group
4069exp: @dots{}
4070 | exp '/' exp
4071 @{
4072 if ($3)
4073 $$ = $1 / $3;
4074 else
4075 @{
4076 $$ = 1;
4e03e201
AD
4077 fprintf (stderr,
4078 "Division by zero, l%d,c%d-l%d,c%d",
4079 @@3.first_line, @@3.first_column,
4080 @@3.last_line, @@3.last_column);
3e259915
MA
4081 @}
4082 @}
4083@end group
4084@end example
847bf1f5 4085
32c29292 4086@vindex yylloc
742e4900 4087It is also possible to access the location of the lookahead token, if any,
32c29292
JD
4088from a semantic action.
4089This location is stored in @code{yylloc}.
4090@xref{Action Features, ,Special Features for Use in Actions}.
4091
342b8b6e 4092@node Location Default Action
847bf1f5
AD
4093@subsection Default Action for Locations
4094@vindex YYLLOC_DEFAULT
8a4281b9 4095@cindex GLR parsers and @code{YYLLOC_DEFAULT}
847bf1f5 4096
72d2299c 4097Actually, actions are not the best place to compute locations. Since
704a47c4
AD
4098locations are much more general than semantic values, there is room in
4099the output parser to redefine the default action to take for each
72d2299c 4100rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
96b93a3d
PE
4101matched, before the associated action is run. It is also invoked
4102while processing a syntax error, to compute the error's location.
8a4281b9 4103Before reporting an unresolvable syntactic ambiguity, a GLR
8710fc41
JD
4104parser invokes @code{YYLLOC_DEFAULT} recursively to compute the location
4105of that ambiguity.
847bf1f5 4106
3e259915 4107Most of the time, this macro is general enough to suppress location
79282c6c 4108dedicated code from semantic actions.
847bf1f5 4109
72d2299c 4110The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
96b93a3d 4111the location of the grouping (the result of the computation). When a
766de5eb 4112rule is matched, the second parameter identifies locations of
96b93a3d 4113all right hand side elements of the rule being matched, and the third
8710fc41 4114parameter is the size of the rule's right hand side.
8a4281b9 4115When a GLR parser reports an ambiguity, which of multiple candidate
8710fc41
JD
4116right hand sides it passes to @code{YYLLOC_DEFAULT} is undefined.
4117When processing a syntax error, the second parameter identifies locations
4118of the symbols that were discarded during error processing, and the third
96b93a3d 4119parameter is the number of discarded symbols.
847bf1f5 4120
766de5eb 4121By default, @code{YYLLOC_DEFAULT} is defined this way:
847bf1f5 4122
766de5eb 4123@smallexample
847bf1f5 4124@group
766de5eb
PE
4125# define YYLLOC_DEFAULT(Current, Rhs, N) \
4126 do \
4127 if (N) \
4128 @{ \
4129 (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
4130 (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
4131 (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
4132 (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
4133 @} \
4134 else \
4135 @{ \
4136 (Current).first_line = (Current).last_line = \
4137 YYRHSLOC(Rhs, 0).last_line; \
4138 (Current).first_column = (Current).last_column = \
4139 YYRHSLOC(Rhs, 0).last_column; \
4140 @} \
4141 while (0)
847bf1f5 4142@end group
766de5eb 4143@end smallexample
676385e2 4144
766de5eb
PE
4145where @code{YYRHSLOC (rhs, k)} is the location of the @var{k}th symbol
4146in @var{rhs} when @var{k} is positive, and the location of the symbol
f28ac696 4147just before the reduction when @var{k} and @var{n} are both zero.
676385e2 4148
3e259915 4149When defining @code{YYLLOC_DEFAULT}, you should consider that:
847bf1f5 4150
3e259915 4151@itemize @bullet
79282c6c 4152@item
72d2299c 4153All arguments are free of side-effects. However, only the first one (the
3e259915 4154result) should be modified by @code{YYLLOC_DEFAULT}.
847bf1f5 4155
3e259915 4156@item
766de5eb
PE
4157For consistency with semantic actions, valid indexes within the
4158right hand side range from 1 to @var{n}. When @var{n} is zero, only 0 is a
4159valid index, and it refers to the symbol just before the reduction.
4160During error processing @var{n} is always positive.
0ae99356
PE
4161
4162@item
4163Your macro should parenthesize its arguments, if need be, since the
4164actual arguments may not be surrounded by parentheses. Also, your
4165macro should expand to something that can be used as a single
4166statement when it is followed by a semicolon.
3e259915 4167@end itemize
847bf1f5 4168
342b8b6e 4169@node Declarations
bfa74976
RS
4170@section Bison Declarations
4171@cindex declarations, Bison
4172@cindex Bison declarations
4173
4174The @dfn{Bison declarations} section of a Bison grammar defines the symbols
4175used in formulating the grammar and the data types of semantic values.
4176@xref{Symbols}.
4177
4178All token type names (but not single-character literal tokens such as
4179@code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
4180declared if you need to specify which data type to use for the semantic
4181value (@pxref{Multiple Types, ,More Than One Value Type}).
4182
ff7571c0
JD
4183The first rule in the grammar file also specifies the start symbol, by
4184default. If you want some other symbol to be the start symbol, you
4185must declare it explicitly (@pxref{Language and Grammar, ,Languages
4186and Context-Free Grammars}).
bfa74976
RS
4187
4188@menu
b50d2359 4189* Require Decl:: Requiring a Bison version.
bfa74976
RS
4190* Token Decl:: Declaring terminal symbols.
4191* Precedence Decl:: Declaring terminals with precedence and associativity.
4192* Union Decl:: Declaring the set of all semantic value types.
4193* Type Decl:: Declaring the choice of type for a nonterminal symbol.
18d192f0 4194* Initial Action Decl:: Code run before parsing starts.
72f889cc 4195* Destructor Decl:: Declaring how symbols are freed.
d6328241 4196* Expect Decl:: Suppressing warnings about parsing conflicts.
bfa74976
RS
4197* Start Decl:: Specifying the start symbol.
4198* Pure Decl:: Requesting a reentrant parser.
9987d1b3 4199* Push Decl:: Requesting a push parser.
bfa74976
RS
4200* Decl Summary:: Table of all Bison declarations.
4201@end menu
4202
b50d2359
AD
4203@node Require Decl
4204@subsection Require a Version of Bison
4205@cindex version requirement
4206@cindex requiring a version of Bison
4207@findex %require
4208
4209You may require the minimum version of Bison to process the grammar. If
9b8a5ce0
AD
4210the requirement is not met, @command{bison} exits with an error (exit
4211status 63).
b50d2359
AD
4212
4213@example
4214%require "@var{version}"
4215@end example
4216
342b8b6e 4217@node Token Decl
bfa74976
RS
4218@subsection Token Type Names
4219@cindex declaring token type names
4220@cindex token type names, declaring
931c7513 4221@cindex declaring literal string tokens
bfa74976
RS
4222@findex %token
4223
4224The basic way to declare a token type name (terminal symbol) is as follows:
4225
4226@example
4227%token @var{name}
4228@end example
4229
4230Bison will convert this into a @code{#define} directive in
4231the parser, so that the function @code{yylex} (if it is in this file)
4232can use the name @var{name} to stand for this token type's code.
4233
d78f0ac9
AD
4234Alternatively, you can use @code{%left}, @code{%right},
4235@code{%precedence}, or
14ded682
AD
4236@code{%nonassoc} instead of @code{%token}, if you wish to specify
4237associativity and precedence. @xref{Precedence Decl, ,Operator
4238Precedence}.
bfa74976
RS
4239
4240You can explicitly specify the numeric code for a token type by appending
b1cc23c4 4241a nonnegative decimal or hexadecimal integer value in the field immediately
1452af69 4242following the token name:
bfa74976
RS
4243
4244@example
4245%token NUM 300
1452af69 4246%token XNUM 0x12d // a GNU extension
bfa74976
RS
4247@end example
4248
4249@noindent
4250It is generally best, however, to let Bison choose the numeric codes for
4251all token types. Bison will automatically select codes that don't conflict
e966383b 4252with each other or with normal characters.
bfa74976
RS
4253
4254In the event that the stack type is a union, you must augment the
4255@code{%token} or other token declaration to include the data type
704a47c4
AD
4256alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
4257Than One Value Type}).
bfa74976
RS
4258
4259For example:
4260
4261@example
4262@group
4263%union @{ /* define stack type */
4264 double val;
4265 symrec *tptr;
4266@}
4267%token <val> NUM /* define token NUM and its type */
4268@end group
4269@end example
4270
931c7513
RS
4271You can associate a literal string token with a token type name by
4272writing the literal string at the end of a @code{%token}
4273declaration which declares the name. For example:
4274
4275@example
4276%token arrow "=>"
4277@end example
4278
4279@noindent
4280For example, a grammar for the C language might specify these names with
4281equivalent literal string tokens:
4282
4283@example
4284%token <operator> OR "||"
4285%token <operator> LE 134 "<="
4286%left OR "<="
4287@end example
4288
4289@noindent
4290Once you equate the literal string and the token name, you can use them
4291interchangeably in further declarations or the grammar rules. The
4292@code{yylex} function can use the token name or the literal string to
4293obtain the token type code number (@pxref{Calling Convention}).
b1cc23c4
JD
4294Syntax error messages passed to @code{yyerror} from the parser will reference
4295the literal string instead of the token name.
4296
4297The token numbered as 0 corresponds to end of file; the following line
4298allows for nicer error messages referring to ``end of file'' instead
4299of ``$end'':
4300
4301@example
4302%token END 0 "end of file"
4303@end example
931c7513 4304
342b8b6e 4305@node Precedence Decl
bfa74976
RS
4306@subsection Operator Precedence
4307@cindex precedence declarations
4308@cindex declaring operator precedence
4309@cindex operator precedence, declaring
4310
d78f0ac9
AD
4311Use the @code{%left}, @code{%right}, @code{%nonassoc}, or
4312@code{%precedence} declaration to
bfa74976
RS
4313declare a token and specify its precedence and associativity, all at
4314once. These are called @dfn{precedence declarations}.
704a47c4
AD
4315@xref{Precedence, ,Operator Precedence}, for general information on
4316operator precedence.
bfa74976 4317
ab7f29f8 4318The syntax of a precedence declaration is nearly the same as that of
bfa74976
RS
4319@code{%token}: either
4320
4321@example
4322%left @var{symbols}@dots{}
4323@end example
4324
4325@noindent
4326or
4327
4328@example
4329%left <@var{type}> @var{symbols}@dots{}
4330@end example
4331
4332And indeed any of these declarations serves the purposes of @code{%token}.
4333But in addition, they specify the associativity and relative precedence for
4334all the @var{symbols}:
4335
4336@itemize @bullet
4337@item
4338The associativity of an operator @var{op} determines how repeated uses
4339of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
4340@var{z}} is parsed by grouping @var{x} with @var{y} first or by
4341grouping @var{y} with @var{z} first. @code{%left} specifies
4342left-associativity (grouping @var{x} with @var{y} first) and
4343@code{%right} specifies right-associativity (grouping @var{y} with
4344@var{z} first). @code{%nonassoc} specifies no associativity, which
4345means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
4346considered a syntax error.
4347
d78f0ac9
AD
4348@code{%precedence} gives only precedence to the @var{symbols}, and
4349defines no associativity at all. Use this to define precedence only,
4350and leave any potential conflict due to associativity enabled.
4351
bfa74976
RS
4352@item
4353The precedence of an operator determines how it nests with other operators.
4354All the tokens declared in a single precedence declaration have equal
4355precedence and nest together according to their associativity.
4356When two tokens declared in different precedence declarations associate,
4357the one declared later has the higher precedence and is grouped first.
4358@end itemize
4359
ab7f29f8
JD
4360For backward compatibility, there is a confusing difference between the
4361argument lists of @code{%token} and precedence declarations.
4362Only a @code{%token} can associate a literal string with a token type name.
4363A precedence declaration always interprets a literal string as a reference to a
4364separate token.
4365For example:
4366
4367@example
4368%left OR "<=" // Does not declare an alias.
4369%left OR 134 "<=" 135 // Declares 134 for OR and 135 for "<=".
4370@end example
4371
342b8b6e 4372@node Union Decl
bfa74976
RS
4373@subsection The Collection of Value Types
4374@cindex declaring value types
4375@cindex value types, declaring
4376@findex %union
4377
287c78f6
PE
4378The @code{%union} declaration specifies the entire collection of
4379possible data types for semantic values. The keyword @code{%union} is
4380followed by braced code containing the same thing that goes inside a
4381@code{union} in C@.
bfa74976
RS
4382
4383For example:
4384
4385@example
4386@group
4387%union @{
4388 double val;
4389 symrec *tptr;
4390@}
4391@end group
4392@end example
4393
4394@noindent
4395This says that the two alternative types are @code{double} and @code{symrec
4396*}. They are given names @code{val} and @code{tptr}; these names are used
4397in the @code{%token} and @code{%type} declarations to pick one of the types
4398for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
4399
8a4281b9 4400As an extension to POSIX, a tag is allowed after the
6273355b
PE
4401@code{union}. For example:
4402
4403@example
4404@group
4405%union value @{
4406 double val;
4407 symrec *tptr;
4408@}
4409@end group
4410@end example
4411
d6ca7905 4412@noindent
6273355b
PE
4413specifies the union tag @code{value}, so the corresponding C type is
4414@code{union value}. If you do not specify a tag, it defaults to
4415@code{YYSTYPE}.
4416
8a4281b9 4417As another extension to POSIX, you may specify multiple
d6ca7905
PE
4418@code{%union} declarations; their contents are concatenated. However,
4419only the first @code{%union} declaration can specify a tag.
4420
6273355b 4421Note that, unlike making a @code{union} declaration in C, you need not write
bfa74976
RS
4422a semicolon after the closing brace.
4423
ddc8ede1
PE
4424Instead of @code{%union}, you can define and use your own union type
4425@code{YYSTYPE} if your grammar contains at least one
4426@samp{<@var{type}>} tag. For example, you can put the following into
4427a header file @file{parser.h}:
4428
4429@example
4430@group
4431union YYSTYPE @{
4432 double val;
4433 symrec *tptr;
4434@};
4435typedef union YYSTYPE YYSTYPE;
4436@end group
4437@end example
4438
4439@noindent
4440and then your grammar can use the following
4441instead of @code{%union}:
4442
4443@example
4444@group
4445%@{
4446#include "parser.h"
4447%@}
4448%type <val> expr
4449%token <tptr> ID
4450@end group
4451@end example
4452
342b8b6e 4453@node Type Decl
bfa74976
RS
4454@subsection Nonterminal Symbols
4455@cindex declaring value types, nonterminals
4456@cindex value types, nonterminals, declaring
4457@findex %type
4458
4459@noindent
4460When you use @code{%union} to specify multiple value types, you must
4461declare the value type of each nonterminal symbol for which values are
4462used. This is done with a @code{%type} declaration, like this:
4463
4464@example
4465%type <@var{type}> @var{nonterminal}@dots{}
4466@end example
4467
4468@noindent
704a47c4
AD
4469Here @var{nonterminal} is the name of a nonterminal symbol, and
4470@var{type} is the name given in the @code{%union} to the alternative
4471that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
4472can give any number of nonterminal symbols in the same @code{%type}
4473declaration, if they have the same value type. Use spaces to separate
4474the symbol names.
bfa74976 4475
931c7513
RS
4476You can also declare the value type of a terminal symbol. To do this,
4477use the same @code{<@var{type}>} construction in a declaration for the
4478terminal symbol. All kinds of token declarations allow
4479@code{<@var{type}>}.
4480
18d192f0
AD
4481@node Initial Action Decl
4482@subsection Performing Actions before Parsing
4483@findex %initial-action
4484
4485Sometimes your parser needs to perform some initializations before
4486parsing. The @code{%initial-action} directive allows for such arbitrary
4487code.
4488
4489@deffn {Directive} %initial-action @{ @var{code} @}
4490@findex %initial-action
287c78f6 4491Declare that the braced @var{code} must be invoked before parsing each time
451364ed 4492@code{yyparse} is called. The @var{code} may use @code{$$} and
742e4900 4493@code{@@$} --- initial value and location of the lookahead --- and the
451364ed 4494@code{%parse-param}.
18d192f0
AD
4495@end deffn
4496
451364ed
AD
4497For instance, if your locations use a file name, you may use
4498
4499@example
48b16bbc 4500%parse-param @{ char const *file_name @};
451364ed
AD
4501%initial-action
4502@{
4626a15d 4503 @@$.initialize (file_name);
451364ed
AD
4504@};
4505@end example
4506
18d192f0 4507
72f889cc
AD
4508@node Destructor Decl
4509@subsection Freeing Discarded Symbols
4510@cindex freeing discarded symbols
4511@findex %destructor
12e35840 4512@findex <*>
3ebecc24 4513@findex <>
a85284cf
AD
4514During error recovery (@pxref{Error Recovery}), symbols already pushed
4515on the stack and tokens coming from the rest of the file are discarded
4516until the parser falls on its feet. If the parser runs out of memory,
9d9b8b70 4517or if it returns via @code{YYABORT} or @code{YYACCEPT}, all the
a85284cf
AD
4518symbols on the stack must be discarded. Even if the parser succeeds, it
4519must discard the start symbol.
258b75ca
PE
4520
4521When discarded symbols convey heap based information, this memory is
4522lost. While this behavior can be tolerable for batch parsers, such as
4b367315
AD
4523in traditional compilers, it is unacceptable for programs like shells or
4524protocol implementations that may parse and execute indefinitely.
258b75ca 4525
a85284cf
AD
4526The @code{%destructor} directive defines code that is called when a
4527symbol is automatically discarded.
72f889cc
AD
4528
4529@deffn {Directive} %destructor @{ @var{code} @} @var{symbols}
4530@findex %destructor
287c78f6
PE
4531Invoke the braced @var{code} whenever the parser discards one of the
4532@var{symbols}.
4b367315 4533Within @var{code}, @code{$$} designates the semantic value associated
ec5479ce
JD
4534with the discarded symbol, and @code{@@$} designates its location.
4535The additional parser parameters are also available (@pxref{Parser Function, ,
4536The Parser Function @code{yyparse}}).
ec5479ce 4537
b2a0b7ca
JD
4538When a symbol is listed among @var{symbols}, its @code{%destructor} is called a
4539per-symbol @code{%destructor}.
4540You may also define a per-type @code{%destructor} by listing a semantic type
12e35840 4541tag among @var{symbols}.
b2a0b7ca 4542In that case, the parser will invoke this @var{code} whenever it discards any
12e35840 4543grammar symbol that has that semantic type tag unless that symbol has its own
b2a0b7ca
JD
4544per-symbol @code{%destructor}.
4545
12e35840 4546Finally, you can define two different kinds of default @code{%destructor}s.
85894313
JD
4547(These default forms are experimental.
4548More user feedback will help to determine whether they should become permanent
4549features.)
3ebecc24 4550You can place each of @code{<*>} and @code{<>} in the @var{symbols} list of
12e35840
JD
4551exactly one @code{%destructor} declaration in your grammar file.
4552The parser will invoke the @var{code} associated with one of these whenever it
4553discards any user-defined grammar symbol that has no per-symbol and no per-type
4554@code{%destructor}.
4555The parser uses the @var{code} for @code{<*>} in the case of such a grammar
4556symbol for which you have formally declared a semantic type tag (@code{%type}
4557counts as such a declaration, but @code{$<tag>$} does not).
3ebecc24 4558The parser uses the @var{code} for @code{<>} in the case of such a grammar
12e35840 4559symbol that has no declared semantic type tag.
72f889cc
AD
4560@end deffn
4561
b2a0b7ca 4562@noindent
12e35840 4563For example:
72f889cc
AD
4564
4565@smallexample
ec5479ce
JD
4566%union @{ char *string; @}
4567%token <string> STRING1
4568%token <string> STRING2
4569%type <string> string1
4570%type <string> string2
b2a0b7ca
JD
4571%union @{ char character; @}
4572%token <character> CHR
4573%type <character> chr
12e35840
JD
4574%token TAGLESS
4575
b2a0b7ca 4576%destructor @{ @} <character>
12e35840
JD
4577%destructor @{ free ($$); @} <*>
4578%destructor @{ free ($$); printf ("%d", @@$.first_line); @} STRING1 string1
3ebecc24 4579%destructor @{ printf ("Discarding tagless symbol.\n"); @} <>
72f889cc
AD
4580@end smallexample
4581
4582@noindent
b2a0b7ca
JD
4583guarantees that, when the parser discards any user-defined symbol that has a
4584semantic type tag other than @code{<character>}, it passes its semantic value
12e35840 4585to @code{free} by default.
ec5479ce
JD
4586However, when the parser discards a @code{STRING1} or a @code{string1}, it also
4587prints its line number to @code{stdout}.
4588It performs only the second @code{%destructor} in this case, so it invokes
4589@code{free} only once.
12e35840
JD
4590Finally, the parser merely prints a message whenever it discards any symbol,
4591such as @code{TAGLESS}, that has no semantic type tag.
4592
4593A Bison-generated parser invokes the default @code{%destructor}s only for
4594user-defined as opposed to Bison-defined symbols.
4595For example, the parser will not invoke either kind of default
4596@code{%destructor} for the special Bison-defined symbols @code{$accept},
4597@code{$undefined}, or @code{$end} (@pxref{Table of Symbols, ,Bison Symbols}),
4598none of which you can reference in your grammar.
4599It also will not invoke either for the @code{error} token (@pxref{Table of
4600Symbols, ,error}), which is always defined by Bison regardless of whether you
4601reference it in your grammar.
4602However, it may invoke one of them for the end token (token 0) if you
4603redefine it from @code{$end} to, for example, @code{END}:
3508ce36
JD
4604
4605@smallexample
4606%token END 0
4607@end smallexample
4608
12e35840
JD
4609@cindex actions in mid-rule
4610@cindex mid-rule actions
4611Finally, Bison will never invoke a @code{%destructor} for an unreferenced
4612mid-rule semantic value (@pxref{Mid-Rule Actions,,Actions in Mid-Rule}).
4613That is, Bison does not consider a mid-rule to have a semantic value if you do
4614not reference @code{$$} in the mid-rule's action or @code{$@var{n}} (where
4615@var{n} is the RHS symbol position of the mid-rule) in any later action in that
4616rule.
4617However, if you do reference either, the Bison-generated parser will invoke the
3ebecc24 4618@code{<>} @code{%destructor} whenever it discards the mid-rule symbol.
12e35840 4619
3508ce36
JD
4620@ignore
4621@noindent
4622In the future, it may be possible to redefine the @code{error} token as a
4623nonterminal that captures the discarded symbols.
4624In that case, the parser will invoke the default destructor for it as well.
4625@end ignore
4626
e757bb10
AD
4627@sp 1
4628
4629@cindex discarded symbols
4630@dfn{Discarded symbols} are the following:
4631
4632@itemize
4633@item
4634stacked symbols popped during the first phase of error recovery,
4635@item
4636incoming terminals during the second phase of error recovery,
4637@item
742e4900 4638the current lookahead and the entire stack (except the current
9d9b8b70 4639right-hand side symbols) when the parser returns immediately, and
258b75ca
PE
4640@item
4641the start symbol, when the parser succeeds.
e757bb10
AD
4642@end itemize
4643
9d9b8b70
PE
4644The parser can @dfn{return immediately} because of an explicit call to
4645@code{YYABORT} or @code{YYACCEPT}, or failed error recovery, or memory
4646exhaustion.
4647
29553547 4648Right-hand side symbols of a rule that explicitly triggers a syntax
9d9b8b70
PE
4649error via @code{YYERROR} are not discarded automatically. As a rule
4650of thumb, destructors are invoked only when user actions cannot manage
a85284cf 4651the memory.
e757bb10 4652
342b8b6e 4653@node Expect Decl
bfa74976
RS
4654@subsection Suppressing Conflict Warnings
4655@cindex suppressing conflict warnings
4656@cindex preventing warnings about conflicts
4657@cindex warnings, preventing
4658@cindex conflicts, suppressing warnings of
4659@findex %expect
d6328241 4660@findex %expect-rr
bfa74976
RS
4661
4662Bison normally warns if there are any conflicts in the grammar
7da99ede
AD
4663(@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
4664have harmless shift/reduce conflicts which are resolved in a predictable
4665way and would be difficult to eliminate. It is desirable to suppress
4666the warning about these conflicts unless the number of conflicts
4667changes. You can do this with the @code{%expect} declaration.
bfa74976
RS
4668
4669The declaration looks like this:
4670
4671@example
4672%expect @var{n}
4673@end example
4674
035aa4a0
PE
4675Here @var{n} is a decimal integer. The declaration says there should
4676be @var{n} shift/reduce conflicts and no reduce/reduce conflicts.
4677Bison reports an error if the number of shift/reduce conflicts differs
4678from @var{n}, or if there are any reduce/reduce conflicts.
bfa74976 4679
eb45ef3b 4680For deterministic parsers, reduce/reduce conflicts are more
035aa4a0 4681serious, and should be eliminated entirely. Bison will always report
8a4281b9 4682reduce/reduce conflicts for these parsers. With GLR
035aa4a0 4683parsers, however, both kinds of conflicts are routine; otherwise,
8a4281b9 4684there would be no need to use GLR parsing. Therefore, it is
035aa4a0 4685also possible to specify an expected number of reduce/reduce conflicts
8a4281b9 4686in GLR parsers, using the declaration:
d6328241
PH
4687
4688@example
4689%expect-rr @var{n}
4690@end example
4691
bfa74976
RS
4692In general, using @code{%expect} involves these steps:
4693
4694@itemize @bullet
4695@item
4696Compile your grammar without @code{%expect}. Use the @samp{-v} option
4697to get a verbose list of where the conflicts occur. Bison will also
4698print the number of conflicts.
4699
4700@item
4701Check each of the conflicts to make sure that Bison's default
4702resolution is what you really want. If not, rewrite the grammar and
4703go back to the beginning.
4704
4705@item
4706Add an @code{%expect} declaration, copying the number @var{n} from the
8a4281b9 4707number which Bison printed. With GLR parsers, add an
035aa4a0 4708@code{%expect-rr} declaration as well.
bfa74976
RS
4709@end itemize
4710
93d7dde9
JD
4711Now Bison will report an error if you introduce an unexpected conflict,
4712but will keep silent otherwise.
bfa74976 4713
342b8b6e 4714@node Start Decl
bfa74976
RS
4715@subsection The Start-Symbol
4716@cindex declaring the start symbol
4717@cindex start symbol, declaring
4718@cindex default start symbol
4719@findex %start
4720
4721Bison assumes by default that the start symbol for the grammar is the first
4722nonterminal specified in the grammar specification section. The programmer
4723may override this restriction with the @code{%start} declaration as follows:
4724
4725@example
4726%start @var{symbol}
4727@end example
4728
342b8b6e 4729@node Pure Decl
bfa74976
RS
4730@subsection A Pure (Reentrant) Parser
4731@cindex reentrant parser
4732@cindex pure parser
d9df47b6 4733@findex %define api.pure
bfa74976
RS
4734
4735A @dfn{reentrant} program is one which does not alter in the course of
4736execution; in other words, it consists entirely of @dfn{pure} (read-only)
4737code. Reentrancy is important whenever asynchronous execution is possible;
9d9b8b70
PE
4738for example, a nonreentrant program may not be safe to call from a signal
4739handler. In systems with multiple threads of control, a nonreentrant
bfa74976
RS
4740program must be called only within interlocks.
4741
70811b85 4742Normally, Bison generates a parser which is not reentrant. This is
c827f760
PE
4743suitable for most uses, and it permits compatibility with Yacc. (The
4744standard Yacc interfaces are inherently nonreentrant, because they use
70811b85
RS
4745statically allocated variables for communication with @code{yylex},
4746including @code{yylval} and @code{yylloc}.)
bfa74976 4747
70811b85 4748Alternatively, you can generate a pure, reentrant parser. The Bison
67501061 4749declaration @samp{%define api.pure} says that you want the parser to be
70811b85 4750reentrant. It looks like this:
bfa74976
RS
4751
4752@example
d9df47b6 4753%define api.pure
bfa74976
RS
4754@end example
4755
70811b85
RS
4756The result is that the communication variables @code{yylval} and
4757@code{yylloc} become local variables in @code{yyparse}, and a different
4758calling convention is used for the lexical analyzer function
4759@code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
f4101aa6
AD
4760Parsers}, for the details of this. The variable @code{yynerrs}
4761becomes local in @code{yyparse} in pull mode but it becomes a member
9987d1b3 4762of yypstate in push mode. (@pxref{Error Reporting, ,The Error
70811b85
RS
4763Reporting Function @code{yyerror}}). The convention for calling
4764@code{yyparse} itself is unchanged.
4765
4766Whether the parser is pure has nothing to do with the grammar rules.
4767You can generate either a pure parser or a nonreentrant parser from any
4768valid grammar.
bfa74976 4769
9987d1b3
JD
4770@node Push Decl
4771@subsection A Push Parser
4772@cindex push parser
4773@cindex push parser
67212941 4774@findex %define api.push-pull
9987d1b3 4775
59da312b
JD
4776(The current push parsing interface is experimental and may evolve.
4777More user feedback will help to stabilize it.)
4778
f4101aa6
AD
4779A pull parser is called once and it takes control until all its input
4780is completely parsed. A push parser, on the other hand, is called
9987d1b3
JD
4781each time a new token is made available.
4782
f4101aa6 4783A push parser is typically useful when the parser is part of a
9987d1b3 4784main event loop in the client's application. This is typically
f4101aa6
AD
4785a requirement of a GUI, when the main event loop needs to be triggered
4786within a certain time period.
9987d1b3 4787
d782395d
JD
4788Normally, Bison generates a pull parser.
4789The following Bison declaration says that you want the parser to be a push
67212941 4790parser (@pxref{Decl Summary,,%define api.push-pull}):
9987d1b3
JD
4791
4792@example
cf499cff 4793%define api.push-pull push
9987d1b3
JD
4794@end example
4795
4796In almost all cases, you want to ensure that your push parser is also
4797a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}). The only
f4101aa6 4798time you should create an impure push parser is to have backwards
9987d1b3
JD
4799compatibility with the impure Yacc pull mode interface. Unless you know
4800what you are doing, your declarations should look like this:
4801
4802@example
d9df47b6 4803%define api.pure
cf499cff 4804%define api.push-pull push
9987d1b3
JD
4805@end example
4806
f4101aa6
AD
4807There is a major notable functional difference between the pure push parser
4808and the impure push parser. It is acceptable for a pure push parser to have
9987d1b3
JD
4809many parser instances, of the same type of parser, in memory at the same time.
4810An impure push parser should only use one parser at a time.
4811
4812When a push parser is selected, Bison will generate some new symbols in
f4101aa6
AD
4813the generated parser. @code{yypstate} is a structure that the generated
4814parser uses to store the parser's state. @code{yypstate_new} is the
9987d1b3
JD
4815function that will create a new parser instance. @code{yypstate_delete}
4816will free the resources associated with the corresponding parser instance.
f4101aa6 4817Finally, @code{yypush_parse} is the function that should be called whenever a
9987d1b3
JD
4818token is available to provide the parser. A trivial example
4819of using a pure push parser would look like this:
4820
4821@example
4822int status;
4823yypstate *ps = yypstate_new ();
4824do @{
4825 status = yypush_parse (ps, yylex (), NULL);
4826@} while (status == YYPUSH_MORE);
4827yypstate_delete (ps);
4828@end example
4829
4830If the user decided to use an impure push parser, a few things about
f4101aa6 4831the generated parser will change. The @code{yychar} variable becomes
9987d1b3
JD
4832a global variable instead of a variable in the @code{yypush_parse} function.
4833For this reason, the signature of the @code{yypush_parse} function is
f4101aa6 4834changed to remove the token as a parameter. A nonreentrant push parser
9987d1b3
JD
4835example would thus look like this:
4836
4837@example
4838extern int yychar;
4839int status;
4840yypstate *ps = yypstate_new ();
4841do @{
4842 yychar = yylex ();
4843 status = yypush_parse (ps);
4844@} while (status == YYPUSH_MORE);
4845yypstate_delete (ps);
4846@end example
4847
f4101aa6 4848That's it. Notice the next token is put into the global variable @code{yychar}
9987d1b3
JD
4849for use by the next invocation of the @code{yypush_parse} function.
4850
f4101aa6 4851Bison also supports both the push parser interface along with the pull parser
9987d1b3 4852interface in the same generated parser. In order to get this functionality,
cf499cff
JD
4853you should replace the @samp{%define api.push-pull push} declaration with the
4854@samp{%define api.push-pull both} declaration. Doing this will create all of
c373bf8b 4855the symbols mentioned earlier along with the two extra symbols, @code{yyparse}
f4101aa6
AD
4856and @code{yypull_parse}. @code{yyparse} can be used exactly as it normally
4857would be used. However, the user should note that it is implemented in the
d782395d
JD
4858generated parser by calling @code{yypull_parse}.
4859This makes the @code{yyparse} function that is generated with the
cf499cff 4860@samp{%define api.push-pull both} declaration slower than the normal
d782395d
JD
4861@code{yyparse} function. If the user
4862calls the @code{yypull_parse} function it will parse the rest of the input
f4101aa6
AD
4863stream. It is possible to @code{yypush_parse} tokens to select a subgrammar
4864and then @code{yypull_parse} the rest of the input stream. If you would like
4865to switch back and forth between between parsing styles, you would have to
4866write your own @code{yypull_parse} function that knows when to quit looking
4867for input. An example of using the @code{yypull_parse} function would look
9987d1b3
JD
4868like this:
4869
4870@example
4871yypstate *ps = yypstate_new ();
4872yypull_parse (ps); /* Will call the lexer */
4873yypstate_delete (ps);
4874@end example
4875
67501061 4876Adding the @samp{%define api.pure} declaration does exactly the same thing to
cf499cff
JD
4877the generated parser with @samp{%define api.push-pull both} as it did for
4878@samp{%define api.push-pull push}.
9987d1b3 4879
342b8b6e 4880@node Decl Summary
bfa74976
RS
4881@subsection Bison Declaration Summary
4882@cindex Bison declaration summary
4883@cindex declaration summary
4884@cindex summary, Bison declaration
4885
d8988b2f 4886Here is a summary of the declarations used to define a grammar:
bfa74976 4887
18b519c0 4888@deffn {Directive} %union
bfa74976
RS
4889Declare the collection of data types that semantic values may have
4890(@pxref{Union Decl, ,The Collection of Value Types}).
18b519c0 4891@end deffn
bfa74976 4892
18b519c0 4893@deffn {Directive} %token
bfa74976
RS
4894Declare a terminal symbol (token type name) with no precedence
4895or associativity specified (@pxref{Token Decl, ,Token Type Names}).
18b519c0 4896@end deffn
bfa74976 4897
18b519c0 4898@deffn {Directive} %right
bfa74976
RS
4899Declare a terminal symbol (token type name) that is right-associative
4900(@pxref{Precedence Decl, ,Operator Precedence}).
18b519c0 4901@end deffn
bfa74976 4902
18b519c0 4903@deffn {Directive} %left
bfa74976
RS
4904Declare a terminal symbol (token type name) that is left-associative
4905(@pxref{Precedence Decl, ,Operator Precedence}).
18b519c0 4906@end deffn
bfa74976 4907
18b519c0 4908@deffn {Directive} %nonassoc
bfa74976 4909Declare a terminal symbol (token type name) that is nonassociative
bfa74976 4910(@pxref{Precedence Decl, ,Operator Precedence}).
39a06c25
PE
4911Using it in a way that would be associative is a syntax error.
4912@end deffn
4913
91d2c560 4914@ifset defaultprec
39a06c25 4915@deffn {Directive} %default-prec
22fccf95 4916Assign a precedence to rules lacking an explicit @code{%prec} modifier
39a06c25
PE
4917(@pxref{Contextual Precedence, ,Context-Dependent Precedence}).
4918@end deffn
91d2c560 4919@end ifset
bfa74976 4920
18b519c0 4921@deffn {Directive} %type
bfa74976
RS
4922Declare the type of semantic values for a nonterminal symbol
4923(@pxref{Type Decl, ,Nonterminal Symbols}).
18b519c0 4924@end deffn
bfa74976 4925
18b519c0 4926@deffn {Directive} %start
89cab50d
AD
4927Specify the grammar's start symbol (@pxref{Start Decl, ,The
4928Start-Symbol}).
18b519c0 4929@end deffn
bfa74976 4930
18b519c0 4931@deffn {Directive} %expect
bfa74976
RS
4932Declare the expected number of shift-reduce conflicts
4933(@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
18b519c0
AD
4934@end deffn
4935
bfa74976 4936
d8988b2f
AD
4937@sp 1
4938@noindent
4939In order to change the behavior of @command{bison}, use the following
4940directives:
4941
148d66d8
JD
4942@deffn {Directive} %code @{@var{code}@}
4943@findex %code
4944This is the unqualified form of the @code{%code} directive.
8405b70c
PB
4945It inserts @var{code} verbatim at a language-dependent default location in the
4946output@footnote{The default location is actually skeleton-dependent;
4947 writers of non-standard skeletons however should choose the default location
4948 consistently with the behavior of the standard Bison skeletons.}.
148d66d8
JD
4949
4950@cindex Prologue
ff7571c0
JD
4951For C/C++, the default location is the parser implementation file
4952after the usual contents of the parser header file. Thus,
4953@code{%code} replaces the traditional Yacc prologue,
4954@code{%@{@var{code}%@}}, for most purposes. For a detailed
4955discussion, see @ref{Prologue Alternatives}.
148d66d8 4956
8405b70c 4957For Java, the default location is inside the parser class.
148d66d8
JD
4958@end deffn
4959
4960@deffn {Directive} %code @var{qualifier} @{@var{code}@}
4961This is the qualified form of the @code{%code} directive.
4962If you need to specify location-sensitive verbatim @var{code} that does not
4963belong at the default location selected by the unqualified @code{%code} form,
4964use this form instead.
4965
4966@var{qualifier} identifies the purpose of @var{code} and thus the location(s)
4967where Bison should generate it.
c6abeab1
JD
4968Not all @var{qualifier}s are accepted for all target languages.
4969Unaccepted @var{qualifier}s produce an error.
4970Some of the accepted @var{qualifier}s are:
148d66d8
JD
4971
4972@itemize @bullet
148d66d8 4973@item requires
793fbca5 4974@findex %code requires
148d66d8
JD
4975
4976@itemize @bullet
4977@item Language(s): C, C++
4978
4979@item Purpose: This is the best place to write dependency code required for
4980@code{YYSTYPE} and @code{YYLTYPE}.
4981In other words, it's the best place to define types referenced in @code{%union}
4982directives, and it's the best place to override Bison's default @code{YYSTYPE}
4983and @code{YYLTYPE} definitions.
4984
ff7571c0
JD
4985@item Location(s): The parser header file and the parser implementation file
4986before the Bison-generated @code{YYSTYPE} and @code{YYLTYPE}
4987definitions.
148d66d8
JD
4988@end itemize
4989
4990@item provides
4991@findex %code provides
4992
4993@itemize @bullet
4994@item Language(s): C, C++
4995
4996@item Purpose: This is the best place to write additional definitions and
4997declarations that should be provided to other modules.
4998
ff7571c0
JD
4999@item Location(s): The parser header file and the parser implementation
5000file after the Bison-generated @code{YYSTYPE}, @code{YYLTYPE}, and
5001token definitions.
148d66d8
JD
5002@end itemize
5003
5004@item top
5005@findex %code top
5006
5007@itemize @bullet
5008@item Language(s): C, C++
5009
ff7571c0
JD
5010@item Purpose: The unqualified @code{%code} or @code{%code requires}
5011should usually be more appropriate than @code{%code top}. However,
5012occasionally it is necessary to insert code much nearer the top of the
5013parser implementation file. For example:
148d66d8
JD
5014
5015@smallexample
5016%code top @{
5017 #define _GNU_SOURCE
5018 #include <stdio.h>
5019@}
5020@end smallexample
5021
ff7571c0 5022@item Location(s): Near the top of the parser implementation file.
148d66d8 5023@end itemize
8405b70c 5024
148d66d8
JD
5025@item imports
5026@findex %code imports
5027
5028@itemize @bullet
5029@item Language(s): Java
5030
5031@item Purpose: This is the best place to write Java import directives.
5032
5033@item Location(s): The parser Java file after any Java package directive and
5034before any class definitions.
5035@end itemize
148d66d8
JD
5036@end itemize
5037
148d66d8
JD
5038@cindex Prologue
5039For a detailed discussion of how to use @code{%code} in place of the
5040traditional Yacc prologue for C/C++, see @ref{Prologue Alternatives}.
5041@end deffn
5042
18b519c0 5043@deffn {Directive} %debug
fa819509
AD
5044Instrument the output parser for traces. Obsoleted by @samp{%define
5045parse.trace}.
ec3bc396 5046@xref{Tracing, ,Tracing Your Parser}.
f7dae1ea 5047@end deffn
d8988b2f 5048
c1d19e10 5049@deffn {Directive} %define @var{variable}
cf499cff 5050@deffnx {Directive} %define @var{variable} @var{value}
c1d19e10 5051@deffnx {Directive} %define @var{variable} "@var{value}"
9611cfa2 5052Define a variable to adjust Bison's behavior.
9611cfa2 5053
0b6d43c5 5054It is an error if a @var{variable} is defined by @code{%define} multiple
17aed602 5055times, but see @ref{Bison Options,,-D @var{name}[=@var{value}]}.
9611cfa2 5056
82f3355e
JD
5057@var{value} must be placed in quotation marks if it contains any character
5058other than a letter, underscore, period, or non-initial dash or digit.
cf499cff
JD
5059
5060Omitting @code{"@var{value}"} entirely is always equivalent to specifying
9611cfa2
JD
5061@code{""}.
5062
c6abeab1 5063Some @var{variable}s take Boolean values.
9611cfa2
JD
5064In this case, Bison will complain if the variable definition does not meet one
5065of the following four conditions:
5066
5067@enumerate
cf499cff 5068@item @code{@var{value}} is @code{true}
9611cfa2 5069
cf499cff
JD
5070@item @code{@var{value}} is omitted (or @code{""} is specified).
5071This is equivalent to @code{true}.
9611cfa2 5072
cf499cff 5073@item @code{@var{value}} is @code{false}.
9611cfa2
JD
5074
5075@item @var{variable} is never defined.
c6abeab1 5076In this case, Bison selects a default value.
9611cfa2 5077@end enumerate
148d66d8 5078
c6abeab1
JD
5079What @var{variable}s are accepted, as well as their meanings and default
5080values, depend on the selected target language and/or the parser
5081skeleton (@pxref{Decl Summary,,%language}, @pxref{Decl
5082Summary,,%skeleton}).
5083Unaccepted @var{variable}s produce an error.
793fbca5
JD
5084Some of the accepted @var{variable}s are:
5085
fa819509 5086@table @code
6b5a0de9 5087@c ================================================== api.namespace
67501061
AD
5088@item api.namespace
5089@findex %define api.namespace
5090@itemize
5091@item Languages(s): C++
5092
f1b238df 5093@item Purpose: Specify the namespace for the parser class.
67501061
AD
5094For example, if you specify:
5095
5096@smallexample
5097%define api.namespace "foo::bar"
5098@end smallexample
5099
5100Bison uses @code{foo::bar} verbatim in references such as:
5101
5102@smallexample
5103foo::bar::parser::semantic_type
5104@end smallexample
5105
5106However, to open a namespace, Bison removes any leading @code{::} and then
5107splits on any remaining occurrences:
5108
5109@smallexample
5110namespace foo @{ namespace bar @{
5111 class position;
5112 class location;
5113@} @}
5114@end smallexample
5115
5116@item Accepted Values:
5117Any absolute or relative C++ namespace reference without a trailing
5118@code{"::"}. For example, @code{"foo"} or @code{"::foo::bar"}.
5119
5120@item Default Value:
5121The value specified by @code{%name-prefix}, which defaults to @code{yy}.
5122This usage of @code{%name-prefix} is for backward compatibility and can
5123be confusing since @code{%name-prefix} also specifies the textual prefix
5124for the lexical analyzer function. Thus, if you specify
5125@code{%name-prefix}, it is best to also specify @samp{%define
5126api.namespace} so that @code{%name-prefix} @emph{only} affects the
5127lexical analyzer function. For example, if you specify:
5128
5129@smallexample
5130%define api.namespace "foo"
5131%name-prefix "bar::"
5132@end smallexample
5133
5134The parser namespace is @code{foo} and @code{yylex} is referenced as
5135@code{bar::lex}.
5136@end itemize
5137@c namespace
5138
5139
5140
5141@c ================================================== api.pure
d9df47b6
JD
5142@item api.pure
5143@findex %define api.pure
5144
5145@itemize @bullet
5146@item Language(s): C
5147
5148@item Purpose: Request a pure (reentrant) parser program.
5149@xref{Pure Decl, ,A Pure (Reentrant) Parser}.
5150
5151@item Accepted Values: Boolean
5152
cf499cff 5153@item Default Value: @code{false}
d9df47b6 5154@end itemize
71b00ed8 5155@c api.pure
d9df47b6 5156
67501061
AD
5157
5158
5159@c ================================================== api.push-pull
67212941
JD
5160@item api.push-pull
5161@findex %define api.push-pull
793fbca5
JD
5162
5163@itemize @bullet
eb45ef3b 5164@item Language(s): C (deterministic parsers only)
793fbca5 5165
f1b238df 5166@item Purpose: Request a pull parser, a push parser, or both.
d782395d 5167@xref{Push Decl, ,A Push Parser}.
59da312b
JD
5168(The current push parsing interface is experimental and may evolve.
5169More user feedback will help to stabilize it.)
793fbca5 5170
cf499cff 5171@item Accepted Values: @code{pull}, @code{push}, @code{both}
793fbca5 5172
cf499cff 5173@item Default Value: @code{pull}
793fbca5 5174@end itemize
67212941 5175@c api.push-pull
71b00ed8 5176
6b5a0de9
AD
5177
5178
5179@c ================================================== api.tokens.prefix
4c6622c2
AD
5180@item api.tokens.prefix
5181@findex %define api.tokens.prefix
5182
5183@itemize
5184@item Languages(s): all
5185
5186@item Purpose:
5187Add a prefix to the token names when generating their definition in the
5188target language. For instance
5189
5190@example
5191%token FILE for ERROR
5192%define api.tokens.prefix "TOK_"
5193%%
5194start: FILE for ERROR;
5195@end example
5196
5197@noindent
5198generates the definition of the symbols @code{TOK_FILE}, @code{TOK_for},
5199and @code{TOK_ERROR} in the generated source files. In particular, the
5200scanner must use these prefixed token names, while the grammar itself
5201may still use the short names (as in the sample rule given above). The
5202generated informational files (@file{*.output}, @file{*.xml},
5203@file{*.dot}) are not modified by this prefix. See @ref{Calc++ Parser}
5204and @ref{Calc++ Scanner}, for a complete example.
5205
5206@item Accepted Values:
5207Any string. Should be a valid identifier prefix in the target language,
5208in other words, it should typically be an identifier itself (sequence of
5209letters, underscores, and ---not at the beginning--- digits).
5210
5211@item Default Value:
5212empty
5213@end itemize
5214@c api.tokens.prefix
5215
5216
3cdc21cf
AD
5217@c ================================================== lex_symbol
5218@item variant
5219@findex %define lex_symbol
5220
5221@itemize @bullet
5222@item Language(s):
5223C++
5224
5225@item Purpose:
5226When variant-based semantic values are enabled (@pxref{C++ Variants}),
5227request that symbols be handled as a whole (type, value, and possibly
5228location) in the scanner. @xref{Complete Symbols}, for details.
5229
5230@item Accepted Values:
5231Boolean.
5232
5233@item Default Value:
5234@code{false}
5235@end itemize
5236@c lex_symbol
5237
5238
6b5a0de9
AD
5239@c ================================================== lr.default-reductions
5240
5bab9d08 5241@item lr.default-reductions
110ef36a 5242@cindex default reductions
5bab9d08 5243@findex %define lr.default-reductions
eb45ef3b
JD
5244@cindex delayed syntax errors
5245@cindex syntax errors delayed
8a4281b9 5246@cindex LAC
fcf834f9 5247@findex %nonassoc
eb45ef3b
JD
5248
5249@itemize @bullet
5250@item Language(s): all
5251
fcf834f9 5252@item Purpose: Specify the kind of states that are permitted to
110ef36a 5253contain default reductions.
fcf834f9
JD
5254That is, in such a state, Bison selects the reduction with the largest
5255lookahead set to be the default parser action and then removes that
110ef36a 5256lookahead set.
fcf834f9
JD
5257(The ability to specify where default reductions should be used is
5258experimental.
eb45ef3b
JD
5259More user feedback will help to stabilize it.)
5260
5261@item Accepted Values:
5262@itemize
cf499cff 5263@item @code{all}.
fcf834f9
JD
5264This is the traditional Bison behavior.
5265The main advantage is a significant decrease in the size of the parser
5266tables.
5267The disadvantage is that, when the generated parser encounters a
5268syntactically unacceptable token, the parser might then perform
5269unnecessary default reductions before it can detect the syntax error.
5270Such delayed syntax error detection is usually inherent in
8a4281b9
JD
5271LALR and IELR parser tables anyway due to
5272LR state merging (@pxref{Decl Summary,,lr.type}).
fcf834f9 5273Furthermore, the use of @code{%nonassoc} can contribute to delayed
8a4281b9 5274syntax error detection even in the case of canonical LR.
fcf834f9 5275As an experimental feature, delayed syntax error detection can be
8a4281b9 5276overcome in all cases by enabling LAC (@pxref{Decl
fcf834f9
JD
5277Summary,,parse.lac}, for details, including a discussion of the effects
5278of delayed syntax error detection).
eb45ef3b 5279
cf499cff 5280@item @code{consistent}.
eb45ef3b
JD
5281@cindex consistent states
5282A consistent state is a state that has only one possible action.
5283If that action is a reduction, then the parser does not need to request
5284a lookahead token from the scanner before performing that action.
fcf834f9
JD
5285However, the parser recognizes the ability to ignore the lookahead token
5286in this way only when such a reduction is encoded as a default
5287reduction.
5288Thus, if default reductions are permitted only in consistent states,
8a4281b9 5289then a canonical LR parser that does not employ
fcf834f9
JD
5290@code{%nonassoc} detects a syntax error as soon as it @emph{needs} the
5291syntactically unacceptable token from the scanner.
eb45ef3b 5292
cf499cff 5293@item @code{accepting}.
eb45ef3b 5294@cindex accepting state
fcf834f9
JD
5295In the accepting state, the default reduction is actually the accept
5296action.
8a4281b9 5297In this case, a canonical LR parser that does not employ
fcf834f9
JD
5298@code{%nonassoc} detects a syntax error as soon as it @emph{reaches} the
5299syntactically unacceptable token in the input.
5300That is, it does not perform any extra reductions.
eb45ef3b
JD
5301@end itemize
5302
5303@item Default Value:
5304@itemize
cf499cff
JD
5305@item @code{accepting} if @code{lr.type} is @code{canonical-lr}.
5306@item @code{all} otherwise.
eb45ef3b
JD
5307@end itemize
5308@end itemize
5309
6b5a0de9
AD
5310@c ============================================ lr.keep-unreachable-states
5311
67212941
JD
5312@item lr.keep-unreachable-states
5313@findex %define lr.keep-unreachable-states
31984206
JD
5314
5315@itemize @bullet
5316@item Language(s): all
5317
f1b238df
JD
5318@item Purpose: Request that Bison allow unreachable parser states to
5319remain in the parser tables.
31984206
JD
5320Bison considers a state to be unreachable if there exists no sequence of
5321transitions from the start state to that state.
5322A state can become unreachable during conflict resolution if Bison disables a
5323shift action leading to it from a predecessor state.
5324Keeping unreachable states is sometimes useful for analysis purposes, but they
5325are useless in the generated parser.
5326
5327@item Accepted Values: Boolean
5328
cf499cff 5329@item Default Value: @code{false}
31984206
JD
5330
5331@item Caveats:
5332
5333@itemize @bullet
cff03fb2
JD
5334
5335@item Unreachable states may contain conflicts and may use rules not used in
5336any other state.
31984206
JD
5337Thus, keeping unreachable states may induce warnings that are irrelevant to
5338your parser's behavior, and it may eliminate warnings that are relevant.
5339Of course, the change in warnings may actually be relevant to a parser table
5340analysis that wants to keep unreachable states, so this behavior will likely
5341remain in future Bison releases.
5342
5343@item While Bison is able to remove unreachable states, it is not guaranteed to
5344remove other kinds of useless states.
5345Specifically, when Bison disables reduce actions during conflict resolution,
5346some goto actions may become useless, and thus some additional states may
5347become useless.
5348If Bison were to compute which goto actions were useless and then disable those
5349actions, it could identify such states as unreachable and then remove those
5350states.
5351However, Bison does not compute which goto actions are useless.
5352@end itemize
5353@end itemize
67212941 5354@c lr.keep-unreachable-states
31984206 5355
6b5a0de9
AD
5356@c ================================================== lr.type
5357
eb45ef3b
JD
5358@item lr.type
5359@findex %define lr.type
8a4281b9
JD
5360@cindex LALR
5361@cindex IELR
5362@cindex LR
eb45ef3b
JD
5363
5364@itemize @bullet
5365@item Language(s): all
5366
f1b238df 5367@item Purpose: Specify the type of parser tables within the
8a4281b9 5368LR(1) family.
eb45ef3b
JD
5369(This feature is experimental.
5370More user feedback will help to stabilize it.)
5371
5372@item Accepted Values:
5373@itemize
cf499cff 5374@item @code{lalr}.
8a4281b9
JD
5375While Bison generates LALR parser tables by default for
5376historical reasons, IELR or canonical LR is almost
eb45ef3b 5377always preferable for deterministic parsers.
8a4281b9 5378The trouble is that LALR parser tables can suffer from
110ef36a 5379mysterious conflicts and thus may not accept the full set of sentences
8a4281b9 5380that IELR and canonical LR accept.
eb45ef3b 5381@xref{Mystery Conflicts}, for details.
8a4281b9 5382However, there are at least two scenarios where LALR may be
eb45ef3b
JD
5383worthwhile:
5384@itemize
8a4281b9
JD
5385@cindex GLR with LALR
5386@item When employing GLR parsers (@pxref{GLR Parsers}), if you
eb45ef3b
JD
5387do not resolve any conflicts statically (for example, with @code{%left}
5388or @code{%prec}), then the parser explores all potential parses of any
5389given input.
8a4281b9 5390In this case, the use of LALR parser tables is guaranteed not
110ef36a 5391to alter the language accepted by the parser.
8a4281b9 5392LALR parser tables are the smallest parser tables Bison can
eb45ef3b 5393currently generate, so they may be preferable.
f1b238df 5394Nevertheless, once you begin to resolve conflicts statically,
8a4281b9
JD
5395GLR begins to behave more like a deterministic parser, and so
5396IELR and canonical LR can be helpful to avoid
5397LALR's mysterious behavior.
eb45ef3b
JD
5398
5399@item Occasionally during development, an especially malformed grammar
8a4281b9
JD
5400with a major recurring flaw may severely impede the IELR or
5401canonical LR parser table generation algorithm.
5402LALR can be a quick way to generate parser tables in order to
eb45ef3b 5403investigate such problems while ignoring the more subtle differences
8a4281b9 5404from IELR and canonical LR.
eb45ef3b
JD
5405@end itemize
5406
cf499cff 5407@item @code{ielr}.
8a4281b9
JD
5408IELR is a minimal LR algorithm.
5409That is, given any grammar (LR or non-LR),
5410IELR and canonical LR always accept exactly the same
eb45ef3b 5411set of sentences.
8a4281b9
JD
5412However, as for LALR, the number of parser states is often an
5413order of magnitude less for IELR than for canonical
5414LR.
5415More importantly, because canonical LR's extra parser states
5416may contain duplicate conflicts in the case of non-LR
5417grammars, the number of conflicts for IELR is often an order
eb45ef3b
JD
5418of magnitude less as well.
5419This can significantly reduce the complexity of developing of a grammar.
5420
cf499cff 5421@item @code{canonical-lr}.
eb45ef3b
JD
5422@cindex delayed syntax errors
5423@cindex syntax errors delayed
8a4281b9 5424@cindex LAC
fcf834f9 5425@findex %nonassoc
8a4281b9 5426While inefficient, canonical LR parser tables can be an
fcf834f9 5427interesting means to explore a grammar because they have a property that
8a4281b9 5428IELR and LALR tables do not.
fcf834f9
JD
5429That is, if @code{%nonassoc} is not used and default reductions are left
5430disabled (@pxref{Decl Summary,,lr.default-reductions}), then, for every
8a4281b9 5431left context of every canonical LR state, the set of tokens
fcf834f9
JD
5432accepted by that state is guaranteed to be the exact set of tokens that
5433is syntactically acceptable in that left context.
8a4281b9 5434It might then seem that an advantage of canonical LR parsers
fcf834f9
JD
5435in production is that, under the above constraints, they are guaranteed
5436to detect a syntax error as soon as possible without performing any
5437unnecessary reductions.
8a4281b9 5438However, IELR parsers using LAC (@pxref{Decl
fcf834f9
JD
5439Summary,,parse.lac}) are also able to achieve this behavior without
5440sacrificing @code{%nonassoc} or default reductions.
eb45ef3b
JD
5441@end itemize
5442
cf499cff 5443@item Default Value: @code{lalr}
eb45ef3b
JD
5444@end itemize
5445
67501061
AD
5446
5447@c ================================================== namespace
793fbca5
JD
5448@item namespace
5449@findex %define namespace
67501061 5450Obsoleted by @code{api.namespace}
fa819509
AD
5451@c namespace
5452
31b850d2
AD
5453
5454@c ================================================== parse.assert
0c90a1f5
AD
5455@item parse.assert
5456@findex %define parse.assert
5457
5458@itemize
5459@item Languages(s): C++
5460
5461@item Purpose: Issue runtime assertions to catch invalid uses.
3cdc21cf
AD
5462In C++, when variants are used (@pxref{C++ Variants}), symbols must be
5463constructed and
0c90a1f5
AD
5464destroyed properly. This option checks these constraints.
5465
5466@item Accepted Values: Boolean
5467
5468@item Default Value: @code{false}
5469@end itemize
5470@c parse.assert
5471
31b850d2
AD
5472
5473@c ================================================== parse.error
5474@item parse.error
5475@findex %define parse.error
5476@itemize
5477@item Languages(s):
fcf834f9 5478all
31b850d2
AD
5479@item Purpose:
5480Control the kind of error messages passed to the error reporting
5481function. @xref{Error Reporting, ,The Error Reporting Function
5482@code{yyerror}}.
5483@item Accepted Values:
5484@itemize
cf499cff 5485@item @code{simple}
31b850d2
AD
5486Error messages passed to @code{yyerror} are simply @w{@code{"syntax
5487error"}}.
cf499cff 5488@item @code{verbose}
31b850d2
AD
5489Error messages report the unexpected token, and possibly the expected
5490ones.
5491@end itemize
5492
5493@item Default Value:
5494@code{simple}
5495@end itemize
5496@c parse.error
5497
5498
fcf834f9
JD
5499@c ================================================== parse.lac
5500@item parse.lac
5501@findex %define parse.lac
8a4281b9 5502@cindex LAC
fcf834f9
JD
5503@cindex lookahead correction
5504
5505@itemize
5506@item Languages(s): C
5507
8a4281b9 5508@item Purpose: Enable LAC (lookahead correction) to improve
fcf834f9
JD
5509syntax error handling.
5510
8a4281b9 5511Canonical LR, IELR, and LALR can suffer
fcf834f9
JD
5512from a couple of problems upon encountering a syntax error. First, the
5513parser might perform additional parser stack reductions before
5514discovering the syntax error. Such reductions perform user semantic
5515actions that are unexpected because they are based on an invalid token,
5516and they cause error recovery to begin in a different syntactic context
5517than the one in which the invalid token was encountered. Second, when
5518verbose error messages are enabled (with @code{%error-verbose} or
5519@code{#define YYERROR_VERBOSE}), the expected token list in the syntax
5520error message can both contain invalid tokens and omit valid tokens.
5521
5522The culprits for the above problems are @code{%nonassoc}, default
5523reductions in inconsistent states, and parser state merging. Thus,
8a4281b9
JD
5524IELR and LALR suffer the most. Canonical
5525LR can suffer only if @code{%nonassoc} is used or if default
fcf834f9
JD
5526reductions are enabled for inconsistent states.
5527
8a4281b9
JD
5528LAC is a new mechanism within the parsing algorithm that
5529completely solves these problems for canonical LR,
5530IELR, and LALR without sacrificing @code{%nonassoc},
fcf834f9
JD
5531default reductions, or state mering. Conceptually, the mechanism is
5532straight-forward. Whenever the parser fetches a new token from the
5533scanner so that it can determine the next parser action, it immediately
5534suspends normal parsing and performs an exploratory parse using a
5535temporary copy of the normal parser state stack. During this
5536exploratory parse, the parser does not perform user semantic actions.
5537If the exploratory parse reaches a shift action, normal parsing then
5538resumes on the normal parser stacks. If the exploratory parse reaches
5539an error instead, the parser reports a syntax error. If verbose syntax
5540error messages are enabled, the parser must then discover the list of
5541expected tokens, so it performs a separate exploratory parse for each
5542token in the grammar.
5543
8a4281b9 5544There is one subtlety about the use of LAC. That is, when in
fcf834f9
JD
5545a consistent parser state with a default reduction, the parser will not
5546attempt to fetch a token from the scanner because no lookahead is needed
5547to determine the next parser action. Thus, whether default reductions
5548are enabled in consistent states (@pxref{Decl
5549Summary,,lr.default-reductions}) affects how soon the parser detects a
5550syntax error: when it @emph{reaches} an erroneous token or when it
5551eventually @emph{needs} that token as a lookahead. The latter behavior
5552is probably more intuitive, so Bison currently provides no way to
5553achieve the former behavior while default reductions are fully enabled.
5554
8a4281b9 5555Thus, when LAC is in use, for some fixed decision of whether
fcf834f9 5556to enable default reductions in consistent states, canonical
8a4281b9 5557LR and IELR behave exactly the same for both
fcf834f9 5558syntactically acceptable and syntactically unacceptable input. While
8a4281b9
JD
5559LALR still does not support the full language-recognition
5560power of canonical LR and IELR, LAC at
5561least enables LALR's syntax error handling to correctly
5562reflect LALR's language-recognition power.
fcf834f9 5563
8a4281b9 5564Because LAC requires many parse actions to be performed twice,
fcf834f9
JD
5565it can have a performance penalty. However, not all parse actions must
5566be performed twice. Specifically, during a series of default reductions
5567in consistent states and shift actions, the parser never has to initiate
5568an exploratory parse. Moreover, the most time-consuming tasks in a
5569parse are often the file I/O, the lexical analysis performed by the
5570scanner, and the user's semantic actions, but none of these are
5571performed during the exploratory parse. Finally, the base of the
5572temporary stack used during an exploratory parse is a pointer into the
5573normal parser state stack so that the stack is never physically copied.
8a4281b9 5574In our experience, the performance penalty of LAC has proven
fcf834f9
JD
5575insignificant for practical grammars.
5576
5577@item Accepted Values: @code{none}, @code{full}
5578
5579@item Default Value: @code{none}
5580@end itemize
5581@c parse.lac
5582
31b850d2 5583@c ================================================== parse.trace
fa819509
AD
5584@item parse.trace
5585@findex %define parse.trace
5586
5587@itemize
5588@item Languages(s): C, C++
5589
5590@item Purpose: Require parser instrumentation for tracing.
ff7571c0
JD
5591In C/C++, define the macro @code{YYDEBUG} to 1 in the parser implementation
5592file if it is not already defined, so that the debugging facilities are
5593compiled. @xref{Tracing, ,Tracing Your Parser}.
793fbca5 5594
fa819509
AD
5595@item Accepted Values: Boolean
5596
5597@item Default Value: @code{false}
5598@end itemize
fa819509 5599@c parse.trace
99c08fb6 5600
3cdc21cf
AD
5601@c ================================================== variant
5602@item variant
5603@findex %define variant
5604
5605@itemize @bullet
5606@item Language(s):
5607C++
5608
5609@item Purpose:
f1b238df 5610Request variant-based semantic values.
3cdc21cf
AD
5611@xref{C++ Variants}.
5612
5613@item Accepted Values:
5614Boolean.
5615
5616@item Default Value:
5617@code{false}
5618@end itemize
5619@c variant
5620
5621
99c08fb6 5622@end table
d782395d 5623@end deffn
99c08fb6 5624@c ---------------------------------------------------------- %define
d782395d 5625
18b519c0 5626@deffn {Directive} %defines
ff7571c0
JD
5627Write a parser header file containing macro definitions for the token
5628type names defined in the grammar as well as a few other declarations.
5629If the parser implementation file is named @file{@var{name}.c} then
5630the parser header file is named @file{@var{name}.h}.
d8988b2f 5631
ff7571c0 5632For C parsers, the parser header file declares @code{YYSTYPE} unless
ddc8ede1 5633@code{YYSTYPE} is already defined as a macro or you have used a
ff7571c0
JD
5634@code{<@var{type}>} tag without using @code{%union}. Therefore, if
5635you are using a @code{%union} (@pxref{Multiple Types, ,More Than One
5636Value Type}) with components that require other definitions, or if you
5637have defined a @code{YYSTYPE} macro or type definition (@pxref{Value
5638Type, ,Data Types of Semantic Values}), you need to arrange for these
5639definitions to be propagated to all modules, e.g., by putting them in
5640a prerequisite header that is included both by your parser and by any
5641other module that needs @code{YYSTYPE}.
5642
5643Unless your parser is pure, the parser header file declares
5644@code{yylval} as an external variable. @xref{Pure Decl, ,A Pure
5645(Reentrant) Parser}.
5646
5647If you have also used locations, the parser header file declares
4bfd5e4e 5648@code{YYLTYPE} and @code{yylloc} using a protocol similar to that of
ff7571c0
JD
5649the @code{YYSTYPE} macro and @code{yylval}. @xref{Locations,
5650,Tracking Locations}.
4bfd5e4e 5651
ff7571c0
JD
5652This parser header file is normally essential if you wish to put the
5653definition of @code{yylex} in a separate source file, because
5654@code{yylex} typically needs to be able to refer to the
5655above-mentioned declarations and to the token type codes. @xref{Token
5656Values, ,Semantic Values of Tokens}.
9bc0dd67 5657
16dc6a9e
JD
5658@findex %code requires
5659@findex %code provides
5660If you have declared @code{%code requires} or @code{%code provides}, the output
5661header also contains their code.
148d66d8 5662@xref{Decl Summary, ,%code}.
592d0b1e
PB
5663@end deffn
5664
02975b9a
JD
5665@deffn {Directive} %defines @var{defines-file}
5666Same as above, but save in the file @var{defines-file}.
5667@end deffn
5668
18b519c0 5669@deffn {Directive} %destructor
258b75ca 5670Specify how the parser should reclaim the memory associated to
fa7e68c3 5671discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
18b519c0 5672@end deffn
72f889cc 5673
02975b9a 5674@deffn {Directive} %file-prefix "@var{prefix}"
ff7571c0
JD
5675Specify a prefix to use for all Bison output file names. The names
5676are chosen as if the grammar file were named @file{@var{prefix}.y}.
18b519c0 5677@end deffn
d8988b2f 5678
e6e704dc 5679@deffn {Directive} %language "@var{language}"
0e021770 5680Specify the programming language for the generated parser. Currently
59da312b 5681supported languages include C, C++, and Java.
e6e704dc 5682@var{language} is case-insensitive.
ed4d67dc
JD
5683
5684This directive is experimental and its effect may be modified in future
5685releases.
0e021770
PE
5686@end deffn
5687
18b519c0 5688@deffn {Directive} %locations
89cab50d
AD
5689Generate the code processing the locations (@pxref{Action Features,
5690,Special Features for Use in Actions}). This mode is enabled as soon as
5691the grammar uses the special @samp{@@@var{n}} tokens, but if your
5692grammar does not use it, using @samp{%locations} allows for more
6e649e65 5693accurate syntax error messages.
18b519c0 5694@end deffn
89cab50d 5695
02975b9a 5696@deffn {Directive} %name-prefix "@var{prefix}"
d8988b2f
AD
5697Rename the external symbols used in the parser so that they start with
5698@var{prefix} instead of @samp{yy}. The precise list of symbols renamed
aa08666d 5699in C parsers
d8988b2f 5700is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
91e3ac9a 5701@code{yylval}, @code{yychar}, @code{yydebug}, and
f4101aa6
AD
5702(if locations are used) @code{yylloc}. If you use a push parser,
5703@code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
5704@code{yypstate_new} and @code{yypstate_delete} will
5705also be renamed. For example, if you use @samp{%name-prefix "c_"}, the
793fbca5 5706names become @code{c_parse}, @code{c_lex}, and so on.
67501061 5707For C++ parsers, see the @samp{%define api.namespace} documentation in this
793fbca5 5708section.
aa08666d 5709@xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
18b519c0 5710@end deffn
931c7513 5711
91d2c560 5712@ifset defaultprec
22fccf95
PE
5713@deffn {Directive} %no-default-prec
5714Do not assign a precedence to rules lacking an explicit @code{%prec}
5715modifier (@pxref{Contextual Precedence, ,Context-Dependent
5716Precedence}).
5717@end deffn
91d2c560 5718@end ifset
22fccf95 5719
18b519c0 5720@deffn {Directive} %no-lines
931c7513 5721Don't generate any @code{#line} preprocessor commands in the parser
ff7571c0
JD
5722implementation file. Ordinarily Bison writes these commands in the
5723parser implementation file so that the C compiler and debuggers will
5724associate errors and object code with your source file (the grammar
5725file). This directive causes them to associate errors with the parser
5726implementation file, treating it as an independent source file in its
5727own right.
18b519c0 5728@end deffn
931c7513 5729
02975b9a 5730@deffn {Directive} %output "@var{file}"
ff7571c0 5731Specify @var{file} for the parser implementation file.
18b519c0 5732@end deffn
6deb4447 5733
18b519c0 5734@deffn {Directive} %pure-parser
67501061 5735Deprecated version of @samp{%define api.pure} (@pxref{Decl Summary, ,%define}),
d9df47b6 5736for which Bison is more careful to warn about unreasonable usage.
18b519c0 5737@end deffn
6deb4447 5738
b50d2359 5739@deffn {Directive} %require "@var{version}"
9b8a5ce0
AD
5740Require version @var{version} or higher of Bison. @xref{Require Decl, ,
5741Require a Version of Bison}.
b50d2359
AD
5742@end deffn
5743
0e021770 5744@deffn {Directive} %skeleton "@var{file}"
a7867f53
JD
5745Specify the skeleton to use.
5746
ed4d67dc
JD
5747@c You probably don't need this option unless you are developing Bison.
5748@c You should use @code{%language} if you want to specify the skeleton for a
5749@c different language, because it is clearer and because it will always choose the
5750@c correct skeleton for non-deterministic or push parsers.
a7867f53
JD
5751
5752If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
5753file in the Bison installation directory.
5754If it does, @var{file} is an absolute file name or a file name relative to the
5755directory of the grammar file.
5756This is similar to how most shells resolve commands.
0e021770
PE
5757@end deffn
5758
18b519c0 5759@deffn {Directive} %token-table
ff7571c0
JD
5760Generate an array of token names in the parser implementation file.
5761The name of the array is @code{yytname}; @code{yytname[@var{i}]} is
5762the name of the token whose internal Bison token code number is
5763@var{i}. The first three elements of @code{yytname} correspond to the
5764predefined tokens @code{"$end"}, @code{"error"}, and
5765@code{"$undefined"}; after these come the symbols defined in the
5766grammar file.
931c7513 5767
9e0876fb
PE
5768The name in the table includes all the characters needed to represent
5769the token in Bison. For single-character literals and literal
5770strings, this includes the surrounding quoting characters and any
5771escape sequences. For example, the Bison single-character literal
5772@code{'+'} corresponds to a three-character name, represented in C as
5773@code{"'+'"}; and the Bison two-character literal string @code{"\\/"}
5774corresponds to a five-character name, represented in C as
5775@code{"\"\\\\/\""}.
931c7513 5776
8c9a50be 5777When you specify @code{%token-table}, Bison also generates macro
931c7513
RS
5778definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
5779@code{YYNRULES}, and @code{YYNSTATES}:
5780
5781@table @code
5782@item YYNTOKENS
5783The highest token number, plus one.
5784@item YYNNTS
9ecbd125 5785The number of nonterminal symbols.
931c7513
RS
5786@item YYNRULES
5787The number of grammar rules,
5788@item YYNSTATES
5789The number of parser states (@pxref{Parser States}).
5790@end table
18b519c0 5791@end deffn
d8988b2f 5792
18b519c0 5793@deffn {Directive} %verbose
d8988b2f 5794Write an extra output file containing verbose descriptions of the
742e4900 5795parser states and what is done for each type of lookahead token in
72d2299c 5796that state. @xref{Understanding, , Understanding Your Parser}, for more
ec3bc396 5797information.
18b519c0 5798@end deffn
d8988b2f 5799
18b519c0 5800@deffn {Directive} %yacc
d8988b2f
AD
5801Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
5802including its naming conventions. @xref{Bison Options}, for more.
18b519c0 5803@end deffn
d8988b2f
AD
5804
5805
342b8b6e 5806@node Multiple Parsers
bfa74976
RS
5807@section Multiple Parsers in the Same Program
5808
5809Most programs that use Bison parse only one language and therefore contain
5810only one Bison parser. But what if you want to parse more than one
5811language with the same program? Then you need to avoid a name conflict
5812between different definitions of @code{yyparse}, @code{yylval}, and so on.
5813
5814The easy way to do this is to use the option @samp{-p @var{prefix}}
704a47c4
AD
5815(@pxref{Invocation, ,Invoking Bison}). This renames the interface
5816functions and variables of the Bison parser to start with @var{prefix}
5817instead of @samp{yy}. You can use this to give each parser distinct
5818names that do not conflict.
bfa74976
RS
5819
5820The precise list of symbols renamed is @code{yyparse}, @code{yylex},
2a8d363a 5821@code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yylloc},
f4101aa6
AD
5822@code{yychar} and @code{yydebug}. If you use a push parser,
5823@code{yypush_parse}, @code{yypull_parse}, @code{yypstate},
9987d1b3 5824@code{yypstate_new} and @code{yypstate_delete} will also be renamed.
f4101aa6 5825For example, if you use @samp{-p c}, the names become @code{cparse},
9987d1b3 5826@code{clex}, and so on.
bfa74976
RS
5827
5828@strong{All the other variables and macros associated with Bison are not
5829renamed.} These others are not global; there is no conflict if the same
5830name is used in different parsers. For example, @code{YYSTYPE} is not
5831renamed, but defining this in different ways in different parsers causes
5832no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
5833
ff7571c0
JD
5834The @samp{-p} option works by adding macro definitions to the
5835beginning of the parser implementation file, defining @code{yyparse}
5836as @code{@var{prefix}parse}, and so on. This effectively substitutes
5837one name for the other in the entire parser implementation file.
bfa74976 5838
342b8b6e 5839@node Interface
bfa74976
RS
5840@chapter Parser C-Language Interface
5841@cindex C-language interface
5842@cindex interface
5843
5844The Bison parser is actually a C function named @code{yyparse}. Here we
5845describe the interface conventions of @code{yyparse} and the other
5846functions that it needs to use.
5847
5848Keep in mind that the parser uses many C identifiers starting with
5849@samp{yy} and @samp{YY} for internal purposes. If you use such an
75f5aaea
MA
5850identifier (aside from those in this manual) in an action or in epilogue
5851in the grammar file, you are likely to run into trouble.
bfa74976
RS
5852
5853@menu
f5f419de
DJ
5854* Parser Function:: How to call @code{yyparse} and what it returns.
5855* Push Parser Function:: How to call @code{yypush_parse} and what it returns.
5856* Pull Parser Function:: How to call @code{yypull_parse} and what it returns.
5857* Parser Create Function:: How to call @code{yypstate_new} and what it returns.
5858* Parser Delete Function:: How to call @code{yypstate_delete} and what it returns.
5859* Lexical:: You must supply a function @code{yylex}
5860 which reads tokens.
5861* Error Reporting:: You must supply a function @code{yyerror}.
5862* Action Features:: Special features for use in actions.
5863* Internationalization:: How to let the parser speak in the user's
5864 native language.
bfa74976
RS
5865@end menu
5866
342b8b6e 5867@node Parser Function
bfa74976
RS
5868@section The Parser Function @code{yyparse}
5869@findex yyparse
5870
5871You call the function @code{yyparse} to cause parsing to occur. This
5872function reads tokens, executes actions, and ultimately returns when it
5873encounters end-of-input or an unrecoverable syntax error. You can also
14ded682
AD
5874write an action which directs @code{yyparse} to return immediately
5875without reading further.
bfa74976 5876
2a8d363a
AD
5877
5878@deftypefun int yyparse (void)
bfa74976
RS
5879The value returned by @code{yyparse} is 0 if parsing was successful (return
5880is due to end-of-input).
5881
b47dbebe
PE
5882The value is 1 if parsing failed because of invalid input, i.e., input
5883that contains a syntax error or that causes @code{YYABORT} to be
5884invoked.
5885
5886The value is 2 if parsing failed due to memory exhaustion.
2a8d363a 5887@end deftypefun
bfa74976
RS
5888
5889In an action, you can cause immediate return from @code{yyparse} by using
5890these macros:
5891
2a8d363a 5892@defmac YYACCEPT
bfa74976
RS
5893@findex YYACCEPT
5894Return immediately with value 0 (to report success).
2a8d363a 5895@end defmac
bfa74976 5896
2a8d363a 5897@defmac YYABORT
bfa74976
RS
5898@findex YYABORT
5899Return immediately with value 1 (to report failure).
2a8d363a
AD
5900@end defmac
5901
5902If you use a reentrant parser, you can optionally pass additional
5903parameter information to it in a reentrant way. To do so, use the
5904declaration @code{%parse-param}:
5905
2055a44e 5906@deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
2a8d363a 5907@findex %parse-param
2055a44e
AD
5908Declare that one or more
5909@var{argument-declaration} are additional @code{yyparse} arguments.
94175978 5910The @var{argument-declaration} is used when declaring
feeb0eda
PE
5911functions or prototypes. The last identifier in
5912@var{argument-declaration} must be the argument name.
2a8d363a
AD
5913@end deffn
5914
5915Here's an example. Write this in the parser:
5916
5917@example
2055a44e 5918%parse-param @{int *nastiness@} @{int *randomness@}
2a8d363a
AD
5919@end example
5920
5921@noindent
5922Then call the parser like this:
5923
5924@example
5925@{
5926 int nastiness, randomness;
5927 @dots{} /* @r{Store proper data in @code{nastiness} and @code{randomness}.} */
5928 value = yyparse (&nastiness, &randomness);
5929 @dots{}
5930@}
5931@end example
5932
5933@noindent
5934In the grammar actions, use expressions like this to refer to the data:
5935
5936@example
5937exp: @dots{} @{ @dots{}; *randomness += 1; @dots{} @}
5938@end example
5939
9987d1b3
JD
5940@node Push Parser Function
5941@section The Push Parser Function @code{yypush_parse}
5942@findex yypush_parse
5943
59da312b
JD
5944(The current push parsing interface is experimental and may evolve.
5945More user feedback will help to stabilize it.)
5946
f4101aa6 5947You call the function @code{yypush_parse} to parse a single token. This
cf499cff
JD
5948function is available if either the @samp{%define api.push-pull push} or
5949@samp{%define api.push-pull both} declaration is used.
9987d1b3
JD
5950@xref{Push Decl, ,A Push Parser}.
5951
5952@deftypefun int yypush_parse (yypstate *yyps)
f4101aa6 5953The value returned by @code{yypush_parse} is the same as for yyparse with the
9987d1b3
JD
5954following exception. @code{yypush_parse} will return YYPUSH_MORE if more input
5955is required to finish parsing the grammar.
5956@end deftypefun
5957
5958@node Pull Parser Function
5959@section The Pull Parser Function @code{yypull_parse}
5960@findex yypull_parse
5961
59da312b
JD
5962(The current push parsing interface is experimental and may evolve.
5963More user feedback will help to stabilize it.)
5964
f4101aa6 5965You call the function @code{yypull_parse} to parse the rest of the input
cf499cff 5966stream. This function is available if the @samp{%define api.push-pull both}
f4101aa6 5967declaration is used.
9987d1b3
JD
5968@xref{Push Decl, ,A Push Parser}.
5969
5970@deftypefun int yypull_parse (yypstate *yyps)
5971The value returned by @code{yypull_parse} is the same as for @code{yyparse}.
5972@end deftypefun
5973
5974@node Parser Create Function
5975@section The Parser Create Function @code{yystate_new}
5976@findex yypstate_new
5977
59da312b
JD
5978(The current push parsing interface is experimental and may evolve.
5979More user feedback will help to stabilize it.)
5980
f4101aa6 5981You call the function @code{yypstate_new} to create a new parser instance.
cf499cff
JD
5982This function is available if either the @samp{%define api.push-pull push} or
5983@samp{%define api.push-pull both} declaration is used.
9987d1b3
JD
5984@xref{Push Decl, ,A Push Parser}.
5985
5986@deftypefun yypstate *yypstate_new (void)
f50bfcd6 5987The function will return a valid parser instance if there was memory available
333e670c
JD
5988or 0 if no memory was available.
5989In impure mode, it will also return 0 if a parser instance is currently
5990allocated.
9987d1b3
JD
5991@end deftypefun
5992
5993@node Parser Delete Function
5994@section The Parser Delete Function @code{yystate_delete}
5995@findex yypstate_delete
5996
59da312b
JD
5997(The current push parsing interface is experimental and may evolve.
5998More user feedback will help to stabilize it.)
5999
9987d1b3 6000You call the function @code{yypstate_delete} to delete a parser instance.
cf499cff
JD
6001function is available if either the @samp{%define api.push-pull push} or
6002@samp{%define api.push-pull both} declaration is used.
9987d1b3
JD
6003@xref{Push Decl, ,A Push Parser}.
6004
6005@deftypefun void yypstate_delete (yypstate *yyps)
6006This function will reclaim the memory associated with a parser instance.
6007After this call, you should no longer attempt to use the parser instance.
6008@end deftypefun
bfa74976 6009
342b8b6e 6010@node Lexical
bfa74976
RS
6011@section The Lexical Analyzer Function @code{yylex}
6012@findex yylex
6013@cindex lexical analyzer
6014
6015The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
6016the input stream and returns them to the parser. Bison does not create
6017this function automatically; you must write it so that @code{yyparse} can
6018call it. The function is sometimes referred to as a lexical scanner.
6019
ff7571c0
JD
6020In simple programs, @code{yylex} is often defined at the end of the
6021Bison grammar file. If @code{yylex} is defined in a separate source
6022file, you need to arrange for the token-type macro definitions to be
6023available there. To do this, use the @samp{-d} option when you run
6024Bison, so that it will write these macro definitions into the separate
6025parser header file, @file{@var{name}.tab.h}, which you can include in
6026the other source files that need it. @xref{Invocation, ,Invoking
6027Bison}.
bfa74976
RS
6028
6029@menu
6030* Calling Convention:: How @code{yyparse} calls @code{yylex}.
f5f419de
DJ
6031* Token Values:: How @code{yylex} must return the semantic value
6032 of the token it has read.
6033* Token Locations:: How @code{yylex} must return the text location
6034 (line number, etc.) of the token, if the
6035 actions want that.
6036* Pure Calling:: How the calling convention differs in a pure parser
6037 (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
bfa74976
RS
6038@end menu
6039
342b8b6e 6040@node Calling Convention
bfa74976
RS
6041@subsection Calling Convention for @code{yylex}
6042
72d2299c
PE
6043The value that @code{yylex} returns must be the positive numeric code
6044for the type of token it has just found; a zero or negative value
6045signifies end-of-input.
bfa74976
RS
6046
6047When a token is referred to in the grammar rules by a name, that name
ff7571c0
JD
6048in the parser implementation file becomes a C macro whose definition
6049is the proper numeric code for that token type. So @code{yylex} can
6050use the name to indicate that type. @xref{Symbols}.
bfa74976
RS
6051
6052When a token is referred to in the grammar rules by a character literal,
6053the numeric code for that character is also the code for the token type.
72d2299c
PE
6054So @code{yylex} can simply return that character code, possibly converted
6055to @code{unsigned char} to avoid sign-extension. The null character
6056must not be used this way, because its code is zero and that
bfa74976
RS
6057signifies end-of-input.
6058
6059Here is an example showing these things:
6060
6061@example
13863333
AD
6062int
6063yylex (void)
bfa74976
RS
6064@{
6065 @dots{}
72d2299c 6066 if (c == EOF) /* Detect end-of-input. */
bfa74976
RS
6067 return 0;
6068 @dots{}
6069 if (c == '+' || c == '-')
72d2299c 6070 return c; /* Assume token type for `+' is '+'. */
bfa74976 6071 @dots{}
72d2299c 6072 return INT; /* Return the type of the token. */
bfa74976
RS
6073 @dots{}
6074@}
6075@end example
6076
6077@noindent
6078This interface has been designed so that the output from the @code{lex}
6079utility can be used without change as the definition of @code{yylex}.
6080
931c7513
RS
6081If the grammar uses literal string tokens, there are two ways that
6082@code{yylex} can determine the token type codes for them:
6083
6084@itemize @bullet
6085@item
6086If the grammar defines symbolic token names as aliases for the
6087literal string tokens, @code{yylex} can use these symbolic names like
6088all others. In this case, the use of the literal string tokens in
6089the grammar file has no effect on @code{yylex}.
6090
6091@item
9ecbd125 6092@code{yylex} can find the multicharacter token in the @code{yytname}
931c7513 6093table. The index of the token in the table is the token type's code.
9ecbd125 6094The name of a multicharacter token is recorded in @code{yytname} with a
931c7513 6095double-quote, the token's characters, and another double-quote. The
9e0876fb
PE
6096token's characters are escaped as necessary to be suitable as input
6097to Bison.
931c7513 6098
9e0876fb
PE
6099Here's code for looking up a multicharacter token in @code{yytname},
6100assuming that the characters of the token are stored in
6101@code{token_buffer}, and assuming that the token does not contain any
6102characters like @samp{"} that require escaping.
931c7513
RS
6103
6104@smallexample
6105for (i = 0; i < YYNTOKENS; i++)
6106 @{
6107 if (yytname[i] != 0
6108 && yytname[i][0] == '"'
68449b3a
PE
6109 && ! strncmp (yytname[i] + 1, token_buffer,
6110 strlen (token_buffer))
931c7513
RS
6111 && yytname[i][strlen (token_buffer) + 1] == '"'
6112 && yytname[i][strlen (token_buffer) + 2] == 0)
6113 break;
6114 @}
6115@end smallexample
6116
6117The @code{yytname} table is generated only if you use the
8c9a50be 6118@code{%token-table} declaration. @xref{Decl Summary}.
931c7513
RS
6119@end itemize
6120
342b8b6e 6121@node Token Values
bfa74976
RS
6122@subsection Semantic Values of Tokens
6123
6124@vindex yylval
9d9b8b70 6125In an ordinary (nonreentrant) parser, the semantic value of the token must
bfa74976
RS
6126be stored into the global variable @code{yylval}. When you are using
6127just one data type for semantic values, @code{yylval} has that type.
6128Thus, if the type is @code{int} (the default), you might write this in
6129@code{yylex}:
6130
6131@example
6132@group
6133 @dots{}
72d2299c
PE
6134 yylval = value; /* Put value onto Bison stack. */
6135 return INT; /* Return the type of the token. */
bfa74976
RS
6136 @dots{}
6137@end group
6138@end example
6139
6140When you are using multiple data types, @code{yylval}'s type is a union
704a47c4
AD
6141made from the @code{%union} declaration (@pxref{Union Decl, ,The
6142Collection of Value Types}). So when you store a token's value, you
6143must use the proper member of the union. If the @code{%union}
6144declaration looks like this:
bfa74976
RS
6145
6146@example
6147@group
6148%union @{
6149 int intval;
6150 double val;
6151 symrec *tptr;
6152@}
6153@end group
6154@end example
6155
6156@noindent
6157then the code in @code{yylex} might look like this:
6158
6159@example
6160@group
6161 @dots{}
72d2299c
PE
6162 yylval.intval = value; /* Put value onto Bison stack. */
6163 return INT; /* Return the type of the token. */
bfa74976
RS
6164 @dots{}
6165@end group
6166@end example
6167
95923bd6
AD
6168@node Token Locations
6169@subsection Textual Locations of Tokens
bfa74976
RS
6170
6171@vindex yylloc
847bf1f5 6172If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
f8e1c9e5
AD
6173Tracking Locations}) in actions to keep track of the textual locations
6174of tokens and groupings, then you must provide this information in
6175@code{yylex}. The function @code{yyparse} expects to find the textual
6176location of a token just parsed in the global variable @code{yylloc}.
6177So @code{yylex} must store the proper data in that variable.
847bf1f5
AD
6178
6179By default, the value of @code{yylloc} is a structure and you need only
89cab50d
AD
6180initialize the members that are going to be used by the actions. The
6181four members are called @code{first_line}, @code{first_column},
6182@code{last_line} and @code{last_column}. Note that the use of this
6183feature makes the parser noticeably slower.
bfa74976
RS
6184
6185@tindex YYLTYPE
6186The data type of @code{yylloc} has the name @code{YYLTYPE}.
6187
342b8b6e 6188@node Pure Calling
c656404a 6189@subsection Calling Conventions for Pure Parsers
bfa74976 6190
67501061 6191When you use the Bison declaration @samp{%define api.pure} to request a
e425e872
RS
6192pure, reentrant parser, the global communication variables @code{yylval}
6193and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
6194Parser}.) In such parsers the two global variables are replaced by
6195pointers passed as arguments to @code{yylex}. You must declare them as
6196shown here, and pass the information back by storing it through those
6197pointers.
bfa74976
RS
6198
6199@example
13863333
AD
6200int
6201yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
bfa74976
RS
6202@{
6203 @dots{}
6204 *lvalp = value; /* Put value onto Bison stack. */
6205 return INT; /* Return the type of the token. */
6206 @dots{}
6207@}
6208@end example
6209
6210If the grammar file does not use the @samp{@@} constructs to refer to
95923bd6 6211textual locations, then the type @code{YYLTYPE} will not be defined. In
bfa74976
RS
6212this case, omit the second argument; @code{yylex} will be called with
6213only one argument.
6214
2055a44e 6215If you wish to pass additional arguments to @code{yylex}, use
2a8d363a 6216@code{%lex-param} just like @code{%parse-param} (@pxref{Parser
2055a44e
AD
6217Function}). To pass additional arguments to both @code{yylex} and
6218@code{yyparse}, use @code{%param}.
e425e872 6219
2055a44e 6220@deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
2a8d363a 6221@findex %lex-param
2055a44e
AD
6222Specify that @var{argument-declaration} are additional @code{yylex} argument
6223declarations. You may pass one or more such declarations, which is
6224equivalent to repeating @code{%lex-param}.
6225@end deffn
6226
6227@deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
6228@findex %param
6229Specify that @var{argument-declaration} are additional
6230@code{yylex}/@code{yyparse} argument declaration. This is equivalent to
6231@samp{%lex-param @{@var{argument-declaration}@} @dots{} %parse-param
6232@{@var{argument-declaration}@} @dots{}}. You may pass one or more
6233declarations, which is equivalent to repeating @code{%param}.
2a8d363a 6234@end deffn
e425e872 6235
2a8d363a 6236For instance:
e425e872
RS
6237
6238@example
2055a44e
AD
6239%lex-param @{scanner_mode *mode@}
6240%parse-param @{parser_mode *mode@}
6241%param @{environment_type *env@}
e425e872
RS
6242@end example
6243
6244@noindent
2a8d363a 6245results in the following signature:
e425e872
RS
6246
6247@example
2055a44e
AD
6248int yylex (scanner_mode *mode, environment_type *env);
6249int yyparse (parser_mode *mode, environment_type *env);
e425e872
RS
6250@end example
6251
67501061 6252If @samp{%define api.pure} is added:
c656404a
RS
6253
6254@example
2055a44e
AD
6255int yylex (YYSTYPE *lvalp, scanner_mode *mode, environment_type *env);
6256int yyparse (parser_mode *mode, environment_type *env);
c656404a
RS
6257@end example
6258
2a8d363a 6259@noindent
67501061 6260and finally, if both @samp{%define api.pure} and @code{%locations} are used:
c656404a 6261
2a8d363a 6262@example
2055a44e
AD
6263int yylex (YYSTYPE *lvalp, YYLTYPE *llocp,
6264 scanner_mode *mode, environment_type *env);
6265int yyparse (parser_mode *mode, environment_type *env);
2a8d363a 6266@end example
931c7513 6267
342b8b6e 6268@node Error Reporting
bfa74976
RS
6269@section The Error Reporting Function @code{yyerror}
6270@cindex error reporting function
6271@findex yyerror
6272@cindex parse error
6273@cindex syntax error
6274
31b850d2 6275The Bison parser detects a @dfn{syntax error} (or @dfn{parse error})
9ecbd125 6276whenever it reads a token which cannot satisfy any syntax rule. An
bfa74976 6277action in the grammar can also explicitly proclaim an error, using the
ceed8467
AD
6278macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
6279in Actions}).
bfa74976
RS
6280
6281The Bison parser expects to report the error by calling an error
6282reporting function named @code{yyerror}, which you must supply. It is
6283called by @code{yyparse} whenever a syntax error is found, and it
6e649e65
PE
6284receives one argument. For a syntax error, the string is normally
6285@w{@code{"syntax error"}}.
bfa74976 6286
31b850d2 6287@findex %define parse.error
cf499cff 6288If you invoke @samp{%define parse.error verbose} in the Bison
2a8d363a
AD
6289declarations section (@pxref{Bison Declarations, ,The Bison Declarations
6290Section}), then Bison provides a more verbose and specific error message
6e649e65 6291string instead of just plain @w{@code{"syntax error"}}.
bfa74976 6292
1a059451
PE
6293The parser can detect one other kind of error: memory exhaustion. This
6294can happen when the input contains constructions that are very deeply
bfa74976 6295nested. It isn't likely you will encounter this, since the Bison
1a059451
PE
6296parser normally extends its stack automatically up to a very large limit. But
6297if memory is exhausted, @code{yyparse} calls @code{yyerror} in the usual
6298fashion, except that the argument string is @w{@code{"memory exhausted"}}.
6299
6300In some cases diagnostics like @w{@code{"syntax error"}} are
6301translated automatically from English to some other language before
6302they are passed to @code{yyerror}. @xref{Internationalization}.
bfa74976
RS
6303
6304The following definition suffices in simple programs:
6305
6306@example
6307@group
13863333 6308void
38a92d50 6309yyerror (char const *s)
bfa74976
RS
6310@{
6311@end group
6312@group
6313 fprintf (stderr, "%s\n", s);
6314@}
6315@end group
6316@end example
6317
6318After @code{yyerror} returns to @code{yyparse}, the latter will attempt
6319error recovery if you have written suitable error recovery grammar rules
6320(@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
6321immediately return 1.
6322
93724f13 6323Obviously, in location tracking pure parsers, @code{yyerror} should have
fa7e68c3 6324an access to the current location.
8a4281b9 6325This is indeed the case for the GLR
2a8d363a 6326parsers, but not for the Yacc parser, for historical reasons. I.e., if
d9df47b6 6327@samp{%locations %define api.pure} is passed then the prototypes for
2a8d363a
AD
6328@code{yyerror} are:
6329
6330@example
38a92d50
PE
6331void yyerror (char const *msg); /* Yacc parsers. */
6332void yyerror (YYLTYPE *locp, char const *msg); /* GLR parsers. */
2a8d363a
AD
6333@end example
6334
feeb0eda 6335If @samp{%parse-param @{int *nastiness@}} is used, then:
2a8d363a
AD
6336
6337@example
b317297e
PE
6338void yyerror (int *nastiness, char const *msg); /* Yacc parsers. */
6339void yyerror (int *nastiness, char const *msg); /* GLR parsers. */
2a8d363a
AD
6340@end example
6341
8a4281b9 6342Finally, GLR and Yacc parsers share the same @code{yyerror} calling
2a8d363a
AD
6343convention for absolutely pure parsers, i.e., when the calling
6344convention of @code{yylex} @emph{and} the calling convention of
67501061 6345@samp{%define api.pure} are pure.
d9df47b6 6346I.e.:
2a8d363a
AD
6347
6348@example
6349/* Location tracking. */
6350%locations
6351/* Pure yylex. */
d9df47b6 6352%define api.pure
feeb0eda 6353%lex-param @{int *nastiness@}
2a8d363a 6354/* Pure yyparse. */
feeb0eda
PE
6355%parse-param @{int *nastiness@}
6356%parse-param @{int *randomness@}
2a8d363a
AD
6357@end example
6358
6359@noindent
6360results in the following signatures for all the parser kinds:
6361
6362@example
6363int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness);
6364int yyparse (int *nastiness, int *randomness);
93724f13
AD
6365void yyerror (YYLTYPE *locp,
6366 int *nastiness, int *randomness,
38a92d50 6367 char const *msg);
2a8d363a
AD
6368@end example
6369
1c0c3e95 6370@noindent
38a92d50
PE
6371The prototypes are only indications of how the code produced by Bison
6372uses @code{yyerror}. Bison-generated code always ignores the returned
6373value, so @code{yyerror} can return any type, including @code{void}.
6374Also, @code{yyerror} can be a variadic function; that is why the
6375message is always passed last.
6376
6377Traditionally @code{yyerror} returns an @code{int} that is always
6378ignored, but this is purely for historical reasons, and @code{void} is
6379preferable since it more accurately describes the return type for
6380@code{yyerror}.
93724f13 6381
bfa74976
RS
6382@vindex yynerrs
6383The variable @code{yynerrs} contains the number of syntax errors
8a2800e7 6384reported so far. Normally this variable is global; but if you
704a47c4
AD
6385request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
6386then it is a local variable which only the actions can access.
bfa74976 6387
342b8b6e 6388@node Action Features
bfa74976
RS
6389@section Special Features for Use in Actions
6390@cindex summary, action features
6391@cindex action features summary
6392
6393Here is a table of Bison constructs, variables and macros that
6394are useful in actions.
6395
18b519c0 6396@deffn {Variable} $$
bfa74976
RS
6397Acts like a variable that contains the semantic value for the
6398grouping made by the current rule. @xref{Actions}.
18b519c0 6399@end deffn
bfa74976 6400
18b519c0 6401@deffn {Variable} $@var{n}
bfa74976
RS
6402Acts like a variable that contains the semantic value for the
6403@var{n}th component of the current rule. @xref{Actions}.
18b519c0 6404@end deffn
bfa74976 6405
18b519c0 6406@deffn {Variable} $<@var{typealt}>$
bfa74976 6407Like @code{$$} but specifies alternative @var{typealt} in the union
704a47c4
AD
6408specified by the @code{%union} declaration. @xref{Action Types, ,Data
6409Types of Values in Actions}.
18b519c0 6410@end deffn
bfa74976 6411
18b519c0 6412@deffn {Variable} $<@var{typealt}>@var{n}
bfa74976 6413Like @code{$@var{n}} but specifies alternative @var{typealt} in the
13863333 6414union specified by the @code{%union} declaration.
e0c471a9 6415@xref{Action Types, ,Data Types of Values in Actions}.
18b519c0 6416@end deffn
bfa74976 6417
18b519c0 6418@deffn {Macro} YYABORT;
bfa74976
RS
6419Return immediately from @code{yyparse}, indicating failure.
6420@xref{Parser Function, ,The Parser Function @code{yyparse}}.
18b519c0 6421@end deffn
bfa74976 6422
18b519c0 6423@deffn {Macro} YYACCEPT;
bfa74976
RS
6424Return immediately from @code{yyparse}, indicating success.
6425@xref{Parser Function, ,The Parser Function @code{yyparse}}.
18b519c0 6426@end deffn
bfa74976 6427
18b519c0 6428@deffn {Macro} YYBACKUP (@var{token}, @var{value});
bfa74976
RS
6429@findex YYBACKUP
6430Unshift a token. This macro is allowed only for rules that reduce
742e4900 6431a single value, and only when there is no lookahead token.
8a4281b9 6432It is also disallowed in GLR parsers.
742e4900 6433It installs a lookahead token with token type @var{token} and
bfa74976
RS
6434semantic value @var{value}; then it discards the value that was
6435going to be reduced by this rule.
6436
6437If the macro is used when it is not valid, such as when there is
742e4900 6438a lookahead token already, then it reports a syntax error with
bfa74976
RS
6439a message @samp{cannot back up} and performs ordinary error
6440recovery.
6441
6442In either case, the rest of the action is not executed.
18b519c0 6443@end deffn
bfa74976 6444
18b519c0 6445@deffn {Macro} YYEMPTY
bfa74976 6446@vindex YYEMPTY
742e4900 6447Value stored in @code{yychar} when there is no lookahead token.
18b519c0 6448@end deffn
bfa74976 6449
32c29292
JD
6450@deffn {Macro} YYEOF
6451@vindex YYEOF
742e4900 6452Value stored in @code{yychar} when the lookahead is the end of the input
32c29292
JD
6453stream.
6454@end deffn
6455
18b519c0 6456@deffn {Macro} YYERROR;
bfa74976
RS
6457@findex YYERROR
6458Cause an immediate syntax error. This statement initiates error
6459recovery just as if the parser itself had detected an error; however, it
6460does not call @code{yyerror}, and does not print any message. If you
6461want to print an error message, call @code{yyerror} explicitly before
6462the @samp{YYERROR;} statement. @xref{Error Recovery}.
18b519c0 6463@end deffn
bfa74976 6464
18b519c0 6465@deffn {Macro} YYRECOVERING
02103984
PE
6466@findex YYRECOVERING
6467The expression @code{YYRECOVERING ()} yields 1 when the parser
6468is recovering from a syntax error, and 0 otherwise.
bfa74976 6469@xref{Error Recovery}.
18b519c0 6470@end deffn
bfa74976 6471
18b519c0 6472@deffn {Variable} yychar
742e4900
JD
6473Variable containing either the lookahead token, or @code{YYEOF} when the
6474lookahead is the end of the input stream, or @code{YYEMPTY} when no lookahead
32c29292
JD
6475has been performed so the next token is not yet known.
6476Do not modify @code{yychar} in a deferred semantic action (@pxref{GLR Semantic
6477Actions}).
742e4900 6478@xref{Lookahead, ,Lookahead Tokens}.
18b519c0 6479@end deffn
bfa74976 6480
18b519c0 6481@deffn {Macro} yyclearin;
742e4900 6482Discard the current lookahead token. This is useful primarily in
32c29292
JD
6483error rules.
6484Do not invoke @code{yyclearin} in a deferred semantic action (@pxref{GLR
6485Semantic Actions}).
6486@xref{Error Recovery}.
18b519c0 6487@end deffn
bfa74976 6488
18b519c0 6489@deffn {Macro} yyerrok;
bfa74976 6490Resume generating error messages immediately for subsequent syntax
13863333 6491errors. This is useful primarily in error rules.
bfa74976 6492@xref{Error Recovery}.
18b519c0 6493@end deffn
bfa74976 6494
32c29292 6495@deffn {Variable} yylloc
742e4900 6496Variable containing the lookahead token location when @code{yychar} is not set
32c29292
JD
6497to @code{YYEMPTY} or @code{YYEOF}.
6498Do not modify @code{yylloc} in a deferred semantic action (@pxref{GLR Semantic
6499Actions}).
6500@xref{Actions and Locations, ,Actions and Locations}.
6501@end deffn
6502
6503@deffn {Variable} yylval
742e4900 6504Variable containing the lookahead token semantic value when @code{yychar} is
32c29292
JD
6505not set to @code{YYEMPTY} or @code{YYEOF}.
6506Do not modify @code{yylval} in a deferred semantic action (@pxref{GLR Semantic
6507Actions}).
6508@xref{Actions, ,Actions}.
6509@end deffn
6510
18b519c0 6511@deffn {Value} @@$
847bf1f5 6512@findex @@$
95923bd6 6513Acts like a structure variable containing information on the textual location
847bf1f5
AD
6514of the grouping made by the current rule. @xref{Locations, ,
6515Tracking Locations}.
bfa74976 6516
847bf1f5
AD
6517@c Check if those paragraphs are still useful or not.
6518
6519@c @example
6520@c struct @{
6521@c int first_line, last_line;
6522@c int first_column, last_column;
6523@c @};
6524@c @end example
6525
6526@c Thus, to get the starting line number of the third component, you would
6527@c use @samp{@@3.first_line}.
bfa74976 6528
847bf1f5
AD
6529@c In order for the members of this structure to contain valid information,
6530@c you must make @code{yylex} supply this information about each token.
6531@c If you need only certain members, then @code{yylex} need only fill in
6532@c those members.
bfa74976 6533
847bf1f5 6534@c The use of this feature makes the parser noticeably slower.
18b519c0 6535@end deffn
847bf1f5 6536
18b519c0 6537@deffn {Value} @@@var{n}
847bf1f5 6538@findex @@@var{n}
95923bd6 6539Acts like a structure variable containing information on the textual location
847bf1f5
AD
6540of the @var{n}th component of the current rule. @xref{Locations, ,
6541Tracking Locations}.
18b519c0 6542@end deffn
bfa74976 6543
f7ab6a50
PE
6544@node Internationalization
6545@section Parser Internationalization
6546@cindex internationalization
6547@cindex i18n
6548@cindex NLS
6549@cindex gettext
6550@cindex bison-po
6551
6552A Bison-generated parser can print diagnostics, including error and
6553tracing messages. By default, they appear in English. However, Bison
f8e1c9e5
AD
6554also supports outputting diagnostics in the user's native language. To
6555make this work, the user should set the usual environment variables.
6556@xref{Users, , The User's View, gettext, GNU @code{gettext} utilities}.
6557For example, the shell command @samp{export LC_ALL=fr_CA.UTF-8} might
8a4281b9 6558set the user's locale to French Canadian using the UTF-8
f7ab6a50
PE
6559encoding. The exact set of available locales depends on the user's
6560installation.
6561
6562The maintainer of a package that uses a Bison-generated parser enables
6563the internationalization of the parser's output through the following
8a4281b9
JD
6564steps. Here we assume a package that uses GNU Autoconf and
6565GNU Automake.
f7ab6a50
PE
6566
6567@enumerate
6568@item
30757c8c 6569@cindex bison-i18n.m4
8a4281b9 6570Into the directory containing the GNU Autoconf macros used
f7ab6a50
PE
6571by the package---often called @file{m4}---copy the
6572@file{bison-i18n.m4} file installed by Bison under
6573@samp{share/aclocal/bison-i18n.m4} in Bison's installation directory.
6574For example:
6575
6576@example
6577cp /usr/local/share/aclocal/bison-i18n.m4 m4/bison-i18n.m4
6578@end example
6579
6580@item
30757c8c
PE
6581@findex BISON_I18N
6582@vindex BISON_LOCALEDIR
6583@vindex YYENABLE_NLS
f7ab6a50
PE
6584In the top-level @file{configure.ac}, after the @code{AM_GNU_GETTEXT}
6585invocation, add an invocation of @code{BISON_I18N}. This macro is
6586defined in the file @file{bison-i18n.m4} that you copied earlier. It
6587causes @samp{configure} to find the value of the
30757c8c
PE
6588@code{BISON_LOCALEDIR} variable, and it defines the source-language
6589symbol @code{YYENABLE_NLS} to enable translations in the
6590Bison-generated parser.
f7ab6a50
PE
6591
6592@item
6593In the @code{main} function of your program, designate the directory
6594containing Bison's runtime message catalog, through a call to
6595@samp{bindtextdomain} with domain name @samp{bison-runtime}.
6596For example:
6597
6598@example
6599bindtextdomain ("bison-runtime", BISON_LOCALEDIR);
6600@end example
6601
6602Typically this appears after any other call @code{bindtextdomain
6603(PACKAGE, LOCALEDIR)} that your package already has. Here we rely on
6604@samp{BISON_LOCALEDIR} to be defined as a string through the
6605@file{Makefile}.
6606
6607@item
6608In the @file{Makefile.am} that controls the compilation of the @code{main}
6609function, make @samp{BISON_LOCALEDIR} available as a C preprocessor macro,
6610either in @samp{DEFS} or in @samp{AM_CPPFLAGS}. For example:
6611
6612@example
6613DEFS = @@DEFS@@ -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6614@end example
6615
6616or:
6617
6618@example
6619AM_CPPFLAGS = -DBISON_LOCALEDIR='"$(BISON_LOCALEDIR)"'
6620@end example
6621
6622@item
6623Finally, invoke the command @command{autoreconf} to generate the build
6624infrastructure.
6625@end enumerate
6626
bfa74976 6627
342b8b6e 6628@node Algorithm
13863333
AD
6629@chapter The Bison Parser Algorithm
6630@cindex Bison parser algorithm
bfa74976
RS
6631@cindex algorithm of parser
6632@cindex shifting
6633@cindex reduction
6634@cindex parser stack
6635@cindex stack, parser
6636
6637As Bison reads tokens, it pushes them onto a stack along with their
6638semantic values. The stack is called the @dfn{parser stack}. Pushing a
6639token is traditionally called @dfn{shifting}.
6640
6641For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
6642@samp{3} to come. The stack will have four elements, one for each token
6643that was shifted.
6644
6645But the stack does not always have an element for each token read. When
6646the last @var{n} tokens and groupings shifted match the components of a
6647grammar rule, they can be combined according to that rule. This is called
6648@dfn{reduction}. Those tokens and groupings are replaced on the stack by a
6649single grouping whose symbol is the result (left hand side) of that rule.
6650Running the rule's action is part of the process of reduction, because this
6651is what computes the semantic value of the resulting grouping.
6652
6653For example, if the infix calculator's parser stack contains this:
6654
6655@example
66561 + 5 * 3
6657@end example
6658
6659@noindent
6660and the next input token is a newline character, then the last three
6661elements can be reduced to 15 via the rule:
6662
6663@example
6664expr: expr '*' expr;
6665@end example
6666
6667@noindent
6668Then the stack contains just these three elements:
6669
6670@example
66711 + 15
6672@end example
6673
6674@noindent
6675At this point, another reduction can be made, resulting in the single value
667616. Then the newline token can be shifted.
6677
6678The parser tries, by shifts and reductions, to reduce the entire input down
6679to a single grouping whose symbol is the grammar's start-symbol
6680(@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
6681
6682This kind of parser is known in the literature as a bottom-up parser.
6683
6684@menu
742e4900 6685* Lookahead:: Parser looks one token ahead when deciding what to do.
bfa74976
RS
6686* Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
6687* Precedence:: Operator precedence works by resolving conflicts.
6688* Contextual Precedence:: When an operator's precedence depends on context.
6689* Parser States:: The parser is a finite-state-machine with stack.
6690* Reduce/Reduce:: When two rules are applicable in the same situation.
f5f419de 6691* Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
676385e2 6692* Generalized LR Parsing:: Parsing arbitrary context-free grammars.
1a059451 6693* Memory Management:: What happens when memory is exhausted. How to avoid it.
bfa74976
RS
6694@end menu
6695
742e4900
JD
6696@node Lookahead
6697@section Lookahead Tokens
6698@cindex lookahead token
bfa74976
RS
6699
6700The Bison parser does @emph{not} always reduce immediately as soon as the
6701last @var{n} tokens and groupings match a rule. This is because such a
6702simple strategy is inadequate to handle most languages. Instead, when a
6703reduction is possible, the parser sometimes ``looks ahead'' at the next
6704token in order to decide what to do.
6705
6706When a token is read, it is not immediately shifted; first it becomes the
742e4900 6707@dfn{lookahead token}, which is not on the stack. Now the parser can
bfa74976 6708perform one or more reductions of tokens and groupings on the stack, while
742e4900
JD
6709the lookahead token remains off to the side. When no more reductions
6710should take place, the lookahead token is shifted onto the stack. This
bfa74976 6711does not mean that all possible reductions have been done; depending on the
742e4900 6712token type of the lookahead token, some rules may choose to delay their
bfa74976
RS
6713application.
6714
742e4900 6715Here is a simple case where lookahead is needed. These three rules define
bfa74976
RS
6716expressions which contain binary addition operators and postfix unary
6717factorial operators (@samp{!}), and allow parentheses for grouping.
6718
6719@example
6720@group
6721expr: term '+' expr
6722 | term
6723 ;
6724@end group
6725
6726@group
6727term: '(' expr ')'
6728 | term '!'
6729 | NUMBER
6730 ;
6731@end group
6732@end example
6733
6734Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
6735should be done? If the following token is @samp{)}, then the first three
6736tokens must be reduced to form an @code{expr}. This is the only valid
6737course, because shifting the @samp{)} would produce a sequence of symbols
6738@w{@code{term ')'}}, and no rule allows this.
6739
6740If the following token is @samp{!}, then it must be shifted immediately so
6741that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
6742parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
6743@code{expr}. It would then be impossible to shift the @samp{!} because
6744doing so would produce on the stack the sequence of symbols @code{expr
6745'!'}. No rule allows that sequence.
6746
6747@vindex yychar
32c29292
JD
6748@vindex yylval
6749@vindex yylloc
742e4900 6750The lookahead token is stored in the variable @code{yychar}.
32c29292
JD
6751Its semantic value and location, if any, are stored in the variables
6752@code{yylval} and @code{yylloc}.
bfa74976
RS
6753@xref{Action Features, ,Special Features for Use in Actions}.
6754
342b8b6e 6755@node Shift/Reduce
bfa74976
RS
6756@section Shift/Reduce Conflicts
6757@cindex conflicts
6758@cindex shift/reduce conflicts
6759@cindex dangling @code{else}
6760@cindex @code{else}, dangling
6761
6762Suppose we are parsing a language which has if-then and if-then-else
6763statements, with a pair of rules like this:
6764
6765@example
6766@group
6767if_stmt:
6768 IF expr THEN stmt
6769 | IF expr THEN stmt ELSE stmt
6770 ;
6771@end group
6772@end example
6773
6774@noindent
6775Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
6776terminal symbols for specific keyword tokens.
6777
742e4900 6778When the @code{ELSE} token is read and becomes the lookahead token, the
bfa74976
RS
6779contents of the stack (assuming the input is valid) are just right for
6780reduction by the first rule. But it is also legitimate to shift the
6781@code{ELSE}, because that would lead to eventual reduction by the second
6782rule.
6783
6784This situation, where either a shift or a reduction would be valid, is
6785called a @dfn{shift/reduce conflict}. Bison is designed to resolve
6786these conflicts by choosing to shift, unless otherwise directed by
6787operator precedence declarations. To see the reason for this, let's
6788contrast it with the other alternative.
6789
6790Since the parser prefers to shift the @code{ELSE}, the result is to attach
6791the else-clause to the innermost if-statement, making these two inputs
6792equivalent:
6793
6794@example
6795if x then if y then win (); else lose;
6796
6797if x then do; if y then win (); else lose; end;
6798@end example
6799
6800But if the parser chose to reduce when possible rather than shift, the
6801result would be to attach the else-clause to the outermost if-statement,
6802making these two inputs equivalent:
6803
6804@example
6805if x then if y then win (); else lose;
6806
6807if x then do; if y then win (); end; else lose;
6808@end example
6809
6810The conflict exists because the grammar as written is ambiguous: either
6811parsing of the simple nested if-statement is legitimate. The established
6812convention is that these ambiguities are resolved by attaching the
6813else-clause to the innermost if-statement; this is what Bison accomplishes
6814by choosing to shift rather than reduce. (It would ideally be cleaner to
6815write an unambiguous grammar, but that is very hard to do in this case.)
6816This particular ambiguity was first encountered in the specifications of
6817Algol 60 and is called the ``dangling @code{else}'' ambiguity.
6818
6819To avoid warnings from Bison about predictable, legitimate shift/reduce
93d7dde9
JD
6820conflicts, use the @code{%expect @var{n}} declaration.
6821There will be no warning as long as the number of shift/reduce conflicts
6822is exactly @var{n}, and Bison will report an error if there is a
6823different number.
bfa74976
RS
6824@xref{Expect Decl, ,Suppressing Conflict Warnings}.
6825
6826The definition of @code{if_stmt} above is solely to blame for the
6827conflict, but the conflict does not actually appear without additional
ff7571c0
JD
6828rules. Here is a complete Bison grammar file that actually manifests
6829the conflict:
bfa74976
RS
6830
6831@example
6832@group
6833%token IF THEN ELSE variable
6834%%
6835@end group
6836@group
6837stmt: expr
6838 | if_stmt
6839 ;
6840@end group
6841
6842@group
6843if_stmt:
6844 IF expr THEN stmt
6845 | IF expr THEN stmt ELSE stmt
6846 ;
6847@end group
6848
6849expr: variable
6850 ;
6851@end example
6852
342b8b6e 6853@node Precedence
bfa74976
RS
6854@section Operator Precedence
6855@cindex operator precedence
6856@cindex precedence of operators
6857
6858Another situation where shift/reduce conflicts appear is in arithmetic
6859expressions. Here shifting is not always the preferred resolution; the
6860Bison declarations for operator precedence allow you to specify when to
6861shift and when to reduce.
6862
6863@menu
6864* Why Precedence:: An example showing why precedence is needed.
d78f0ac9
AD
6865* Using Precedence:: How to specify precedence and associativity.
6866* Precedence Only:: How to specify precedence only.
bfa74976
RS
6867* Precedence Examples:: How these features are used in the previous example.
6868* How Precedence:: How they work.
6869@end menu
6870
342b8b6e 6871@node Why Precedence
bfa74976
RS
6872@subsection When Precedence is Needed
6873
6874Consider the following ambiguous grammar fragment (ambiguous because the
6875input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
6876
6877@example
6878@group
6879expr: expr '-' expr
6880 | expr '*' expr
6881 | expr '<' expr
6882 | '(' expr ')'
6883 @dots{}
6884 ;
6885@end group
6886@end example
6887
6888@noindent
6889Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
14ded682
AD
6890should it reduce them via the rule for the subtraction operator? It
6891depends on the next token. Of course, if the next token is @samp{)}, we
6892must reduce; shifting is invalid because no single rule can reduce the
6893token sequence @w{@samp{- 2 )}} or anything starting with that. But if
6894the next token is @samp{*} or @samp{<}, we have a choice: either
6895shifting or reduction would allow the parse to complete, but with
6896different results.
6897
6898To decide which one Bison should do, we must consider the results. If
6899the next operator token @var{op} is shifted, then it must be reduced
6900first in order to permit another opportunity to reduce the difference.
6901The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
6902hand, if the subtraction is reduced before shifting @var{op}, the result
6903is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
6904reduce should depend on the relative precedence of the operators
6905@samp{-} and @var{op}: @samp{*} should be shifted first, but not
6906@samp{<}.
bfa74976
RS
6907
6908@cindex associativity
6909What about input such as @w{@samp{1 - 2 - 5}}; should this be
14ded682
AD
6910@w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
6911operators we prefer the former, which is called @dfn{left association}.
6912The latter alternative, @dfn{right association}, is desirable for
6913assignment operators. The choice of left or right association is a
6914matter of whether the parser chooses to shift or reduce when the stack
742e4900 6915contains @w{@samp{1 - 2}} and the lookahead token is @samp{-}: shifting
14ded682 6916makes right-associativity.
bfa74976 6917
342b8b6e 6918@node Using Precedence
bfa74976
RS
6919@subsection Specifying Operator Precedence
6920@findex %left
bfa74976 6921@findex %nonassoc
d78f0ac9
AD
6922@findex %precedence
6923@findex %right
bfa74976
RS
6924
6925Bison allows you to specify these choices with the operator precedence
6926declarations @code{%left} and @code{%right}. Each such declaration
6927contains a list of tokens, which are operators whose precedence and
6928associativity is being declared. The @code{%left} declaration makes all
6929those operators left-associative and the @code{%right} declaration makes
6930them right-associative. A third alternative is @code{%nonassoc}, which
6931declares that it is a syntax error to find the same operator twice ``in a
6932row''.
d78f0ac9
AD
6933The last alternative, @code{%precedence}, allows to define only
6934precedence and no associativity at all. As a result, any
6935associativity-related conflict that remains will be reported as an
6936compile-time error. The directive @code{%nonassoc} creates run-time
6937error: using the operator in a associative way is a syntax error. The
6938directive @code{%precedence} creates compile-time errors: an operator
6939@emph{can} be involved in an associativity-related conflict, contrary to
6940what expected the grammar author.
bfa74976
RS
6941
6942The relative precedence of different operators is controlled by the
d78f0ac9
AD
6943order in which they are declared. The first precedence/associativity
6944declaration in the file declares the operators whose
bfa74976
RS
6945precedence is lowest, the next such declaration declares the operators
6946whose precedence is a little higher, and so on.
6947
d78f0ac9
AD
6948@node Precedence Only
6949@subsection Specifying Precedence Only
6950@findex %precedence
6951
8a4281b9 6952Since POSIX Yacc defines only @code{%left}, @code{%right}, and
d78f0ac9
AD
6953@code{%nonassoc}, which all defines precedence and associativity, little
6954attention is paid to the fact that precedence cannot be defined without
6955defining associativity. Yet, sometimes, when trying to solve a
6956conflict, precedence suffices. In such a case, using @code{%left},
6957@code{%right}, or @code{%nonassoc} might hide future (associativity
6958related) conflicts that would remain hidden.
6959
6960The dangling @code{else} ambiguity (@pxref{Shift/Reduce, , Shift/Reduce
f50bfcd6 6961Conflicts}) can be solved explicitly. This shift/reduce conflicts occurs
d78f0ac9
AD
6962in the following situation, where the period denotes the current parsing
6963state:
6964
6965@example
6966if @var{e1} then if @var{e2} then @var{s1} . else @var{s2}
6967@end example
6968
6969The conflict involves the reduction of the rule @samp{IF expr THEN
6970stmt}, which precedence is by default that of its last token
6971(@code{THEN}), and the shifting of the token @code{ELSE}. The usual
6972disambiguation (attach the @code{else} to the closest @code{if}),
6973shifting must be preferred, i.e., the precedence of @code{ELSE} must be
6974higher than that of @code{THEN}. But neither is expected to be involved
6975in an associativity related conflict, which can be specified as follows.
6976
6977@example
6978%precedence THEN
6979%precedence ELSE
6980@end example
6981
6982The unary-minus is another typical example where associativity is
6983usually over-specified, see @ref{Infix Calc, , Infix Notation
f50bfcd6 6984Calculator: @code{calc}}. The @code{%left} directive is traditionally
d78f0ac9
AD
6985used to declare the precedence of @code{NEG}, which is more than needed
6986since it also defines its associativity. While this is harmless in the
6987traditional example, who knows how @code{NEG} might be used in future
6988evolutions of the grammar@dots{}
6989
342b8b6e 6990@node Precedence Examples
bfa74976
RS
6991@subsection Precedence Examples
6992
6993In our example, we would want the following declarations:
6994
6995@example
6996%left '<'
6997%left '-'
6998%left '*'
6999@end example
7000
7001In a more complete example, which supports other operators as well, we
7002would declare them in groups of equal precedence. For example, @code{'+'} is
7003declared with @code{'-'}:
7004
7005@example
7006%left '<' '>' '=' NE LE GE
7007%left '+' '-'
7008%left '*' '/'
7009@end example
7010
7011@noindent
7012(Here @code{NE} and so on stand for the operators for ``not equal''
7013and so on. We assume that these tokens are more than one character long
7014and therefore are represented by names, not character literals.)
7015
342b8b6e 7016@node How Precedence
bfa74976
RS
7017@subsection How Precedence Works
7018
7019The first effect of the precedence declarations is to assign precedence
7020levels to the terminal symbols declared. The second effect is to assign
704a47c4
AD
7021precedence levels to certain rules: each rule gets its precedence from
7022the last terminal symbol mentioned in the components. (You can also
7023specify explicitly the precedence of a rule. @xref{Contextual
7024Precedence, ,Context-Dependent Precedence}.)
7025
7026Finally, the resolution of conflicts works by comparing the precedence
742e4900 7027of the rule being considered with that of the lookahead token. If the
704a47c4
AD
7028token's precedence is higher, the choice is to shift. If the rule's
7029precedence is higher, the choice is to reduce. If they have equal
7030precedence, the choice is made based on the associativity of that
7031precedence level. The verbose output file made by @samp{-v}
7032(@pxref{Invocation, ,Invoking Bison}) says how each conflict was
7033resolved.
bfa74976
RS
7034
7035Not all rules and not all tokens have precedence. If either the rule or
742e4900 7036the lookahead token has no precedence, then the default is to shift.
bfa74976 7037
342b8b6e 7038@node Contextual Precedence
bfa74976
RS
7039@section Context-Dependent Precedence
7040@cindex context-dependent precedence
7041@cindex unary operator precedence
7042@cindex precedence, context-dependent
7043@cindex precedence, unary operator
7044@findex %prec
7045
7046Often the precedence of an operator depends on the context. This sounds
7047outlandish at first, but it is really very common. For example, a minus
7048sign typically has a very high precedence as a unary operator, and a
7049somewhat lower precedence (lower than multiplication) as a binary operator.
7050
d78f0ac9
AD
7051The Bison precedence declarations
7052can only be used once for a given token; so a token has
bfa74976
RS
7053only one precedence declared in this way. For context-dependent
7054precedence, you need to use an additional mechanism: the @code{%prec}
e0c471a9 7055modifier for rules.
bfa74976
RS
7056
7057The @code{%prec} modifier declares the precedence of a particular rule by
7058specifying a terminal symbol whose precedence should be used for that rule.
7059It's not necessary for that symbol to appear otherwise in the rule. The
7060modifier's syntax is:
7061
7062@example
7063%prec @var{terminal-symbol}
7064@end example
7065
7066@noindent
7067and it is written after the components of the rule. Its effect is to
7068assign the rule the precedence of @var{terminal-symbol}, overriding
7069the precedence that would be deduced for it in the ordinary way. The
7070altered rule precedence then affects how conflicts involving that rule
7071are resolved (@pxref{Precedence, ,Operator Precedence}).
7072
7073Here is how @code{%prec} solves the problem of unary minus. First, declare
7074a precedence for a fictitious terminal symbol named @code{UMINUS}. There
7075are no tokens of this type, but the symbol serves to stand for its
7076precedence:
7077
7078@example
7079@dots{}
7080%left '+' '-'
7081%left '*'
7082%left UMINUS
7083@end example
7084
7085Now the precedence of @code{UMINUS} can be used in specific rules:
7086
7087@example
7088@group
7089exp: @dots{}
7090 | exp '-' exp
7091 @dots{}
7092 | '-' exp %prec UMINUS
7093@end group
7094@end example
7095
91d2c560 7096@ifset defaultprec
39a06c25
PE
7097If you forget to append @code{%prec UMINUS} to the rule for unary
7098minus, Bison silently assumes that minus has its usual precedence.
7099This kind of problem can be tricky to debug, since one typically
7100discovers the mistake only by testing the code.
7101
22fccf95 7102The @code{%no-default-prec;} declaration makes it easier to discover
39a06c25
PE
7103this kind of problem systematically. It causes rules that lack a
7104@code{%prec} modifier to have no precedence, even if the last terminal
7105symbol mentioned in their components has a declared precedence.
7106
22fccf95 7107If @code{%no-default-prec;} is in effect, you must specify @code{%prec}
39a06c25
PE
7108for all rules that participate in precedence conflict resolution.
7109Then you will see any shift/reduce conflict until you tell Bison how
7110to resolve it, either by changing your grammar or by adding an
7111explicit precedence. This will probably add declarations to the
7112grammar, but it helps to protect against incorrect rule precedences.
7113
22fccf95
PE
7114The effect of @code{%no-default-prec;} can be reversed by giving
7115@code{%default-prec;}, which is the default.
91d2c560 7116@end ifset
39a06c25 7117
342b8b6e 7118@node Parser States
bfa74976
RS
7119@section Parser States
7120@cindex finite-state machine
7121@cindex parser state
7122@cindex state (of parser)
7123
7124The function @code{yyparse} is implemented using a finite-state machine.
7125The values pushed on the parser stack are not simply token type codes; they
7126represent the entire sequence of terminal and nonterminal symbols at or
7127near the top of the stack. The current state collects all the information
7128about previous input which is relevant to deciding what to do next.
7129
742e4900
JD
7130Each time a lookahead token is read, the current parser state together
7131with the type of lookahead token are looked up in a table. This table
7132entry can say, ``Shift the lookahead token.'' In this case, it also
bfa74976
RS
7133specifies the new parser state, which is pushed onto the top of the
7134parser stack. Or it can say, ``Reduce using rule number @var{n}.''
7135This means that a certain number of tokens or groupings are taken off
7136the top of the stack, and replaced by one grouping. In other words,
7137that number of states are popped from the stack, and one new state is
7138pushed.
7139
742e4900 7140There is one other alternative: the table can say that the lookahead token
bfa74976
RS
7141is erroneous in the current state. This causes error processing to begin
7142(@pxref{Error Recovery}).
7143
342b8b6e 7144@node Reduce/Reduce
bfa74976
RS
7145@section Reduce/Reduce Conflicts
7146@cindex reduce/reduce conflict
7147@cindex conflicts, reduce/reduce
7148
7149A reduce/reduce conflict occurs if there are two or more rules that apply
7150to the same sequence of input. This usually indicates a serious error
7151in the grammar.
7152
7153For example, here is an erroneous attempt to define a sequence
7154of zero or more @code{word} groupings.
7155
7156@example
7157sequence: /* empty */
7158 @{ printf ("empty sequence\n"); @}
7159 | maybeword
7160 | sequence word
7161 @{ printf ("added word %s\n", $2); @}
7162 ;
7163
7164maybeword: /* empty */
7165 @{ printf ("empty maybeword\n"); @}
7166 | word
7167 @{ printf ("single word %s\n", $1); @}
7168 ;
7169@end example
7170
7171@noindent
7172The error is an ambiguity: there is more than one way to parse a single
7173@code{word} into a @code{sequence}. It could be reduced to a
7174@code{maybeword} and then into a @code{sequence} via the second rule.
7175Alternatively, nothing-at-all could be reduced into a @code{sequence}
7176via the first rule, and this could be combined with the @code{word}
7177using the third rule for @code{sequence}.
7178
7179There is also more than one way to reduce nothing-at-all into a
7180@code{sequence}. This can be done directly via the first rule,
7181or indirectly via @code{maybeword} and then the second rule.
7182
7183You might think that this is a distinction without a difference, because it
7184does not change whether any particular input is valid or not. But it does
7185affect which actions are run. One parsing order runs the second rule's
7186action; the other runs the first rule's action and the third rule's action.
7187In this example, the output of the program changes.
7188
7189Bison resolves a reduce/reduce conflict by choosing to use the rule that
7190appears first in the grammar, but it is very risky to rely on this. Every
7191reduce/reduce conflict must be studied and usually eliminated. Here is the
7192proper way to define @code{sequence}:
7193
7194@example
7195sequence: /* empty */
7196 @{ printf ("empty sequence\n"); @}
7197 | sequence word
7198 @{ printf ("added word %s\n", $2); @}
7199 ;
7200@end example
7201
7202Here is another common error that yields a reduce/reduce conflict:
7203
7204@example
7205sequence: /* empty */
7206 | sequence words
7207 | sequence redirects
7208 ;
7209
7210words: /* empty */
7211 | words word
7212 ;
7213
7214redirects:/* empty */
7215 | redirects redirect
7216 ;
7217@end example
7218
7219@noindent
7220The intention here is to define a sequence which can contain either
7221@code{word} or @code{redirect} groupings. The individual definitions of
7222@code{sequence}, @code{words} and @code{redirects} are error-free, but the
7223three together make a subtle ambiguity: even an empty input can be parsed
7224in infinitely many ways!
7225
7226Consider: nothing-at-all could be a @code{words}. Or it could be two
7227@code{words} in a row, or three, or any number. It could equally well be a
7228@code{redirects}, or two, or any number. Or it could be a @code{words}
7229followed by three @code{redirects} and another @code{words}. And so on.
7230
7231Here are two ways to correct these rules. First, to make it a single level
7232of sequence:
7233
7234@example
7235sequence: /* empty */
7236 | sequence word
7237 | sequence redirect
7238 ;
7239@end example
7240
7241Second, to prevent either a @code{words} or a @code{redirects}
7242from being empty:
7243
7244@example
7245sequence: /* empty */
7246 | sequence words
7247 | sequence redirects
7248 ;
7249
7250words: word
7251 | words word
7252 ;
7253
7254redirects:redirect
7255 | redirects redirect
7256 ;
7257@end example
7258
342b8b6e 7259@node Mystery Conflicts
bfa74976
RS
7260@section Mysterious Reduce/Reduce Conflicts
7261
7262Sometimes reduce/reduce conflicts can occur that don't look warranted.
7263Here is an example:
7264
7265@example
7266@group
7267%token ID
7268
7269%%
7270def: param_spec return_spec ','
7271 ;
7272param_spec:
7273 type
7274 | name_list ':' type
7275 ;
7276@end group
7277@group
7278return_spec:
7279 type
7280 | name ':' type
7281 ;
7282@end group
7283@group
7284type: ID
7285 ;
7286@end group
7287@group
7288name: ID
7289 ;
7290name_list:
7291 name
7292 | name ',' name_list
7293 ;
7294@end group
7295@end example
7296
7297It would seem that this grammar can be parsed with only a single token
742e4900 7298of lookahead: when a @code{param_spec} is being read, an @code{ID} is
bfa74976 7299a @code{name} if a comma or colon follows, or a @code{type} if another
8a4281b9 7300@code{ID} follows. In other words, this grammar is LR(1).
bfa74976 7301
8a4281b9
JD
7302@cindex LR(1)
7303@cindex LALR(1)
eb45ef3b 7304However, for historical reasons, Bison cannot by default handle all
8a4281b9 7305LR(1) grammars.
eb45ef3b
JD
7306In this grammar, two contexts, that after an @code{ID} at the beginning
7307of a @code{param_spec} and likewise at the beginning of a
7308@code{return_spec}, are similar enough that Bison assumes they are the
7309same.
7310They appear similar because the same set of rules would be
bfa74976
RS
7311active---the rule for reducing to a @code{name} and that for reducing to
7312a @code{type}. Bison is unable to determine at that stage of processing
742e4900 7313that the rules would require different lookahead tokens in the two
bfa74976
RS
7314contexts, so it makes a single parser state for them both. Combining
7315the two contexts causes a conflict later. In parser terminology, this
8a4281b9 7316occurrence means that the grammar is not LALR(1).
bfa74976 7317
eb45ef3b 7318For many practical grammars (specifically those that fall into the
8a4281b9 7319non-LR(1) class), the limitations of LALR(1) result in
eb45ef3b
JD
7320difficulties beyond just mysterious reduce/reduce conflicts.
7321The best way to fix all these problems is to select a different parser
7322table generation algorithm.
8a4281b9 7323Either IELR(1) or canonical LR(1) would suffice, but
eb45ef3b
JD
7324the former is more efficient and easier to debug during development.
7325@xref{Decl Summary,,lr.type}, for details.
8a4281b9 7326(Bison's IELR(1) and canonical LR(1) implementations
eb45ef3b
JD
7327are experimental.
7328More user feedback will help to stabilize them.)
7329
8a4281b9 7330If you instead wish to work around LALR(1)'s limitations, you
eb45ef3b
JD
7331can often fix a mysterious conflict by identifying the two parser states
7332that are being confused, and adding something to make them look
7333distinct. In the above example, adding one rule to
bfa74976
RS
7334@code{return_spec} as follows makes the problem go away:
7335
7336@example
7337@group
7338%token BOGUS
7339@dots{}
7340%%
7341@dots{}
7342return_spec:
7343 type
7344 | name ':' type
7345 /* This rule is never used. */
7346 | ID BOGUS
7347 ;
7348@end group
7349@end example
7350
7351This corrects the problem because it introduces the possibility of an
7352additional active rule in the context after the @code{ID} at the beginning of
7353@code{return_spec}. This rule is not active in the corresponding context
7354in a @code{param_spec}, so the two contexts receive distinct parser states.
7355As long as the token @code{BOGUS} is never generated by @code{yylex},
7356the added rule cannot alter the way actual input is parsed.
7357
7358In this particular example, there is another way to solve the problem:
7359rewrite the rule for @code{return_spec} to use @code{ID} directly
7360instead of via @code{name}. This also causes the two confusing
7361contexts to have different sets of active rules, because the one for
7362@code{return_spec} activates the altered rule for @code{return_spec}
7363rather than the one for @code{name}.
7364
7365@example
7366param_spec:
7367 type
7368 | name_list ':' type
7369 ;
7370return_spec:
7371 type
7372 | ID ':' type
7373 ;
7374@end example
7375
8a4281b9 7376For a more detailed exposition of LALR(1) parsers and parser
e054b190
PE
7377generators, please see:
7378Frank DeRemer and Thomas Pennello, Efficient Computation of
8a4281b9 7379LALR(1) Look-Ahead Sets, @cite{ACM Transactions on
e054b190
PE
7380Programming Languages and Systems}, Vol.@: 4, No.@: 4 (October 1982),
7381pp.@: 615--649 @uref{http://doi.acm.org/10.1145/69622.357187}.
7382
fae437e8 7383@node Generalized LR Parsing
8a4281b9
JD
7384@section Generalized LR (GLR) Parsing
7385@cindex GLR parsing
7386@cindex generalized LR (GLR) parsing
676385e2 7387@cindex ambiguous grammars
9d9b8b70 7388@cindex nondeterministic parsing
676385e2 7389
fae437e8
AD
7390Bison produces @emph{deterministic} parsers that choose uniquely
7391when to reduce and which reduction to apply
742e4900 7392based on a summary of the preceding input and on one extra token of lookahead.
676385e2
PH
7393As a result, normal Bison handles a proper subset of the family of
7394context-free languages.
fae437e8 7395Ambiguous grammars, since they have strings with more than one possible
676385e2
PH
7396sequence of reductions cannot have deterministic parsers in this sense.
7397The same is true of languages that require more than one symbol of
742e4900 7398lookahead, since the parser lacks the information necessary to make a
676385e2 7399decision at the point it must be made in a shift-reduce parser.
fae437e8 7400Finally, as previously mentioned (@pxref{Mystery Conflicts}),
eb45ef3b 7401there are languages where Bison's default choice of how to
676385e2
PH
7402summarize the input seen so far loses necessary information.
7403
7404When you use the @samp{%glr-parser} declaration in your grammar file,
7405Bison generates a parser that uses a different algorithm, called
8a4281b9 7406Generalized LR (or GLR). A Bison GLR
c827f760 7407parser uses the same basic
676385e2
PH
7408algorithm for parsing as an ordinary Bison parser, but behaves
7409differently in cases where there is a shift-reduce conflict that has not
fae437e8 7410been resolved by precedence rules (@pxref{Precedence}) or a
8a4281b9 7411reduce-reduce conflict. When a GLR parser encounters such a
c827f760 7412situation, it
fae437e8 7413effectively @emph{splits} into a several parsers, one for each possible
676385e2
PH
7414shift or reduction. These parsers then proceed as usual, consuming
7415tokens in lock-step. Some of the stacks may encounter other conflicts
fae437e8 7416and split further, with the result that instead of a sequence of states,
8a4281b9 7417a Bison GLR parsing stack is what is in effect a tree of states.
676385e2
PH
7418
7419In effect, each stack represents a guess as to what the proper parse
7420is. Additional input may indicate that a guess was wrong, in which case
7421the appropriate stack silently disappears. Otherwise, the semantics
fae437e8 7422actions generated in each stack are saved, rather than being executed
676385e2 7423immediately. When a stack disappears, its saved semantic actions never
fae437e8 7424get executed. When a reduction causes two stacks to become equivalent,
676385e2
PH
7425their sets of semantic actions are both saved with the state that
7426results from the reduction. We say that two stacks are equivalent
fae437e8 7427when they both represent the same sequence of states,
676385e2
PH
7428and each pair of corresponding states represents a
7429grammar symbol that produces the same segment of the input token
7430stream.
7431
7432Whenever the parser makes a transition from having multiple
eb45ef3b 7433states to having one, it reverts to the normal deterministic parsing
676385e2
PH
7434algorithm, after resolving and executing the saved-up actions.
7435At this transition, some of the states on the stack will have semantic
7436values that are sets (actually multisets) of possible actions. The
7437parser tries to pick one of the actions by first finding one whose rule
7438has the highest dynamic precedence, as set by the @samp{%dprec}
fae437e8 7439declaration. Otherwise, if the alternative actions are not ordered by
676385e2 7440precedence, but there the same merging function is declared for both
fae437e8 7441rules by the @samp{%merge} declaration,
676385e2
PH
7442Bison resolves and evaluates both and then calls the merge function on
7443the result. Otherwise, it reports an ambiguity.
7444
8a4281b9
JD
7445It is possible to use a data structure for the GLR parsing tree that
7446permits the processing of any LR(1) grammar in linear time (in the
c827f760 7447size of the input), any unambiguous (not necessarily
8a4281b9 7448LR(1)) grammar in
fae437e8 7449quadratic worst-case time, and any general (possibly ambiguous)
676385e2
PH
7450context-free grammar in cubic worst-case time. However, Bison currently
7451uses a simpler data structure that requires time proportional to the
7452length of the input times the maximum number of stacks required for any
9d9b8b70 7453prefix of the input. Thus, really ambiguous or nondeterministic
676385e2
PH
7454grammars can require exponential time and space to process. Such badly
7455behaving examples, however, are not generally of practical interest.
9d9b8b70 7456Usually, nondeterminism in a grammar is local---the parser is ``in
676385e2 7457doubt'' only for a few tokens at a time. Therefore, the current data
8a4281b9 7458structure should generally be adequate. On LR(1) portions of a
eb45ef3b 7459grammar, in particular, it is only slightly slower than with the
8a4281b9 7460deterministic LR(1) Bison parser.
676385e2 7461
8a4281b9 7462For a more detailed exposition of GLR parsers, please see: Elizabeth
f6481e2f 7463Scott, Adrian Johnstone and Shamsa Sadaf Hussain, Tomita-Style
8a4281b9 7464Generalised LR Parsers, Royal Holloway, University of
f6481e2f
PE
7465London, Department of Computer Science, TR-00-12,
7466@uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps},
7467(2000-12-24).
7468
1a059451
PE
7469@node Memory Management
7470@section Memory Management, and How to Avoid Memory Exhaustion
7471@cindex memory exhaustion
7472@cindex memory management
bfa74976
RS
7473@cindex stack overflow
7474@cindex parser stack overflow
7475@cindex overflow of parser stack
7476
1a059451 7477The Bison parser stack can run out of memory if too many tokens are shifted and
bfa74976 7478not reduced. When this happens, the parser function @code{yyparse}
1a059451 7479calls @code{yyerror} and then returns 2.
bfa74976 7480
c827f760 7481Because Bison parsers have growing stacks, hitting the upper limit
d1a1114f
AD
7482usually results from using a right recursion instead of a left
7483recursion, @xref{Recursion, ,Recursive Rules}.
7484
bfa74976
RS
7485@vindex YYMAXDEPTH
7486By defining the macro @code{YYMAXDEPTH}, you can control how deep the
1a059451 7487parser stack can become before memory is exhausted. Define the
bfa74976
RS
7488macro with a value that is an integer. This value is the maximum number
7489of tokens that can be shifted (and not reduced) before overflow.
bfa74976
RS
7490
7491The stack space allowed is not necessarily allocated. If you specify a
1a059451 7492large value for @code{YYMAXDEPTH}, the parser normally allocates a small
bfa74976
RS
7493stack at first, and then makes it bigger by stages as needed. This
7494increasing allocation happens automatically and silently. Therefore,
7495you do not need to make @code{YYMAXDEPTH} painfully small merely to save
7496space for ordinary inputs that do not need much stack.
7497
d7e14fc0
PE
7498However, do not allow @code{YYMAXDEPTH} to be a value so large that
7499arithmetic overflow could occur when calculating the size of the stack
7500space. Also, do not allow @code{YYMAXDEPTH} to be less than
7501@code{YYINITDEPTH}.
7502
bfa74976
RS
7503@cindex default stack limit
7504The default value of @code{YYMAXDEPTH}, if you do not define it, is
750510000.
7506
7507@vindex YYINITDEPTH
7508You can control how much stack is allocated initially by defining the
eb45ef3b
JD
7509macro @code{YYINITDEPTH} to a positive integer. For the deterministic
7510parser in C, this value must be a compile-time constant
d7e14fc0
PE
7511unless you are assuming C99 or some other target language or compiler
7512that allows variable-length arrays. The default is 200.
7513
1a059451 7514Do not allow @code{YYINITDEPTH} to be greater than @code{YYMAXDEPTH}.
bfa74976 7515
20be2f92
PH
7516You can generate a deterministic parser containing C++ user code from
7517the default (C) skeleton, as well as from the C++ skeleton
7518(@pxref{C++ Parsers}). However, if you do use the default skeleton
7519and want to allow the parsing stack to grow,
7520be careful not to use semantic types or location types that require
7521non-trivial copy constructors.
7522The C skeleton bypasses these constructors when copying data to
7523new, larger stacks.
d1a1114f 7524
342b8b6e 7525@node Error Recovery
bfa74976
RS
7526@chapter Error Recovery
7527@cindex error recovery
7528@cindex recovery from errors
7529
6e649e65 7530It is not usually acceptable to have a program terminate on a syntax
bfa74976
RS
7531error. For example, a compiler should recover sufficiently to parse the
7532rest of the input file and check it for errors; a calculator should accept
7533another expression.
7534
7535In a simple interactive command parser where each input is one line, it may
7536be sufficient to allow @code{yyparse} to return 1 on error and have the
7537caller ignore the rest of the input line when that happens (and then call
7538@code{yyparse} again). But this is inadequate for a compiler, because it
7539forgets all the syntactic context leading up to the error. A syntax error
7540deep within a function in the compiler input should not cause the compiler
7541to treat the following line like the beginning of a source file.
7542
7543@findex error
7544You can define how to recover from a syntax error by writing rules to
7545recognize the special token @code{error}. This is a terminal symbol that
7546is always defined (you need not declare it) and reserved for error
7547handling. The Bison parser generates an @code{error} token whenever a
7548syntax error happens; if you have provided a rule to recognize this token
13863333 7549in the current context, the parse can continue.
bfa74976
RS
7550
7551For example:
7552
7553@example
7554stmnts: /* empty string */
7555 | stmnts '\n'
7556 | stmnts exp '\n'
7557 | stmnts error '\n'
7558@end example
7559
7560The fourth rule in this example says that an error followed by a newline
7561makes a valid addition to any @code{stmnts}.
7562
7563What happens if a syntax error occurs in the middle of an @code{exp}? The
7564error recovery rule, interpreted strictly, applies to the precise sequence
7565of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
7566the middle of an @code{exp}, there will probably be some additional tokens
7567and subexpressions on the stack after the last @code{stmnts}, and there
7568will be tokens to read before the next newline. So the rule is not
7569applicable in the ordinary way.
7570
7571But Bison can force the situation to fit the rule, by discarding part of
72f889cc
AD
7572the semantic context and part of the input. First it discards states
7573and objects from the stack until it gets back to a state in which the
bfa74976 7574@code{error} token is acceptable. (This means that the subexpressions
72f889cc
AD
7575already parsed are discarded, back to the last complete @code{stmnts}.)
7576At this point the @code{error} token can be shifted. Then, if the old
742e4900 7577lookahead token is not acceptable to be shifted next, the parser reads
bfa74976 7578tokens and discards them until it finds a token which is acceptable. In
72f889cc
AD
7579this example, Bison reads and discards input until the next newline so
7580that the fourth rule can apply. Note that discarded symbols are
7581possible sources of memory leaks, see @ref{Destructor Decl, , Freeing
7582Discarded Symbols}, for a means to reclaim this memory.
bfa74976
RS
7583
7584The choice of error rules in the grammar is a choice of strategies for
7585error recovery. A simple and useful strategy is simply to skip the rest of
7586the current input line or current statement if an error is detected:
7587
7588@example
72d2299c 7589stmnt: error ';' /* On error, skip until ';' is read. */
bfa74976
RS
7590@end example
7591
7592It is also useful to recover to the matching close-delimiter of an
7593opening-delimiter that has already been parsed. Otherwise the
7594close-delimiter will probably appear to be unmatched, and generate another,
7595spurious error message:
7596
7597@example
7598primary: '(' expr ')'
7599 | '(' error ')'
7600 @dots{}
7601 ;
7602@end example
7603
7604Error recovery strategies are necessarily guesses. When they guess wrong,
7605one syntax error often leads to another. In the above example, the error
7606recovery rule guesses that an error is due to bad input within one
7607@code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
7608middle of a valid @code{stmnt}. After the error recovery rule recovers
7609from the first error, another syntax error will be found straightaway,
7610since the text following the spurious semicolon is also an invalid
7611@code{stmnt}.
7612
7613To prevent an outpouring of error messages, the parser will output no error
7614message for another syntax error that happens shortly after the first; only
7615after three consecutive input tokens have been successfully shifted will
7616error messages resume.
7617
7618Note that rules which accept the @code{error} token may have actions, just
7619as any other rules can.
7620
7621@findex yyerrok
7622You can make error messages resume immediately by using the macro
7623@code{yyerrok} in an action. If you do this in the error rule's action, no
7624error messages will be suppressed. This macro requires no arguments;
7625@samp{yyerrok;} is a valid C statement.
7626
7627@findex yyclearin
742e4900 7628The previous lookahead token is reanalyzed immediately after an error. If
bfa74976
RS
7629this is unacceptable, then the macro @code{yyclearin} may be used to clear
7630this token. Write the statement @samp{yyclearin;} in the error rule's
7631action.
32c29292 7632@xref{Action Features, ,Special Features for Use in Actions}.
bfa74976 7633
6e649e65 7634For example, suppose that on a syntax error, an error handling routine is
bfa74976
RS
7635called that advances the input stream to some point where parsing should
7636once again commence. The next symbol returned by the lexical scanner is
742e4900 7637probably correct. The previous lookahead token ought to be discarded
bfa74976
RS
7638with @samp{yyclearin;}.
7639
7640@vindex YYRECOVERING
02103984
PE
7641The expression @code{YYRECOVERING ()} yields 1 when the parser
7642is recovering from a syntax error, and 0 otherwise.
7643Syntax error diagnostics are suppressed while recovering from a syntax
7644error.
bfa74976 7645
342b8b6e 7646@node Context Dependency
bfa74976
RS
7647@chapter Handling Context Dependencies
7648
7649The Bison paradigm is to parse tokens first, then group them into larger
7650syntactic units. In many languages, the meaning of a token is affected by
7651its context. Although this violates the Bison paradigm, certain techniques
7652(known as @dfn{kludges}) may enable you to write Bison parsers for such
7653languages.
7654
7655@menu
7656* Semantic Tokens:: Token parsing can depend on the semantic context.
7657* Lexical Tie-ins:: Token parsing can depend on the syntactic context.
7658* Tie-in Recovery:: Lexical tie-ins have implications for how
7659 error recovery rules must be written.
7660@end menu
7661
7662(Actually, ``kludge'' means any technique that gets its job done but is
7663neither clean nor robust.)
7664
342b8b6e 7665@node Semantic Tokens
bfa74976
RS
7666@section Semantic Info in Token Types
7667
7668The C language has a context dependency: the way an identifier is used
7669depends on what its current meaning is. For example, consider this:
7670
7671@example
7672foo (x);
7673@end example
7674
7675This looks like a function call statement, but if @code{foo} is a typedef
7676name, then this is actually a declaration of @code{x}. How can a Bison
7677parser for C decide how to parse this input?
7678
8a4281b9 7679The method used in GNU C is to have two different token types,
bfa74976
RS
7680@code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
7681identifier, it looks up the current declaration of the identifier in order
7682to decide which token type to return: @code{TYPENAME} if the identifier is
7683declared as a typedef, @code{IDENTIFIER} otherwise.
7684
7685The grammar rules can then express the context dependency by the choice of
7686token type to recognize. @code{IDENTIFIER} is accepted as an expression,
7687but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
7688@code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
7689is @emph{not} significant, such as in declarations that can shadow a
7690typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
7691accepted---there is one rule for each of the two token types.
7692
7693This technique is simple to use if the decision of which kinds of
7694identifiers to allow is made at a place close to where the identifier is
7695parsed. But in C this is not always so: C allows a declaration to
7696redeclare a typedef name provided an explicit type has been specified
7697earlier:
7698
7699@example
3a4f411f
PE
7700typedef int foo, bar;
7701int baz (void)
7702@{
7703 static bar (bar); /* @r{redeclare @code{bar} as static variable} */
7704 extern foo foo (foo); /* @r{redeclare @code{foo} as function} */
7705 return foo (bar);
7706@}
bfa74976
RS
7707@end example
7708
7709Unfortunately, the name being declared is separated from the declaration
7710construct itself by a complicated syntactic structure---the ``declarator''.
7711
9ecbd125 7712As a result, part of the Bison parser for C needs to be duplicated, with
14ded682
AD
7713all the nonterminal names changed: once for parsing a declaration in
7714which a typedef name can be redefined, and once for parsing a
7715declaration in which that can't be done. Here is a part of the
7716duplication, with actions omitted for brevity:
bfa74976
RS
7717
7718@example
7719initdcl:
7720 declarator maybeasm '='
7721 init
7722 | declarator maybeasm
7723 ;
7724
7725notype_initdcl:
7726 notype_declarator maybeasm '='
7727 init
7728 | notype_declarator maybeasm
7729 ;
7730@end example
7731
7732@noindent
7733Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
7734cannot. The distinction between @code{declarator} and
7735@code{notype_declarator} is the same sort of thing.
7736
7737There is some similarity between this technique and a lexical tie-in
7738(described next), in that information which alters the lexical analysis is
7739changed during parsing by other parts of the program. The difference is
7740here the information is global, and is used for other purposes in the
7741program. A true lexical tie-in has a special-purpose flag controlled by
7742the syntactic context.
7743
342b8b6e 7744@node Lexical Tie-ins
bfa74976
RS
7745@section Lexical Tie-ins
7746@cindex lexical tie-in
7747
7748One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
7749which is set by Bison actions, whose purpose is to alter the way tokens are
7750parsed.
7751
7752For example, suppose we have a language vaguely like C, but with a special
7753construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
7754an expression in parentheses in which all integers are hexadecimal. In
7755particular, the token @samp{a1b} must be treated as an integer rather than
7756as an identifier if it appears in that context. Here is how you can do it:
7757
7758@example
7759@group
7760%@{
38a92d50
PE
7761 int hexflag;
7762 int yylex (void);
7763 void yyerror (char const *);
bfa74976
RS
7764%@}
7765%%
7766@dots{}
7767@end group
7768@group
7769expr: IDENTIFIER
7770 | constant
7771 | HEX '('
7772 @{ hexflag = 1; @}
7773 expr ')'
7774 @{ hexflag = 0;
7775 $$ = $4; @}
7776 | expr '+' expr
7777 @{ $$ = make_sum ($1, $3); @}
7778 @dots{}
7779 ;
7780@end group
7781
7782@group
7783constant:
7784 INTEGER
7785 | STRING
7786 ;
7787@end group
7788@end example
7789
7790@noindent
7791Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
7792it is nonzero, all integers are parsed in hexadecimal, and tokens starting
7793with letters are parsed as integers if possible.
7794
ff7571c0
JD
7795The declaration of @code{hexflag} shown in the prologue of the grammar
7796file is needed to make it accessible to the actions (@pxref{Prologue,
7797,The Prologue}). You must also write the code in @code{yylex} to obey
7798the flag.
bfa74976 7799
342b8b6e 7800@node Tie-in Recovery
bfa74976
RS
7801@section Lexical Tie-ins and Error Recovery
7802
7803Lexical tie-ins make strict demands on any error recovery rules you have.
7804@xref{Error Recovery}.
7805
7806The reason for this is that the purpose of an error recovery rule is to
7807abort the parsing of one construct and resume in some larger construct.
7808For example, in C-like languages, a typical error recovery rule is to skip
7809tokens until the next semicolon, and then start a new statement, like this:
7810
7811@example
7812stmt: expr ';'
7813 | IF '(' expr ')' stmt @{ @dots{} @}
7814 @dots{}
7815 error ';'
7816 @{ hexflag = 0; @}
7817 ;
7818@end example
7819
7820If there is a syntax error in the middle of a @samp{hex (@var{expr})}
7821construct, this error rule will apply, and then the action for the
7822completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
7823remain set for the entire rest of the input, or until the next @code{hex}
7824keyword, causing identifiers to be misinterpreted as integers.
7825
7826To avoid this problem the error recovery rule itself clears @code{hexflag}.
7827
7828There may also be an error recovery rule that works within expressions.
7829For example, there could be a rule which applies within parentheses
7830and skips to the close-parenthesis:
7831
7832@example
7833@group
7834expr: @dots{}
7835 | '(' expr ')'
7836 @{ $$ = $2; @}
7837 | '(' error ')'
7838 @dots{}
7839@end group
7840@end example
7841
7842If this rule acts within the @code{hex} construct, it is not going to abort
7843that construct (since it applies to an inner level of parentheses within
7844the construct). Therefore, it should not clear the flag: the rest of
7845the @code{hex} construct should be parsed with the flag still in effect.
7846
7847What if there is an error recovery rule which might abort out of the
7848@code{hex} construct or might not, depending on circumstances? There is no
7849way you can write the action to determine whether a @code{hex} construct is
7850being aborted or not. So if you are using a lexical tie-in, you had better
7851make sure your error recovery rules are not of this kind. Each rule must
7852be such that you can be sure that it always will, or always won't, have to
7853clear the flag.
7854
ec3bc396
AD
7855@c ================================================== Debugging Your Parser
7856
342b8b6e 7857@node Debugging
bfa74976 7858@chapter Debugging Your Parser
ec3bc396
AD
7859
7860Developing a parser can be a challenge, especially if you don't
7861understand the algorithm (@pxref{Algorithm, ,The Bison Parser
7862Algorithm}). Even so, sometimes a detailed description of the automaton
7863can help (@pxref{Understanding, , Understanding Your Parser}), or
7864tracing the execution of the parser can give some insight on why it
7865behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
7866
7867@menu
7868* Understanding:: Understanding the structure of your parser.
7869* Tracing:: Tracing the execution of your parser.
7870@end menu
7871
7872@node Understanding
7873@section Understanding Your Parser
7874
7875As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
7876Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
7877frequent than one would hope), looking at this automaton is required to
7878tune or simply fix a parser. Bison provides two different
35fe0834 7879representation of it, either textually or graphically (as a DOT file).
ec3bc396
AD
7880
7881The textual file is generated when the options @option{--report} or
7882@option{--verbose} are specified, see @xref{Invocation, , Invoking
7883Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
ff7571c0
JD
7884the parser implementation file name, and adding @samp{.output}
7885instead. Therefore, if the grammar file is @file{foo.y}, then the
7886parser implementation file is called @file{foo.tab.c} by default. As
7887a consequence, the verbose output file is called @file{foo.output}.
ec3bc396
AD
7888
7889The following grammar file, @file{calc.y}, will be used in the sequel:
7890
7891@example
7892%token NUM STR
7893%left '+' '-'
7894%left '*'
7895%%
7896exp: exp '+' exp
7897 | exp '-' exp
7898 | exp '*' exp
7899 | exp '/' exp
7900 | NUM
7901 ;
7902useless: STR;
7903%%
7904@end example
7905
88bce5a2
AD
7906@command{bison} reports:
7907
7908@example
8f0d265e
JD
7909calc.y: warning: 1 nonterminal useless in grammar
7910calc.y: warning: 1 rule useless in grammar
cff03fb2
JD
7911calc.y:11.1-7: warning: nonterminal useless in grammar: useless
7912calc.y:11.10-12: warning: rule useless in grammar: useless: STR
5a99098d 7913calc.y: conflicts: 7 shift/reduce
88bce5a2
AD
7914@end example
7915
7916When given @option{--report=state}, in addition to @file{calc.tab.c}, it
7917creates a file @file{calc.output} with contents detailed below. The
7918order of the output and the exact presentation might vary, but the
7919interpretation is the same.
ec3bc396
AD
7920
7921The first section includes details on conflicts that were solved thanks
7922to precedence and/or associativity:
7923
7924@example
7925Conflict in state 8 between rule 2 and token '+' resolved as reduce.
7926Conflict in state 8 between rule 2 and token '-' resolved as reduce.
7927Conflict in state 8 between rule 2 and token '*' resolved as shift.
7928@exdent @dots{}
7929@end example
7930
7931@noindent
7932The next section lists states that still have conflicts.
7933
7934@example
5a99098d
PE
7935State 8 conflicts: 1 shift/reduce
7936State 9 conflicts: 1 shift/reduce
7937State 10 conflicts: 1 shift/reduce
7938State 11 conflicts: 4 shift/reduce
ec3bc396
AD
7939@end example
7940
7941@noindent
7942@cindex token, useless
7943@cindex useless token
7944@cindex nonterminal, useless
7945@cindex useless nonterminal
7946@cindex rule, useless
7947@cindex useless rule
7948The next section reports useless tokens, nonterminal and rules. Useless
7949nonterminals and rules are removed in order to produce a smaller parser,
7950but useless tokens are preserved, since they might be used by the
d80fb37a 7951scanner (note the difference between ``useless'' and ``unused''
ec3bc396
AD
7952below):
7953
7954@example
d80fb37a 7955Nonterminals useless in grammar:
ec3bc396
AD
7956 useless
7957
d80fb37a 7958Terminals unused in grammar:
ec3bc396
AD
7959 STR
7960
cff03fb2 7961Rules useless in grammar:
ec3bc396
AD
7962#6 useless: STR;
7963@end example
7964
7965@noindent
7966The next section reproduces the exact grammar that Bison used:
7967
7968@example
7969Grammar
7970
7971 Number, Line, Rule
88bce5a2 7972 0 5 $accept -> exp $end
ec3bc396
AD
7973 1 5 exp -> exp '+' exp
7974 2 6 exp -> exp '-' exp
7975 3 7 exp -> exp '*' exp
7976 4 8 exp -> exp '/' exp
7977 5 9 exp -> NUM
7978@end example
7979
7980@noindent
7981and reports the uses of the symbols:
7982
7983@example
7984Terminals, with rules where they appear
7985
88bce5a2 7986$end (0) 0
ec3bc396
AD
7987'*' (42) 3
7988'+' (43) 1
7989'-' (45) 2
7990'/' (47) 4
7991error (256)
7992NUM (258) 5
7993
7994Nonterminals, with rules where they appear
7995
88bce5a2 7996$accept (8)
ec3bc396
AD
7997 on left: 0
7998exp (9)
7999 on left: 1 2 3 4 5, on right: 0 1 2 3 4
8000@end example
8001
8002@noindent
8003@cindex item
8004@cindex pointed rule
8005@cindex rule, pointed
8006Bison then proceeds onto the automaton itself, describing each state
8007with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
8008item is a production rule together with a point (marked by @samp{.})
8009that the input cursor.
8010
8011@example
8012state 0
8013
88bce5a2 8014 $accept -> . exp $ (rule 0)
ec3bc396 8015
2a8d363a 8016 NUM shift, and go to state 1
ec3bc396 8017
2a8d363a 8018 exp go to state 2
ec3bc396
AD
8019@end example
8020
8021This reads as follows: ``state 0 corresponds to being at the very
8022beginning of the parsing, in the initial rule, right before the start
8023symbol (here, @code{exp}). When the parser returns to this state right
8024after having reduced a rule that produced an @code{exp}, the control
8025flow jumps to state 2. If there is no such transition on a nonterminal
742e4900 8026symbol, and the lookahead is a @code{NUM}, then this token is shifted on
ec3bc396 8027the parse stack, and the control flow jumps to state 1. Any other
742e4900 8028lookahead triggers a syntax error.''
ec3bc396
AD
8029
8030@cindex core, item set
8031@cindex item set core
8032@cindex kernel, item set
8033@cindex item set core
8034Even though the only active rule in state 0 seems to be rule 0, the
742e4900 8035report lists @code{NUM} as a lookahead token because @code{NUM} can be
ec3bc396
AD
8036at the beginning of any rule deriving an @code{exp}. By default Bison
8037reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
8038you want to see more detail you can invoke @command{bison} with
8039@option{--report=itemset} to list all the items, include those that can
8040be derived:
8041
8042@example
8043state 0
8044
88bce5a2 8045 $accept -> . exp $ (rule 0)
ec3bc396
AD
8046 exp -> . exp '+' exp (rule 1)
8047 exp -> . exp '-' exp (rule 2)
8048 exp -> . exp '*' exp (rule 3)
8049 exp -> . exp '/' exp (rule 4)
8050 exp -> . NUM (rule 5)
8051
8052 NUM shift, and go to state 1
8053
8054 exp go to state 2
8055@end example
8056
8057@noindent
8058In the state 1...
8059
8060@example
8061state 1
8062
8063 exp -> NUM . (rule 5)
8064
2a8d363a 8065 $default reduce using rule 5 (exp)
ec3bc396
AD
8066@end example
8067
8068@noindent
742e4900 8069the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead token
ec3bc396
AD
8070(@samp{$default}), the parser will reduce it. If it was coming from
8071state 0, then, after this reduction it will return to state 0, and will
8072jump to state 2 (@samp{exp: go to state 2}).
8073
8074@example
8075state 2
8076
88bce5a2 8077 $accept -> exp . $ (rule 0)
ec3bc396
AD
8078 exp -> exp . '+' exp (rule 1)
8079 exp -> exp . '-' exp (rule 2)
8080 exp -> exp . '*' exp (rule 3)
8081 exp -> exp . '/' exp (rule 4)
8082
2a8d363a
AD
8083 $ shift, and go to state 3
8084 '+' shift, and go to state 4
8085 '-' shift, and go to state 5
8086 '*' shift, and go to state 6
8087 '/' shift, and go to state 7
ec3bc396
AD
8088@end example
8089
8090@noindent
8091In state 2, the automaton can only shift a symbol. For instance,
742e4900 8092because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
ec3bc396
AD
8093@samp{+}, it will be shifted on the parse stack, and the automaton
8094control will jump to state 4, corresponding to the item @samp{exp -> exp
8095'+' . exp}. Since there is no default action, any other token than
6e649e65 8096those listed above will trigger a syntax error.
ec3bc396 8097
eb45ef3b 8098@cindex accepting state
ec3bc396
AD
8099The state 3 is named the @dfn{final state}, or the @dfn{accepting
8100state}:
8101
8102@example
8103state 3
8104
88bce5a2 8105 $accept -> exp $ . (rule 0)
ec3bc396 8106
2a8d363a 8107 $default accept
ec3bc396
AD
8108@end example
8109
8110@noindent
8111the initial rule is completed (the start symbol and the end
8112of input were read), the parsing exits successfully.
8113
8114The interpretation of states 4 to 7 is straightforward, and is left to
8115the reader.
8116
8117@example
8118state 4
8119
8120 exp -> exp '+' . exp (rule 1)
8121
2a8d363a 8122 NUM shift, and go to state 1
ec3bc396 8123
2a8d363a 8124 exp go to state 8
ec3bc396
AD
8125
8126state 5
8127
8128 exp -> exp '-' . exp (rule 2)
8129
2a8d363a 8130 NUM shift, and go to state 1
ec3bc396 8131
2a8d363a 8132 exp go to state 9
ec3bc396
AD
8133
8134state 6
8135
8136 exp -> exp '*' . exp (rule 3)
8137
2a8d363a 8138 NUM shift, and go to state 1
ec3bc396 8139
2a8d363a 8140 exp go to state 10
ec3bc396
AD
8141
8142state 7
8143
8144 exp -> exp '/' . exp (rule 4)
8145
2a8d363a 8146 NUM shift, and go to state 1
ec3bc396 8147
2a8d363a 8148 exp go to state 11
ec3bc396
AD
8149@end example
8150
5a99098d
PE
8151As was announced in beginning of the report, @samp{State 8 conflicts:
81521 shift/reduce}:
ec3bc396
AD
8153
8154@example
8155state 8
8156
8157 exp -> exp . '+' exp (rule 1)
8158 exp -> exp '+' exp . (rule 1)
8159 exp -> exp . '-' exp (rule 2)
8160 exp -> exp . '*' exp (rule 3)
8161 exp -> exp . '/' exp (rule 4)
8162
2a8d363a
AD
8163 '*' shift, and go to state 6
8164 '/' shift, and go to state 7
ec3bc396 8165
2a8d363a
AD
8166 '/' [reduce using rule 1 (exp)]
8167 $default reduce using rule 1 (exp)
ec3bc396
AD
8168@end example
8169
742e4900 8170Indeed, there are two actions associated to the lookahead @samp{/}:
ec3bc396
AD
8171either shifting (and going to state 7), or reducing rule 1. The
8172conflict means that either the grammar is ambiguous, or the parser lacks
8173information to make the right decision. Indeed the grammar is
8174ambiguous, as, since we did not specify the precedence of @samp{/}, the
8175sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
8176NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
8177NUM}, which corresponds to reducing rule 1.
8178
eb45ef3b 8179Because in deterministic parsing a single decision can be made, Bison
ec3bc396
AD
8180arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
8181Shift/Reduce Conflicts}. Discarded actions are reported in between
8182square brackets.
8183
8184Note that all the previous states had a single possible action: either
8185shifting the next token and going to the corresponding state, or
8186reducing a single rule. In the other cases, i.e., when shifting
8187@emph{and} reducing is possible or when @emph{several} reductions are
742e4900
JD
8188possible, the lookahead is required to select the action. State 8 is
8189one such state: if the lookahead is @samp{*} or @samp{/} then the action
ec3bc396
AD
8190is shifting, otherwise the action is reducing rule 1. In other words,
8191the first two items, corresponding to rule 1, are not eligible when the
742e4900 8192lookahead token is @samp{*}, since we specified that @samp{*} has higher
8dd162d3 8193precedence than @samp{+}. More generally, some items are eligible only
742e4900
JD
8194with some set of possible lookahead tokens. When run with
8195@option{--report=lookahead}, Bison specifies these lookahead tokens:
ec3bc396
AD
8196
8197@example
8198state 8
8199
88c78747 8200 exp -> exp . '+' exp (rule 1)
ec3bc396
AD
8201 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
8202 exp -> exp . '-' exp (rule 2)
8203 exp -> exp . '*' exp (rule 3)
8204 exp -> exp . '/' exp (rule 4)
8205
8206 '*' shift, and go to state 6
8207 '/' shift, and go to state 7
8208
8209 '/' [reduce using rule 1 (exp)]
8210 $default reduce using rule 1 (exp)
8211@end example
8212
8213The remaining states are similar:
8214
8215@example
8216state 9
8217
8218 exp -> exp . '+' exp (rule 1)
8219 exp -> exp . '-' exp (rule 2)
8220 exp -> exp '-' exp . (rule 2)
8221 exp -> exp . '*' exp (rule 3)
8222 exp -> exp . '/' exp (rule 4)
8223
2a8d363a
AD
8224 '*' shift, and go to state 6
8225 '/' shift, and go to state 7
ec3bc396 8226
2a8d363a
AD
8227 '/' [reduce using rule 2 (exp)]
8228 $default reduce using rule 2 (exp)
ec3bc396
AD
8229
8230state 10
8231
8232 exp -> exp . '+' exp (rule 1)
8233 exp -> exp . '-' exp (rule 2)
8234 exp -> exp . '*' exp (rule 3)
8235 exp -> exp '*' exp . (rule 3)
8236 exp -> exp . '/' exp (rule 4)
8237
2a8d363a 8238 '/' shift, and go to state 7
ec3bc396 8239
2a8d363a
AD
8240 '/' [reduce using rule 3 (exp)]
8241 $default reduce using rule 3 (exp)
ec3bc396
AD
8242
8243state 11
8244
8245 exp -> exp . '+' exp (rule 1)
8246 exp -> exp . '-' exp (rule 2)
8247 exp -> exp . '*' exp (rule 3)
8248 exp -> exp . '/' exp (rule 4)
8249 exp -> exp '/' exp . (rule 4)
8250
2a8d363a
AD
8251 '+' shift, and go to state 4
8252 '-' shift, and go to state 5
8253 '*' shift, and go to state 6
8254 '/' shift, and go to state 7
ec3bc396 8255
2a8d363a
AD
8256 '+' [reduce using rule 4 (exp)]
8257 '-' [reduce using rule 4 (exp)]
8258 '*' [reduce using rule 4 (exp)]
8259 '/' [reduce using rule 4 (exp)]
8260 $default reduce using rule 4 (exp)
ec3bc396
AD
8261@end example
8262
8263@noindent
fa7e68c3
PE
8264Observe that state 11 contains conflicts not only due to the lack of
8265precedence of @samp{/} with respect to @samp{+}, @samp{-}, and
8266@samp{*}, but also because the
ec3bc396
AD
8267associativity of @samp{/} is not specified.
8268
8269
8270@node Tracing
8271@section Tracing Your Parser
bfa74976
RS
8272@findex yydebug
8273@cindex debugging
8274@cindex tracing the parser
8275
8276If a Bison grammar compiles properly but doesn't do what you want when it
8277runs, the @code{yydebug} parser-trace feature can help you figure out why.
8278
3ded9a63
AD
8279There are several means to enable compilation of trace facilities:
8280
8281@table @asis
8282@item the macro @code{YYDEBUG}
8283@findex YYDEBUG
8284Define the macro @code{YYDEBUG} to a nonzero value when you compile the
8a4281b9 8285parser. This is compliant with POSIX Yacc. You could use
3ded9a63
AD
8286@samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
8287YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
8288Prologue}).
8289
8290@item the option @option{-t}, @option{--debug}
8291Use the @samp{-t} option when you run Bison (@pxref{Invocation,
8a4281b9 8292,Invoking Bison}). This is POSIX compliant too.
3ded9a63
AD
8293
8294@item the directive @samp{%debug}
8295@findex %debug
fa819509
AD
8296Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison Declaration
8297Summary}). This Bison extension is maintained for backward
8298compatibility with previous versions of Bison.
8299
8300@item the variable @samp{parse.trace}
8301@findex %define parse.trace
8302Add the @samp{%define parse.trace} directive (@pxref{Decl Summary,
8303,Bison Declaration Summary}), or pass the @option{-Dparse.trace} option
8304(@pxref{Bison Options}). This is a Bison extension, which is especially
8305useful for languages that don't use a preprocessor. Unless
8a4281b9 8306POSIX and Yacc portability matter to you, this is the
fa819509 8307preferred solution.
3ded9a63
AD
8308@end table
8309
fa819509 8310We suggest that you always enable the trace option so that debugging is
3ded9a63 8311always possible.
bfa74976 8312
02a81e05 8313The trace facility outputs messages with macro calls of the form
e2742e46 8314@code{YYFPRINTF (stderr, @var{format}, @var{args})} where
f57a7536 8315@var{format} and @var{args} are the usual @code{printf} format and variadic
4947ebdb
PE
8316arguments. If you define @code{YYDEBUG} to a nonzero value but do not
8317define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
9c437126 8318and @code{YYFPRINTF} is defined to @code{fprintf}.
bfa74976
RS
8319
8320Once you have compiled the program with trace facilities, the way to
8321request a trace is to store a nonzero value in the variable @code{yydebug}.
8322You can do this by making the C code do it (in @code{main}, perhaps), or
8323you can alter the value with a C debugger.
8324
8325Each step taken by the parser when @code{yydebug} is nonzero produces a
8326line or two of trace information, written on @code{stderr}. The trace
8327messages tell you these things:
8328
8329@itemize @bullet
8330@item
8331Each time the parser calls @code{yylex}, what kind of token was read.
8332
8333@item
8334Each time a token is shifted, the depth and complete contents of the
8335state stack (@pxref{Parser States}).
8336
8337@item
8338Each time a rule is reduced, which rule it is, and the complete contents
8339of the state stack afterward.
8340@end itemize
8341
8342To make sense of this information, it helps to refer to the listing file
704a47c4
AD
8343produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
8344Bison}). This file shows the meaning of each state in terms of
8345positions in various rules, and also what each state will do with each
8346possible input token. As you read the successive trace messages, you
8347can see that the parser is functioning according to its specification in
8348the listing file. Eventually you will arrive at the place where
8349something undesirable happens, and you will see which parts of the
8350grammar are to blame.
bfa74976 8351
ff7571c0
JD
8352The parser implementation file is a C program and you can use C
8353debuggers on it, but it's not easy to interpret what it is doing. The
8354parser function is a finite-state machine interpreter, and aside from
8355the actions it executes the same code over and over. Only the values
8356of variables show where in the grammar it is working.
bfa74976
RS
8357
8358@findex YYPRINT
8359The debugging information normally gives the token type of each token
8360read, but not its semantic value. You can optionally define a macro
8361named @code{YYPRINT} to provide a way to print the value. If you define
8362@code{YYPRINT}, it should take three arguments. The parser will pass a
8363standard I/O stream, the numeric code for the token type, and the token
8364value (from @code{yylval}).
8365
8366Here is an example of @code{YYPRINT} suitable for the multi-function
f5f419de 8367calculator (@pxref{Mfcalc Declarations, ,Declarations for @code{mfcalc}}):
bfa74976
RS
8368
8369@smallexample
38a92d50
PE
8370%@{
8371 static void print_token_value (FILE *, int, YYSTYPE);
8372 #define YYPRINT(file, type, value) print_token_value (file, type, value)
8373%@}
8374
8375@dots{} %% @dots{} %% @dots{}
bfa74976
RS
8376
8377static void
831d3c99 8378print_token_value (FILE *file, int type, YYSTYPE value)
bfa74976
RS
8379@{
8380 if (type == VAR)
d3c4e709 8381 fprintf (file, "%s", value.tptr->name);
bfa74976 8382 else if (type == NUM)
d3c4e709 8383 fprintf (file, "%d", value.val);
bfa74976
RS
8384@}
8385@end smallexample
8386
ec3bc396
AD
8387@c ================================================= Invoking Bison
8388
342b8b6e 8389@node Invocation
bfa74976
RS
8390@chapter Invoking Bison
8391@cindex invoking Bison
8392@cindex Bison invocation
8393@cindex options for invoking Bison
8394
8395The usual way to invoke Bison is as follows:
8396
8397@example
8398bison @var{infile}
8399@end example
8400
8401Here @var{infile} is the grammar file name, which usually ends in
ff7571c0
JD
8402@samp{.y}. The parser implementation file's name is made by replacing
8403the @samp{.y} with @samp{.tab.c} and removing any leading directory.
8404Thus, the @samp{bison foo.y} file name yields @file{foo.tab.c}, and
8405the @samp{bison hack/foo.y} file name yields @file{foo.tab.c}. It's
8406also possible, in case you are writing C++ code instead of C in your
8407grammar file, to name it @file{foo.ypp} or @file{foo.y++}. Then, the
8408output files will take an extension like the given one as input
8409(respectively @file{foo.tab.cpp} and @file{foo.tab.c++}). This
8410feature takes effect with all options that manipulate file names like
234a3be3
AD
8411@samp{-o} or @samp{-d}.
8412
8413For example :
8414
8415@example
8416bison -d @var{infile.yxx}
8417@end example
84163231 8418@noindent
72d2299c 8419will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}, and
234a3be3
AD
8420
8421@example
b56471a6 8422bison -d -o @var{output.c++} @var{infile.y}
234a3be3 8423@end example
84163231 8424@noindent
234a3be3
AD
8425will produce @file{output.c++} and @file{outfile.h++}.
8426
8a4281b9 8427For compatibility with POSIX, the standard Bison
397ec073
PE
8428distribution also contains a shell script called @command{yacc} that
8429invokes Bison with the @option{-y} option.
8430
bfa74976 8431@menu
13863333 8432* Bison Options:: All the options described in detail,
c827f760 8433 in alphabetical order by short options.
bfa74976 8434* Option Cross Key:: Alphabetical list of long options.
93dd49ab 8435* Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
bfa74976
RS
8436@end menu
8437
342b8b6e 8438@node Bison Options
bfa74976
RS
8439@section Bison Options
8440
8441Bison supports both traditional single-letter options and mnemonic long
8442option names. Long option names are indicated with @samp{--} instead of
8443@samp{-}. Abbreviations for option names are allowed as long as they
8444are unique. When a long option takes an argument, like
8445@samp{--file-prefix}, connect the option name and the argument with
8446@samp{=}.
8447
8448Here is a list of options that can be used with Bison, alphabetized by
8449short option. It is followed by a cross key alphabetized by long
8450option.
8451
89cab50d
AD
8452@c Please, keep this ordered as in `bison --help'.
8453@noindent
8454Operations modes:
8455@table @option
8456@item -h
8457@itemx --help
8458Print a summary of the command-line options to Bison and exit.
bfa74976 8459
89cab50d
AD
8460@item -V
8461@itemx --version
8462Print the version number of Bison and exit.
bfa74976 8463
f7ab6a50
PE
8464@item --print-localedir
8465Print the name of the directory containing locale-dependent data.
8466
a0de5091
JD
8467@item --print-datadir
8468Print the name of the directory containing skeletons and XSLT.
8469
89cab50d
AD
8470@item -y
8471@itemx --yacc
ff7571c0
JD
8472Act more like the traditional Yacc command. This can cause different
8473diagnostics to be generated, and may change behavior in other minor
8474ways. Most importantly, imitate Yacc's output file name conventions,
8475so that the parser implementation file is called @file{y.tab.c}, and
8476the other outputs are called @file{y.output} and @file{y.tab.h}.
8477Also, if generating a deterministic parser in C, generate
8478@code{#define} statements in addition to an @code{enum} to associate
8479token numbers with token names. Thus, the following shell script can
8480substitute for Yacc, and the Bison distribution contains such a script
8481for compatibility with POSIX:
bfa74976 8482
89cab50d 8483@example
397ec073 8484#! /bin/sh
26e06a21 8485bison -y "$@@"
89cab50d 8486@end example
54662697
PE
8487
8488The @option{-y}/@option{--yacc} option is intended for use with
8489traditional Yacc grammars. If your grammar uses a Bison extension
8490like @samp{%glr-parser}, Bison might not be Yacc-compatible even if
8491this option is specified.
8492
1d5b3c08
JD
8493@item -W [@var{category}]
8494@itemx --warnings[=@var{category}]
118d4978
AD
8495Output warnings falling in @var{category}. @var{category} can be one
8496of:
8497@table @code
8498@item midrule-values
8e55b3aa
JD
8499Warn about mid-rule values that are set but not used within any of the actions
8500of the parent rule.
8501For example, warn about unused @code{$2} in:
118d4978
AD
8502
8503@example
8504exp: '1' @{ $$ = 1; @} '+' exp @{ $$ = $1 + $4; @};
8505@end example
8506
8e55b3aa
JD
8507Also warn about mid-rule values that are used but not set.
8508For example, warn about unset @code{$$} in the mid-rule action in:
118d4978
AD
8509
8510@example
8511 exp: '1' @{ $1 = 1; @} '+' exp @{ $$ = $2 + $4; @};
8512@end example
8513
8514These warnings are not enabled by default since they sometimes prove to
8515be false alarms in existing grammars employing the Yacc constructs
8e55b3aa 8516@code{$0} or @code{$-@var{n}} (where @var{n} is some positive integer).
118d4978
AD
8517
8518
8519@item yacc
8a4281b9 8520Incompatibilities with POSIX Yacc.
118d4978
AD
8521
8522@item all
8e55b3aa 8523All the warnings.
118d4978 8524@item none
8e55b3aa 8525Turn off all the warnings.
118d4978 8526@item error
8e55b3aa 8527Treat warnings as errors.
118d4978
AD
8528@end table
8529
8530A category can be turned off by prefixing its name with @samp{no-}. For
93d7dde9 8531instance, @option{-Wno-yacc} will hide the warnings about
8a4281b9 8532POSIX Yacc incompatibilities.
89cab50d
AD
8533@end table
8534
8535@noindent
8536Tuning the parser:
8537
8538@table @option
8539@item -t
8540@itemx --debug
ff7571c0
JD
8541In the parser implementation file, define the macro @code{YYDEBUG} to
85421 if it is not already defined, so that the debugging facilities are
8543compiled. @xref{Tracing, ,Tracing Your Parser}.
89cab50d 8544
58697c6d
AD
8545@item -D @var{name}[=@var{value}]
8546@itemx --define=@var{name}[=@var{value}]
17aed602 8547@itemx -F @var{name}[=@var{value}]
de5ab940
JD
8548@itemx --force-define=@var{name}[=@var{value}]
8549Each of these is equivalent to @samp{%define @var{name} "@var{value}"}
8550(@pxref{Decl Summary, ,%define}) except that Bison processes multiple
8551definitions for the same @var{name} as follows:
8552
8553@itemize
8554@item
0b6d43c5
JD
8555Bison quietly ignores all command-line definitions for @var{name} except
8556the last.
de5ab940 8557@item
0b6d43c5
JD
8558If that command-line definition is specified by a @code{-D} or
8559@code{--define}, Bison reports an error for any @code{%define}
8560definition for @var{name}.
de5ab940 8561@item
0b6d43c5
JD
8562If that command-line definition is specified by a @code{-F} or
8563@code{--force-define} instead, Bison quietly ignores all @code{%define}
8564definitions for @var{name}.
8565@item
8566Otherwise, Bison reports an error if there are multiple @code{%define}
8567definitions for @var{name}.
de5ab940
JD
8568@end itemize
8569
8570You should avoid using @code{-F} and @code{--force-define} in your
ff7571c0
JD
8571make files unless you are confident that it is safe to quietly ignore
8572any conflicting @code{%define} that may be added to the grammar file.
58697c6d 8573
0e021770
PE
8574@item -L @var{language}
8575@itemx --language=@var{language}
8576Specify the programming language for the generated parser, as if
8577@code{%language} was specified (@pxref{Decl Summary, , Bison Declaration
59da312b 8578Summary}). Currently supported languages include C, C++, and Java.
e6e704dc 8579@var{language} is case-insensitive.
0e021770 8580
ed4d67dc
JD
8581This option is experimental and its effect may be modified in future
8582releases.
8583
89cab50d 8584@item --locations
d8988b2f 8585Pretend that @code{%locations} was specified. @xref{Decl Summary}.
89cab50d
AD
8586
8587@item -p @var{prefix}
8588@itemx --name-prefix=@var{prefix}
02975b9a 8589Pretend that @code{%name-prefix "@var{prefix}"} was specified.
d8988b2f 8590@xref{Decl Summary}.
bfa74976
RS
8591
8592@item -l
8593@itemx --no-lines
ff7571c0
JD
8594Don't put any @code{#line} preprocessor commands in the parser
8595implementation file. Ordinarily Bison puts them in the parser
8596implementation file so that the C compiler and debuggers will
8597associate errors with your source file, the grammar file. This option
8598causes them to associate errors with the parser implementation file,
8599treating it as an independent source file in its own right.
bfa74976 8600
e6e704dc
JD
8601@item -S @var{file}
8602@itemx --skeleton=@var{file}
a7867f53 8603Specify the skeleton to use, similar to @code{%skeleton}
e6e704dc
JD
8604(@pxref{Decl Summary, , Bison Declaration Summary}).
8605
ed4d67dc
JD
8606@c You probably don't need this option unless you are developing Bison.
8607@c You should use @option{--language} if you want to specify the skeleton for a
8608@c different language, because it is clearer and because it will always
8609@c choose the correct skeleton for non-deterministic or push parsers.
e6e704dc 8610
a7867f53
JD
8611If @var{file} does not contain a @code{/}, @var{file} is the name of a skeleton
8612file in the Bison installation directory.
8613If it does, @var{file} is an absolute file name or a file name relative to the
8614current working directory.
8615This is similar to how most shells resolve commands.
8616
89cab50d
AD
8617@item -k
8618@itemx --token-table
d8988b2f 8619Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
89cab50d 8620@end table
bfa74976 8621
89cab50d
AD
8622@noindent
8623Adjust the output:
bfa74976 8624
89cab50d 8625@table @option
8e55b3aa 8626@item --defines[=@var{file}]
d8988b2f 8627Pretend that @code{%defines} was specified, i.e., write an extra output
6deb4447 8628file containing macro definitions for the token type names defined in
4bfd5e4e 8629the grammar, as well as a few other declarations. @xref{Decl Summary}.
931c7513 8630
8e55b3aa
JD
8631@item -d
8632This is the same as @code{--defines} except @code{-d} does not accept a
8633@var{file} argument since POSIX Yacc requires that @code{-d} can be bundled
8634with other short options.
342b8b6e 8635
89cab50d
AD
8636@item -b @var{file-prefix}
8637@itemx --file-prefix=@var{prefix}
9c437126 8638Pretend that @code{%file-prefix} was specified, i.e., specify prefix to use
72d2299c 8639for all Bison output file names. @xref{Decl Summary}.
bfa74976 8640
ec3bc396
AD
8641@item -r @var{things}
8642@itemx --report=@var{things}
8643Write an extra output file containing verbose description of the comma
8644separated list of @var{things} among:
8645
8646@table @code
8647@item state
8648Description of the grammar, conflicts (resolved and unresolved), and
eb45ef3b 8649parser's automaton.
ec3bc396 8650
742e4900 8651@item lookahead
ec3bc396 8652Implies @code{state} and augments the description of the automaton with
742e4900 8653each rule's lookahead set.
ec3bc396
AD
8654
8655@item itemset
8656Implies @code{state} and augments the description of the automaton with
8657the full set of items for each state, instead of its core only.
8658@end table
8659
1bb2bd75
JD
8660@item --report-file=@var{file}
8661Specify the @var{file} for the verbose description.
8662
bfa74976
RS
8663@item -v
8664@itemx --verbose
9c437126 8665Pretend that @code{%verbose} was specified, i.e., write an extra output
6deb4447 8666file containing verbose descriptions of the grammar and
72d2299c 8667parser. @xref{Decl Summary}.
bfa74976 8668
fa4d969f
PE
8669@item -o @var{file}
8670@itemx --output=@var{file}
ff7571c0 8671Specify the @var{file} for the parser implementation file.
bfa74976 8672
fa4d969f 8673The other output files' names are constructed from @var{file} as
d8988b2f 8674described under the @samp{-v} and @samp{-d} options.
342b8b6e 8675
a7c09cba 8676@item -g [@var{file}]
8e55b3aa 8677@itemx --graph[=@var{file}]
eb45ef3b 8678Output a graphical representation of the parser's
35fe0834 8679automaton computed by Bison, in @uref{http://www.graphviz.org/, Graphviz}
8a4281b9 8680@uref{http://www.graphviz.org/doc/info/lang.html, DOT} format.
8e55b3aa
JD
8681@code{@var{file}} is optional.
8682If omitted and the grammar file is @file{foo.y}, the output file will be
8683@file{foo.dot}.
59da312b 8684
a7c09cba 8685@item -x [@var{file}]
8e55b3aa 8686@itemx --xml[=@var{file}]
eb45ef3b 8687Output an XML report of the parser's automaton computed by Bison.
8e55b3aa 8688@code{@var{file}} is optional.
59da312b
JD
8689If omitted and the grammar file is @file{foo.y}, the output file will be
8690@file{foo.xml}.
8691(The current XML schema is experimental and may evolve.
8692More user feedback will help to stabilize it.)
bfa74976
RS
8693@end table
8694
342b8b6e 8695@node Option Cross Key
bfa74976
RS
8696@section Option Cross Key
8697
8698Here is a list of options, alphabetized by long option, to help you find
de5ab940 8699the corresponding short option and directive.
bfa74976 8700
de5ab940 8701@multitable {@option{--force-define=@var{name}[=@var{value}]}} {@option{-F @var{name}[=@var{value}]}} {@code{%nondeterministic-parser}}
a7c09cba 8702@headitem Long Option @tab Short Option @tab Bison Directive
f4101aa6 8703@include cross-options.texi
aa08666d 8704@end multitable
bfa74976 8705
93dd49ab
PE
8706@node Yacc Library
8707@section Yacc Library
8708
8709The Yacc library contains default implementations of the
8710@code{yyerror} and @code{main} functions. These default
8a4281b9 8711implementations are normally not useful, but POSIX requires
93dd49ab
PE
8712them. To use the Yacc library, link your program with the
8713@option{-ly} option. Note that Bison's implementation of the Yacc
8a4281b9 8714library is distributed under the terms of the GNU General
93dd49ab
PE
8715Public License (@pxref{Copying}).
8716
8717If you use the Yacc library's @code{yyerror} function, you should
8718declare @code{yyerror} as follows:
8719
8720@example
8721int yyerror (char const *);
8722@end example
8723
8724Bison ignores the @code{int} value returned by this @code{yyerror}.
8725If you use the Yacc library's @code{main} function, your
8726@code{yyparse} function should have the following type signature:
8727
8728@example
8729int yyparse (void);
8730@end example
8731
12545799
AD
8732@c ================================================= C++ Bison
8733
8405b70c
PB
8734@node Other Languages
8735@chapter Parsers Written In Other Languages
12545799
AD
8736
8737@menu
8738* C++ Parsers:: The interface to generate C++ parser classes
8405b70c 8739* Java Parsers:: The interface to generate Java parser classes
12545799
AD
8740@end menu
8741
8742@node C++ Parsers
8743@section C++ Parsers
8744
8745@menu
8746* C++ Bison Interface:: Asking for C++ parser generation
8747* C++ Semantic Values:: %union vs. C++
8748* C++ Location Values:: The position and location classes
8749* C++ Parser Interface:: Instantiating and running the parser
8750* C++ Scanner Interface:: Exchanges between yylex and parse
8405b70c 8751* A Complete C++ Example:: Demonstrating their use
12545799
AD
8752@end menu
8753
8754@node C++ Bison Interface
8755@subsection C++ Bison Interface
ed4d67dc 8756@c - %skeleton "lalr1.cc"
12545799
AD
8757@c - Always pure
8758@c - initial action
8759
eb45ef3b 8760The C++ deterministic parser is selected using the skeleton directive,
86e5b440
AD
8761@samp{%skeleton "lalr1.cc"}, or the synonymous command-line option
8762@option{--skeleton=lalr1.cc}.
e6e704dc 8763@xref{Decl Summary}.
0e021770 8764
793fbca5
JD
8765When run, @command{bison} will create several entities in the @samp{yy}
8766namespace.
67501061
AD
8767@findex %define api.namespace
8768Use the @samp{%define api.namespace} directive to change the namespace
8769name, see
793fbca5
JD
8770@ref{Decl Summary}.
8771The various classes are generated in the following files:
aa08666d 8772
12545799
AD
8773@table @file
8774@item position.hh
8775@itemx location.hh
8776The definition of the classes @code{position} and @code{location},
3cdc21cf 8777used for location tracking when enabled. @xref{C++ Location Values}.
12545799
AD
8778
8779@item stack.hh
8780An auxiliary class @code{stack} used by the parser.
8781
fa4d969f
PE
8782@item @var{file}.hh
8783@itemx @var{file}.cc
ff7571c0 8784(Assuming the extension of the grammar file was @samp{.yy}.) The
cd8b5791
AD
8785declaration and implementation of the C++ parser class. The basename
8786and extension of these two files follow the same rules as with regular C
8787parsers (@pxref{Invocation}).
12545799 8788
cd8b5791
AD
8789The header is @emph{mandatory}; you must either pass
8790@option{-d}/@option{--defines} to @command{bison}, or use the
12545799
AD
8791@samp{%defines} directive.
8792@end table
8793
8794All these files are documented using Doxygen; run @command{doxygen}
8795for a complete and accurate documentation.
8796
8797@node C++ Semantic Values
8798@subsection C++ Semantic Values
8799@c - No objects in unions
178e123e 8800@c - YYSTYPE
12545799
AD
8801@c - Printer and destructor
8802
3cdc21cf
AD
8803Bison supports two different means to handle semantic values in C++. One is
8804alike the C interface, and relies on unions (@pxref{C++ Unions}). As C++
8805practitioners know, unions are inconvenient in C++, therefore another
8806approach is provided, based on variants (@pxref{C++ Variants}).
8807
8808@menu
8809* C++ Unions:: Semantic values cannot be objects
8810* C++ Variants:: Using objects as semantic values
8811@end menu
8812
8813@node C++ Unions
8814@subsubsection C++ Unions
8815
12545799
AD
8816The @code{%union} directive works as for C, see @ref{Union Decl, ,The
8817Collection of Value Types}. In particular it produces a genuine
3cdc21cf 8818@code{union}, which have a few specific features in C++.
12545799
AD
8819@itemize @minus
8820@item
fb9712a9
AD
8821The type @code{YYSTYPE} is defined but its use is discouraged: rather
8822you should refer to the parser's encapsulated type
8823@code{yy::parser::semantic_type}.
12545799
AD
8824@item
8825Non POD (Plain Old Data) types cannot be used. C++ forbids any
8826instance of classes with constructors in unions: only @emph{pointers}
8827to such objects are allowed.
8828@end itemize
8829
8830Because objects have to be stored via pointers, memory is not
8831reclaimed automatically: using the @code{%destructor} directive is the
8832only means to avoid leaks. @xref{Destructor Decl, , Freeing Discarded
8833Symbols}.
8834
3cdc21cf
AD
8835@node C++ Variants
8836@subsubsection C++ Variants
8837
8838Starting with version 2.6, Bison provides a @emph{variant} based
8839implementation of semantic values for C++. This alleviates all the
8840limitations reported in the previous section, and in particular, object
8841types can be used without pointers.
8842
8843To enable variant-based semantic values, set @code{%define} variable
8844@code{variant} (@pxref{Decl Summary, , variant}). Once this defined,
8845@code{%union} is ignored, and instead of using the name of the fields of the
8846@code{%union} to ``type'' the symbols, use genuine types.
8847
8848For instance, instead of
8849
8850@example
8851%union
8852@{
8853 int ival;
8854 std::string* sval;
8855@}
8856%token <ival> NUMBER;
8857%token <sval> STRING;
8858@end example
8859
8860@noindent
8861write
8862
8863@example
8864%token <int> NUMBER;
8865%token <std::string> STRING;
8866@end example
8867
8868@code{STRING} is no longer a pointer, which should fairly simplify the user
8869actions in the grammar and in the scanner (in particular the memory
8870management).
8871
8872Since C++ features destructors, and since it is customary to specialize
8873@code{operator<<} to support uniform printing of values, variants also
8874typically simplify Bison printers and destructors.
8875
8876Variants are stricter than unions. When based on unions, you may play any
8877dirty game with @code{yylval}, say storing an @code{int}, reading a
8878@code{char*}, and then storing a @code{double} in it. This is no longer
8879possible with variants: they must be initialized, then assigned to, and
8880eventually, destroyed.
8881
8882@deftypemethod {semantic_type} {T&} build<T> ()
8883Initialize, but leave empty. Returns the address where the actual value may
8884be stored. Requires that the variant was not initialized yet.
8885@end deftypemethod
8886
8887@deftypemethod {semantic_type} {T&} build<T> (const T& @var{t})
8888Initialize, and copy-construct from @var{t}.
8889@end deftypemethod
8890
8891
8892@strong{Warning}: We do not use Boost.Variant, for two reasons. First, it
8893appeared unacceptable to require Boost on the user's machine (i.e., the
8894machine on which the generated parser will be compiled, not the machine on
8895which @command{bison} was run). Second, for each possible semantic value,
8896Boost.Variant not only stores the value, but also a tag specifying its
8897type. But the parser already ``knows'' the type of the semantic value, so
8898that would be duplicating the information.
8899
8900Therefore we developed light-weight variants whose type tag is external (so
8901they are really like @code{unions} for C++ actually). But our code is much
8902less mature that Boost.Variant. So there is a number of limitations in
8903(the current implementation of) variants:
8904@itemize
8905@item
8906Alignment must be enforced: values should be aligned in memory according to
8907the most demanding type. Computing the smallest alignment possible requires
8908meta-programming techniques that are not currently implemented in Bison, and
8909therefore, since, as far as we know, @code{double} is the most demanding
8910type on all platforms, alignments are enforced for @code{double} whatever
8911types are actually used. This may waste space in some cases.
8912
8913@item
8914Our implementation is not conforming with strict aliasing rules. Alias
8915analysis is a technique used in optimizing compilers to detect when two
8916pointers are disjoint (they cannot ``meet''). Our implementation breaks
8917some of the rules that G++ 4.4 uses in its alias analysis, so @emph{strict
8918alias analysis must be disabled}. Use the option
8919@option{-fno-strict-aliasing} to compile the generated parser.
8920
8921@item
8922There might be portability issues we are not aware of.
8923@end itemize
8924
a6ca4ce2 8925As far as we know, these limitations @emph{can} be alleviated. All it takes
3cdc21cf 8926is some time and/or some talented C++ hacker willing to contribute to Bison.
12545799
AD
8927
8928@node C++ Location Values
8929@subsection C++ Location Values
8930@c - %locations
8931@c - class Position
8932@c - class Location
16dc6a9e 8933@c - %define filename_type "const symbol::Symbol"
12545799
AD
8934
8935When the directive @code{%locations} is used, the C++ parser supports
8936location tracking, see @ref{Locations, , Locations Overview}. Two
8937auxiliary classes define a @code{position}, a single point in a file,
8938and a @code{location}, a range composed of a pair of
8939@code{position}s (possibly spanning several files).
8940
fa4d969f 8941@deftypemethod {position} {std::string*} file
12545799
AD
8942The name of the file. It will always be handled as a pointer, the
8943parser will never duplicate nor deallocate it. As an experimental
8944feature you may change it to @samp{@var{type}*} using @samp{%define
16dc6a9e 8945filename_type "@var{type}"}.
12545799
AD
8946@end deftypemethod
8947
8948@deftypemethod {position} {unsigned int} line
8949The line, starting at 1.
8950@end deftypemethod
8951
8952@deftypemethod {position} {unsigned int} lines (int @var{height} = 1)
8953Advance by @var{height} lines, resetting the column number.
8954@end deftypemethod
8955
8956@deftypemethod {position} {unsigned int} column
8957The column, starting at 0.
8958@end deftypemethod
8959
8960@deftypemethod {position} {unsigned int} columns (int @var{width} = 1)
8961Advance by @var{width} columns, without changing the line number.
8962@end deftypemethod
8963
8964@deftypemethod {position} {position&} operator+= (position& @var{pos}, int @var{width})
8965@deftypemethodx {position} {position} operator+ (const position& @var{pos}, int @var{width})
8966@deftypemethodx {position} {position&} operator-= (const position& @var{pos}, int @var{width})
8967@deftypemethodx {position} {position} operator- (position& @var{pos}, int @var{width})
8968Various forms of syntactic sugar for @code{columns}.
8969@end deftypemethod
8970
8971@deftypemethod {position} {position} operator<< (std::ostream @var{o}, const position& @var{p})
8972Report @var{p} on @var{o} like this:
fa4d969f
PE
8973@samp{@var{file}:@var{line}.@var{column}}, or
8974@samp{@var{line}.@var{column}} if @var{file} is null.
12545799
AD
8975@end deftypemethod
8976
8977@deftypemethod {location} {position} begin
8978@deftypemethodx {location} {position} end
8979The first, inclusive, position of the range, and the first beyond.
8980@end deftypemethod
8981
8982@deftypemethod {location} {unsigned int} columns (int @var{width} = 1)
8983@deftypemethodx {location} {unsigned int} lines (int @var{height} = 1)
8984Advance the @code{end} position.
8985@end deftypemethod
8986
8987@deftypemethod {location} {location} operator+ (const location& @var{begin}, const location& @var{end})
8988@deftypemethodx {location} {location} operator+ (const location& @var{begin}, int @var{width})
8989@deftypemethodx {location} {location} operator+= (const location& @var{loc}, int @var{width})
8990Various forms of syntactic sugar.
8991@end deftypemethod
8992
8993@deftypemethod {location} {void} step ()
8994Move @code{begin} onto @code{end}.
8995@end deftypemethod
8996
8997
8998@node C++ Parser Interface
8999@subsection C++ Parser Interface
9000@c - define parser_class_name
9001@c - Ctor
9002@c - parse, error, set_debug_level, debug_level, set_debug_stream,
9003@c debug_stream.
9004@c - Reporting errors
9005
9006The output files @file{@var{output}.hh} and @file{@var{output}.cc}
9007declare and define the parser class in the namespace @code{yy}. The
9008class name defaults to @code{parser}, but may be changed using
16dc6a9e 9009@samp{%define parser_class_name "@var{name}"}. The interface of
9d9b8b70 9010this class is detailed below. It can be extended using the
12545799
AD
9011@code{%parse-param} feature: its semantics is slightly changed since
9012it describes an additional member of the parser class, and an
9013additional argument for its constructor.
9014
3cdc21cf
AD
9015@defcv {Type} {parser} {semantic_type}
9016@defcvx {Type} {parser} {location_type}
9017The types for semantic values and locations (if enabled).
9018@end defcv
9019
86e5b440
AD
9020@defcv {Type} {parser} {token}
9021A structure that contains (only) the definition of the tokens as the
9022@code{yytokentype} enumeration. To refer to the token @code{FOO}, the
9023scanner should use @code{yy::parser::token::FOO}. The scanner can use
9024@samp{typedef yy::parser::token token;} to ``import'' the token enumeration
9025(@pxref{Calc++ Scanner}).
9026@end defcv
9027
3cdc21cf
AD
9028@defcv {Type} {parser} {syntax_error}
9029This class derives from @code{std::runtime_error}. Throw instances of it
9030from user actions to raise parse errors. This is equivalent with first
9031invoking @code{error} to report the location and message of the syntax
9032error, and then to invoke @code{YYERROR} to enter the error-recovery mode.
9033But contrary to @code{YYERROR} which can only be invoked from user actions
9034(i.e., written in the action itself), the exception can be thrown from
9035function invoked from the user action.
8a0adb01 9036@end defcv
12545799
AD
9037
9038@deftypemethod {parser} {} parser (@var{type1} @var{arg1}, ...)
9039Build a new parser object. There are no arguments by default, unless
9040@samp{%parse-param @{@var{type1} @var{arg1}@}} was used.
9041@end deftypemethod
9042
3cdc21cf
AD
9043@deftypemethod {syntax_error} {} syntax_error (const location_type& @var{l}, const std::string& @var{m})
9044@deftypemethodx {syntax_error} {} syntax_error (const std::string& @var{m})
9045Instantiate a syntax-error exception.
9046@end deftypemethod
9047
12545799
AD
9048@deftypemethod {parser} {int} parse ()
9049Run the syntactic analysis, and return 0 on success, 1 otherwise.
9050@end deftypemethod
9051
9052@deftypemethod {parser} {std::ostream&} debug_stream ()
9053@deftypemethodx {parser} {void} set_debug_stream (std::ostream& @var{o})
9054Get or set the stream used for tracing the parsing. It defaults to
9055@code{std::cerr}.
9056@end deftypemethod
9057
9058@deftypemethod {parser} {debug_level_type} debug_level ()
9059@deftypemethodx {parser} {void} set_debug_level (debug_level @var{l})
9060Get or set the tracing level. Currently its value is either 0, no trace,
9d9b8b70 9061or nonzero, full tracing.
12545799
AD
9062@end deftypemethod
9063
9064@deftypemethod {parser} {void} error (const location_type& @var{l}, const std::string& @var{m})
3cdc21cf 9065@deftypemethodx {parser} {void} error (const std::string& @var{m})
12545799
AD
9066The definition for this member function must be supplied by the user:
9067the parser uses it to report a parser error occurring at @var{l},
3cdc21cf
AD
9068described by @var{m}. If location tracking is not enabled, the second
9069signature is used.
12545799
AD
9070@end deftypemethod
9071
9072
9073@node C++ Scanner Interface
9074@subsection C++ Scanner Interface
9075@c - prefix for yylex.
9076@c - Pure interface to yylex
9077@c - %lex-param
9078
9079The parser invokes the scanner by calling @code{yylex}. Contrary to C
9080parsers, C++ parsers are always pure: there is no point in using the
3cdc21cf
AD
9081@samp{%define api.pure} directive. The actual interface with @code{yylex}
9082depends whether you use unions, or variants.
12545799 9083
3cdc21cf
AD
9084@menu
9085* Split Symbols:: Passing symbols as two/three components
9086* Complete Symbols:: Making symbols a whole
9087@end menu
9088
9089@node Split Symbols
9090@subsubsection Split Symbols
9091
9092Therefore the interface is as follows.
9093
86e5b440
AD
9094@deftypemethod {parser} {int} yylex (semantic_type* @var{yylval}, location_type* @var{yylloc}, @var{type1} @var{arg1}, ...)
9095@deftypemethodx {parser} {int} yylex (semantic_type* @var{yylval}, @var{type1} @var{arg1}, ...)
3cdc21cf
AD
9096Return the next token. Its type is the return value, its semantic value and
9097location (if enabled) being @var{yylval} and @var{yylloc}. Invocations of
12545799
AD
9098@samp{%lex-param @{@var{type1} @var{arg1}@}} yield additional arguments.
9099@end deftypemethod
9100
3cdc21cf
AD
9101Note that when using variants, the interface for @code{yylex} is the same,
9102but @code{yylval} is handled differently.
9103
9104Regular union-based code in Lex scanner typically look like:
9105
9106@example
9107[0-9]+ @{
9108 yylval.ival = text_to_int (yytext);
9109 return yy::parser::INTEGER;
9110 @}
9111[a-z]+ @{
9112 yylval.sval = new std::string (yytext);
9113 return yy::parser::IDENTIFIER;
9114 @}
9115@end example
9116
9117Using variants, @code{yylval} is already constructed, but it is not
9118initialized. So the code would look like:
9119
9120@example
9121[0-9]+ @{
9122 yylval.build<int>() = text_to_int (yytext);
9123 return yy::parser::INTEGER;
9124 @}
9125[a-z]+ @{
9126 yylval.build<std::string> = yytext;
9127 return yy::parser::IDENTIFIER;
9128 @}
9129@end example
9130
9131@noindent
9132or
9133
9134@example
9135[0-9]+ @{
9136 yylval.build(text_to_int (yytext));
9137 return yy::parser::INTEGER;
9138 @}
9139[a-z]+ @{
9140 yylval.build(yytext);
9141 return yy::parser::IDENTIFIER;
9142 @}
9143@end example
9144
9145
9146@node Complete Symbols
9147@subsubsection Complete Symbols
9148
9149If you specified both @code{%define variant} and @code{%define lex_symbol},
9150the @code{parser} class also defines the class @code{parser::symbol_type}
9151which defines a @emph{complete} symbol, aggregating its type (i.e., the
9152traditional value returned by @code{yylex}), its semantic value (i.e., the
9153value passed in @code{yylval}, and possibly its location (@code{yylloc}).
9154
9155@deftypemethod {symbol_type} {} symbol_type (token_type @var{type}, const semantic_type& @var{value}, const location_type& @var{location})
9156Build a complete terminal symbol which token type is @var{type}, and which
9157semantic value is @var{value}. If location tracking is enabled, also pass
9158the @var{location}.
9159@end deftypemethod
9160
9161This interface is low-level and should not be used for two reasons. First,
9162it is inconvenient, as you still have to build the semantic value, which is
9163a variant, and second, because consistency is not enforced: as with unions,
9164it is still possible to give an integer as semantic value for a string.
9165
9166So for each token type, Bison generates named constructors as follows.
9167
9168@deftypemethod {symbol_type} {} make_@var{token} (const @var{value_type}& @var{value}, const location_type& @var{location})
9169@deftypemethodx {symbol_type} {} make_@var{token} (const location_type& @var{location})
9170Build a complete terminal symbol for the token type @var{token} (not
9171including the @code{api.tokens.prefix}) whose possible semantic value is
9172@var{value} of adequate @var{value_type}. If location tracking is enabled,
9173also pass the @var{location}.
9174@end deftypemethod
9175
9176For instance, given the following declarations:
9177
9178@example
9179%define api.tokens.prefix "TOK_"
9180%token <std::string> IDENTIFIER;
9181%token <int> INTEGER;
9182%token COLON;
9183@end example
9184
9185@noindent
9186Bison generates the following functions:
9187
9188@example
9189symbol_type make_IDENTIFIER(const std::string& v,
9190 const location_type& l);
9191symbol_type make_INTEGER(const int& v,
9192 const location_type& loc);
9193symbol_type make_COLON(const location_type& loc);
9194@end example
9195
9196@noindent
9197which should be used in a Lex-scanner as follows.
9198
9199@example
9200[0-9]+ return yy::parser::make_INTEGER(text_to_int (yytext), loc);
9201[a-z]+ return yy::parser::make_IDENTIFIER(yytext, loc);
9202":" return yy::parser::make_COLON(loc);
9203@end example
9204
9205Tokens that do not have an identifier are not accessible: you cannot simply
9206use characters such as @code{':'}, they must be declared with @code{%token}.
12545799
AD
9207
9208@node A Complete C++ Example
8405b70c 9209@subsection A Complete C++ Example
12545799
AD
9210
9211This section demonstrates the use of a C++ parser with a simple but
9212complete example. This example should be available on your system,
3cdc21cf 9213ready to compile, in the directory @dfn{.../bison/examples/calc++}. It
12545799
AD
9214focuses on the use of Bison, therefore the design of the various C++
9215classes is very naive: no accessors, no encapsulation of members etc.
9216We will use a Lex scanner, and more precisely, a Flex scanner, to
3cdc21cf 9217demonstrate the various interactions. A hand-written scanner is
12545799
AD
9218actually easier to interface with.
9219
9220@menu
9221* Calc++ --- C++ Calculator:: The specifications
9222* Calc++ Parsing Driver:: An active parsing context
9223* Calc++ Parser:: A parser class
9224* Calc++ Scanner:: A pure C++ Flex scanner
9225* Calc++ Top Level:: Conducting the band
9226@end menu
9227
9228@node Calc++ --- C++ Calculator
8405b70c 9229@subsubsection Calc++ --- C++ Calculator
12545799
AD
9230
9231Of course the grammar is dedicated to arithmetics, a single
9d9b8b70 9232expression, possibly preceded by variable assignments. An
12545799
AD
9233environment containing possibly predefined variables such as
9234@code{one} and @code{two}, is exchanged with the parser. An example
9235of valid input follows.
9236
9237@example
9238three := 3
9239seven := one + two * three
9240seven * seven
9241@end example
9242
9243@node Calc++ Parsing Driver
8405b70c 9244@subsubsection Calc++ Parsing Driver
12545799
AD
9245@c - An env
9246@c - A place to store error messages
9247@c - A place for the result
9248
9249To support a pure interface with the parser (and the scanner) the
9250technique of the ``parsing context'' is convenient: a structure
9251containing all the data to exchange. Since, in addition to simply
9252launch the parsing, there are several auxiliary tasks to execute (open
9253the file for parsing, instantiate the parser etc.), we recommend
9254transforming the simple parsing context structure into a fully blown
9255@dfn{parsing driver} class.
9256
9257The declaration of this driver class, @file{calc++-driver.hh}, is as
9258follows. The first part includes the CPP guard and imports the
fb9712a9
AD
9259required standard library components, and the declaration of the parser
9260class.
12545799 9261
1c59e0a1 9262@comment file: calc++-driver.hh
12545799
AD
9263@example
9264#ifndef CALCXX_DRIVER_HH
9265# define CALCXX_DRIVER_HH
9266# include <string>
9267# include <map>
fb9712a9 9268# include "calc++-parser.hh"
12545799
AD
9269@end example
9270
12545799
AD
9271
9272@noindent
9273Then comes the declaration of the scanning function. Flex expects
9274the signature of @code{yylex} to be defined in the macro
9275@code{YY_DECL}, and the C++ parser expects it to be declared. We can
9276factor both as follows.
1c59e0a1
AD
9277
9278@comment file: calc++-driver.hh
12545799 9279@example
3dc5e96b 9280// Tell Flex the lexer's prototype ...
3cdc21cf
AD
9281# define YY_DECL \
9282 yy::calcxx_parser::symbol_type yylex (calcxx_driver& driver)
12545799
AD
9283// ... and declare it for the parser's sake.
9284YY_DECL;
9285@end example
9286
9287@noindent
9288The @code{calcxx_driver} class is then declared with its most obvious
9289members.
9290
1c59e0a1 9291@comment file: calc++-driver.hh
12545799
AD
9292@example
9293// Conducting the whole scanning and parsing of Calc++.
9294class calcxx_driver
9295@{
9296public:
9297 calcxx_driver ();
9298 virtual ~calcxx_driver ();
9299
9300 std::map<std::string, int> variables;
9301
9302 int result;
9303@end example
9304
9305@noindent
3cdc21cf
AD
9306To encapsulate the coordination with the Flex scanner, it is useful to have
9307member functions to open and close the scanning phase.
12545799 9308
1c59e0a1 9309@comment file: calc++-driver.hh
12545799
AD
9310@example
9311 // Handling the scanner.
9312 void scan_begin ();
9313 void scan_end ();
9314 bool trace_scanning;
9315@end example
9316
9317@noindent
9318Similarly for the parser itself.
9319
1c59e0a1 9320@comment file: calc++-driver.hh
12545799 9321@example
3cdc21cf
AD
9322 // Run the parser on file F.
9323 // Return 0 on success.
bb32f4f2 9324 int parse (const std::string& f);
3cdc21cf
AD
9325 // The name of the file being parsed.
9326 // Used later to pass the file name to the location tracker.
12545799 9327 std::string file;
3cdc21cf 9328 // Whether parser traces should be generated.
12545799
AD
9329 bool trace_parsing;
9330@end example
9331
9332@noindent
9333To demonstrate pure handling of parse errors, instead of simply
9334dumping them on the standard error output, we will pass them to the
9335compiler driver using the following two member functions. Finally, we
9336close the class declaration and CPP guard.
9337
1c59e0a1 9338@comment file: calc++-driver.hh
12545799
AD
9339@example
9340 // Error handling.
9341 void error (const yy::location& l, const std::string& m);
9342 void error (const std::string& m);
9343@};
9344#endif // ! CALCXX_DRIVER_HH
9345@end example
9346
9347The implementation of the driver is straightforward. The @code{parse}
9348member function deserves some attention. The @code{error} functions
9349are simple stubs, they should actually register the located error
9350messages and set error state.
9351
1c59e0a1 9352@comment file: calc++-driver.cc
12545799
AD
9353@example
9354#include "calc++-driver.hh"
9355#include "calc++-parser.hh"
9356
9357calcxx_driver::calcxx_driver ()
9358 : trace_scanning (false), trace_parsing (false)
9359@{
9360 variables["one"] = 1;
9361 variables["two"] = 2;
9362@}
9363
9364calcxx_driver::~calcxx_driver ()
9365@{
9366@}
9367
bb32f4f2 9368int
12545799
AD
9369calcxx_driver::parse (const std::string &f)
9370@{
9371 file = f;
9372 scan_begin ();
9373 yy::calcxx_parser parser (*this);
9374 parser.set_debug_level (trace_parsing);
bb32f4f2 9375 int res = parser.parse ();
12545799 9376 scan_end ();
bb32f4f2 9377 return res;
12545799
AD
9378@}
9379
9380void
9381calcxx_driver::error (const yy::location& l, const std::string& m)
9382@{
9383 std::cerr << l << ": " << m << std::endl;
9384@}
9385
9386void
9387calcxx_driver::error (const std::string& m)
9388@{
9389 std::cerr << m << std::endl;
9390@}
9391@end example
9392
9393@node Calc++ Parser
8405b70c 9394@subsubsection Calc++ Parser
12545799 9395
ff7571c0
JD
9396The grammar file @file{calc++-parser.yy} starts by asking for the C++
9397deterministic parser skeleton, the creation of the parser header file,
9398and specifies the name of the parser class. Because the C++ skeleton
9399changed several times, it is safer to require the version you designed
9400the grammar for.
1c59e0a1
AD
9401
9402@comment file: calc++-parser.yy
12545799 9403@example
ed4d67dc 9404%skeleton "lalr1.cc" /* -*- C++ -*- */
e6e704dc 9405%require "@value{VERSION}"
12545799 9406%defines
16dc6a9e 9407%define parser_class_name "calcxx_parser"
fb9712a9
AD
9408@end example
9409
3cdc21cf
AD
9410@noindent
9411@findex %define variant
9412@findex %define lex_symbol
9413This example will use genuine C++ objects as semantic values, therefore, we
9414require the variant-based interface. To make sure we properly use it, we
9415enable assertions. To fully benefit from type-safety and more natural
9416definition of ``symbol'', we enable @code{lex_symbol}.
9417
9418@comment file: calc++-parser.yy
9419@example
9420%define variant
9421%define parse.assert
9422%define lex_symbol
9423@end example
9424
fb9712a9 9425@noindent
16dc6a9e 9426@findex %code requires
3cdc21cf
AD
9427Then come the declarations/inclusions needed by the semantic values.
9428Because the parser uses the parsing driver and reciprocally, both would like
a6ca4ce2 9429to include the header of the other, which is, of course, insane. This
3cdc21cf 9430mutual dependency will be broken using forward declarations. Because the
fb9712a9 9431driver's header needs detailed knowledge about the parser class (in
3cdc21cf
AD
9432particular its inner types), it is the parser's header which will use a
9433forward declaration of the driver. @xref{Decl Summary, ,%code}.
fb9712a9
AD
9434
9435@comment file: calc++-parser.yy
9436@example
3cdc21cf
AD
9437%code requires
9438@{
12545799 9439# include <string>
fb9712a9 9440class calcxx_driver;
9bc0dd67 9441@}
12545799
AD
9442@end example
9443
9444@noindent
9445The driver is passed by reference to the parser and to the scanner.
9446This provides a simple but effective pure interface, not relying on
9447global variables.
9448
1c59e0a1 9449@comment file: calc++-parser.yy
12545799
AD
9450@example
9451// The parsing context.
2055a44e 9452%param @{ calcxx_driver& driver @}
12545799
AD
9453@end example
9454
9455@noindent
2055a44e 9456Then we request location tracking, and initialize the
f50bfcd6 9457first location's file name. Afterward new locations are computed
12545799 9458relatively to the previous locations: the file name will be
2055a44e 9459propagated.
12545799 9460
1c59e0a1 9461@comment file: calc++-parser.yy
12545799
AD
9462@example
9463%locations
9464%initial-action
9465@{
9466 // Initialize the initial location.
b47dbebe 9467 @@$.begin.filename = @@$.end.filename = &driver.file;
12545799
AD
9468@};
9469@end example
9470
9471@noindent
2055a44e 9472Use the following two directives to enable parser tracing and verbose
12545799
AD
9473error messages.
9474
1c59e0a1 9475@comment file: calc++-parser.yy
12545799 9476@example
fa819509 9477%define parse.trace
cf499cff 9478%define parse.error verbose
12545799
AD
9479@end example
9480
fb9712a9 9481@noindent
136a0f76
PB
9482@findex %code
9483The code between @samp{%code @{} and @samp{@}} is output in the
34f98f46 9484@file{*.cc} file; it needs detailed knowledge about the driver.
fb9712a9
AD
9485
9486@comment file: calc++-parser.yy
9487@example
3cdc21cf
AD
9488%code
9489@{
fb9712a9 9490# include "calc++-driver.hh"
34f98f46 9491@}
fb9712a9
AD
9492@end example
9493
9494
12545799
AD
9495@noindent
9496The token numbered as 0 corresponds to end of file; the following line
99c08fb6
AD
9497allows for nicer error messages referring to ``end of file'' instead of
9498``$end''. Similarly user friendly names are provided for each symbol.
9499To avoid name clashes in the generated files (@pxref{Calc++ Scanner}),
4c6622c2 9500prefix tokens with @code{TOK_} (@pxref{Decl Summary,, api.tokens.prefix}).
12545799 9501
1c59e0a1 9502@comment file: calc++-parser.yy
12545799 9503@example
4c6622c2 9504%define api.tokens.prefix "TOK_"
3cdc21cf
AD
9505%token
9506 END 0 "end of file"
9507 ASSIGN ":="
9508 MINUS "-"
9509 PLUS "+"
9510 STAR "*"
9511 SLASH "/"
9512 LPAREN "("
9513 RPAREN ")"
9514;
12545799
AD
9515@end example
9516
9517@noindent
3cdc21cf
AD
9518Since we use variant-based semantic values, @code{%union} is not used, and
9519both @code{%type} and @code{%token} expect genuine types, as opposed to type
9520tags.
12545799 9521
1c59e0a1 9522@comment file: calc++-parser.yy
12545799 9523@example
3cdc21cf
AD
9524%token <std::string> IDENTIFIER "identifier"
9525%token <int> NUMBER "number"
9526%type <int> exp
9527@end example
9528
9529@noindent
9530No @code{%destructor} is needed to enable memory deallocation during error
9531recovery; the memory, for strings for instance, will be reclaimed by the
9532regular destructors. All the values are printed using their
9533@code{operator<<}.
12545799 9534
3cdc21cf
AD
9535@c FIXME: Document %printer, and mention that it takes a braced-code operand.
9536@comment file: calc++-parser.yy
9537@example
9538%printer @{ debug_stream () << $$; @} <*>;
12545799
AD
9539@end example
9540
9541@noindent
3cdc21cf
AD
9542The grammar itself is straightforward (@pxref{Location Tracking Calc, ,
9543Location Tracking Calculator: @code{ltcalc}}).
12545799 9544
1c59e0a1 9545@comment file: calc++-parser.yy
12545799
AD
9546@example
9547%%
9548%start unit;
9549unit: assignments exp @{ driver.result = $2; @};
9550
99c08fb6
AD
9551assignments:
9552 assignments assignment @{@}
9553| /* Nothing. */ @{@};
12545799 9554
3dc5e96b 9555assignment:
3cdc21cf 9556 "identifier" ":=" exp @{ driver.variables[$1] = $3; @};
12545799 9557
3cdc21cf
AD
9558%left "+" "-";
9559%left "*" "/";
99c08fb6 9560exp:
3cdc21cf
AD
9561 exp "+" exp @{ $$ = $1 + $3; @}
9562| exp "-" exp @{ $$ = $1 - $3; @}
9563| exp "*" exp @{ $$ = $1 * $3; @}
9564| exp "/" exp @{ $$ = $1 / $3; @}
298e8ad9 9565| "(" exp ")" @{ std::swap ($$, $2); @}
3cdc21cf 9566| "identifier" @{ $$ = driver.variables[$1]; @}
298e8ad9 9567| "number" @{ std::swap ($$, $1); @};
12545799
AD
9568%%
9569@end example
9570
9571@noindent
9572Finally the @code{error} member function registers the errors to the
9573driver.
9574
1c59e0a1 9575@comment file: calc++-parser.yy
12545799
AD
9576@example
9577void
3cdc21cf 9578yy::calcxx_parser::error (const location_type& l,
1c59e0a1 9579 const std::string& m)
12545799
AD
9580@{
9581 driver.error (l, m);
9582@}
9583@end example
9584
9585@node Calc++ Scanner
8405b70c 9586@subsubsection Calc++ Scanner
12545799
AD
9587
9588The Flex scanner first includes the driver declaration, then the
9589parser's to get the set of defined tokens.
9590
1c59e0a1 9591@comment file: calc++-scanner.ll
12545799
AD
9592@example
9593%@{ /* -*- C++ -*- */
3c248d70
AD
9594# include <cerrno>
9595# include <climits>
3cdc21cf 9596# include <cstdlib>
12545799
AD
9597# include <string>
9598# include "calc++-driver.hh"
9599# include "calc++-parser.hh"
eaea13f5 9600
3cdc21cf
AD
9601// Work around an incompatibility in flex (at least versions
9602// 2.5.31 through 2.5.33): it generates code that does
9603// not conform to C89. See Debian bug 333231
9604// <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>.
7870f699
PE
9605# undef yywrap
9606# define yywrap() 1
eaea13f5 9607
3cdc21cf
AD
9608// The location of the current token.
9609static yy::location loc;
12545799
AD
9610%@}
9611@end example
9612
9613@noindent
9614Because there is no @code{#include}-like feature we don't need
9615@code{yywrap}, we don't need @code{unput} either, and we parse an
9616actual file, this is not an interactive session with the user.
3cdc21cf 9617Finally, we enable scanner tracing.
12545799 9618
1c59e0a1 9619@comment file: calc++-scanner.ll
12545799
AD
9620@example
9621%option noyywrap nounput batch debug
9622@end example
9623
9624@noindent
9625Abbreviations allow for more readable rules.
9626
1c59e0a1 9627@comment file: calc++-scanner.ll
12545799
AD
9628@example
9629id [a-zA-Z][a-zA-Z_0-9]*
9630int [0-9]+
9631blank [ \t]
9632@end example
9633
9634@noindent
9d9b8b70 9635The following paragraph suffices to track locations accurately. Each
12545799 9636time @code{yylex} is invoked, the begin position is moved onto the end
3cdc21cf
AD
9637position. Then when a pattern is matched, its width is added to the end
9638column. When matching ends of lines, the end
12545799
AD
9639cursor is adjusted, and each time blanks are matched, the begin cursor
9640is moved onto the end cursor to effectively ignore the blanks
9641preceding tokens. Comments would be treated equally.
9642
1c59e0a1 9643@comment file: calc++-scanner.ll
12545799 9644@example
828c373b 9645%@{
3cdc21cf
AD
9646 // Code run each time a pattern is matched.
9647 # define YY_USER_ACTION loc.columns (yyleng);
828c373b 9648%@}
12545799
AD
9649%%
9650%@{
3cdc21cf
AD
9651 // Code run each time yylex is called.
9652 loc.step ();
12545799 9653%@}
3cdc21cf
AD
9654@{blank@}+ loc.step ();
9655[\n]+ loc.lines (yyleng); loc.step ();
12545799
AD
9656@end example
9657
9658@noindent
3cdc21cf 9659The rules are simple. The driver is used to report errors.
12545799 9660
1c59e0a1 9661@comment file: calc++-scanner.ll
12545799 9662@example
3cdc21cf
AD
9663"-" return yy::calcxx_parser::make_MINUS(loc);
9664"+" return yy::calcxx_parser::make_PLUS(loc);
9665"*" return yy::calcxx_parser::make_STAR(loc);
9666"/" return yy::calcxx_parser::make_SLASH(loc);
9667"(" return yy::calcxx_parser::make_LPAREN(loc);
9668")" return yy::calcxx_parser::make_RPAREN(loc);
9669":=" return yy::calcxx_parser::make_ASSIGN(loc);
9670
04098407
PE
9671@{int@} @{
9672 errno = 0;
9673 long n = strtol (yytext, NULL, 10);
9674 if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))
3cdc21cf
AD
9675 driver.error (loc, "integer is out of range");
9676 return yy::calcxx_parser::make_NUMBER(n, loc);
04098407 9677@}
3cdc21cf
AD
9678@{id@} return yy::calcxx_parser::make_IDENTIFIER(yytext, loc);
9679. driver.error (loc, "invalid character");
9680<<EOF>> return yy::calcxx_parser::make_END(loc);
12545799
AD
9681%%
9682@end example
9683
9684@noindent
3cdc21cf 9685Finally, because the scanner-related driver's member-functions depend
12545799
AD
9686on the scanner's data, it is simpler to implement them in this file.
9687
1c59e0a1 9688@comment file: calc++-scanner.ll
12545799
AD
9689@example
9690void
9691calcxx_driver::scan_begin ()
9692@{
9693 yy_flex_debug = trace_scanning;
bb32f4f2
AD
9694 if (file == "-")
9695 yyin = stdin;
9696 else if (!(yyin = fopen (file.c_str (), "r")))
9697 @{
3cdc21cf 9698 error (std::string ("cannot open ") + file + ": " + strerror(errno));
bb32f4f2
AD
9699 exit (1);
9700 @}
12545799
AD
9701@}
9702
9703void
9704calcxx_driver::scan_end ()
9705@{
9706 fclose (yyin);
9707@}
9708@end example
9709
9710@node Calc++ Top Level
8405b70c 9711@subsubsection Calc++ Top Level
12545799
AD
9712
9713The top level file, @file{calc++.cc}, poses no problem.
9714
1c59e0a1 9715@comment file: calc++.cc
12545799
AD
9716@example
9717#include <iostream>
9718#include "calc++-driver.hh"
9719
9720int
fa4d969f 9721main (int argc, char *argv[])
12545799 9722@{
414c76a4 9723 int res = 0;
12545799
AD
9724 calcxx_driver driver;
9725 for (++argv; argv[0]; ++argv)
9726 if (*argv == std::string ("-p"))
9727 driver.trace_parsing = true;
9728 else if (*argv == std::string ("-s"))
9729 driver.trace_scanning = true;
bb32f4f2
AD
9730 else if (!driver.parse (*argv))
9731 std::cout << driver.result << std::endl;
414c76a4
AD
9732 else
9733 res = 1;
9734 return res;
12545799
AD
9735@}
9736@end example
9737
8405b70c
PB
9738@node Java Parsers
9739@section Java Parsers
9740
9741@menu
f5f419de
DJ
9742* Java Bison Interface:: Asking for Java parser generation
9743* Java Semantic Values:: %type and %token vs. Java
9744* Java Location Values:: The position and location classes
9745* Java Parser Interface:: Instantiating and running the parser
9746* Java Scanner Interface:: Specifying the scanner for the parser
9747* Java Action Features:: Special features for use in actions
9748* Java Differences:: Differences between C/C++ and Java Grammars
9749* Java Declarations Summary:: List of Bison declarations used with Java
8405b70c
PB
9750@end menu
9751
9752@node Java Bison Interface
9753@subsection Java Bison Interface
9754@c - %language "Java"
8405b70c 9755
59da312b
JD
9756(The current Java interface is experimental and may evolve.
9757More user feedback will help to stabilize it.)
9758
e254a580
DJ
9759The Java parser skeletons are selected using the @code{%language "Java"}
9760directive or the @option{-L java}/@option{--language=java} option.
8405b70c 9761
e254a580 9762@c FIXME: Documented bug.
ff7571c0
JD
9763When generating a Java parser, @code{bison @var{basename}.y} will
9764create a single Java source file named @file{@var{basename}.java}
9765containing the parser implementation. Using a grammar file without a
9766@file{.y} suffix is currently broken. The basename of the parser
9767implementation file can be changed by the @code{%file-prefix}
9768directive or the @option{-p}/@option{--name-prefix} option. The
9769entire parser implementation file name can be changed by the
9770@code{%output} directive or the @option{-o}/@option{--output} option.
9771The parser implementation file contains a single class for the parser.
8405b70c 9772
e254a580 9773You can create documentation for generated parsers using Javadoc.
8405b70c 9774
e254a580
DJ
9775Contrary to C parsers, Java parsers do not use global variables; the
9776state of the parser is always local to an instance of the parser class.
9777Therefore, all Java parsers are ``pure'', and the @code{%pure-parser}
67501061 9778and @samp{%define api.pure} directives does not do anything when used in
e254a580 9779Java.
8405b70c 9780
e254a580 9781Push parsers are currently unsupported in Java and @code{%define
67212941 9782api.push-pull} have no effect.
01b477c6 9783
8a4281b9 9784GLR parsers are currently unsupported in Java. Do not use the
e254a580
DJ
9785@code{glr-parser} directive.
9786
9787No header file can be generated for Java parsers. Do not use the
9788@code{%defines} directive or the @option{-d}/@option{--defines} options.
9789
9790@c FIXME: Possible code change.
fa819509
AD
9791Currently, support for tracing is always compiled
9792in. Thus the @samp{%define parse.trace} and @samp{%token-table}
9793directives and the
e254a580
DJ
9794@option{-t}/@option{--debug} and @option{-k}/@option{--token-table}
9795options have no effect. This may change in the future to eliminate
fa819509
AD
9796unused code in the generated parser, so use @samp{%define parse.trace}
9797explicitly
1979121c 9798if needed. Also, in the future the
e254a580
DJ
9799@code{%token-table} directive might enable a public interface to
9800access the token names and codes.
8405b70c 9801
09ccae9b 9802Getting a ``code too large'' error from the Java compiler means the code
f50bfcd6 9803hit the 64KB bytecode per method limitation of the Java class file.
09ccae9b
DJ
9804Try reducing the amount of code in actions and static initializers;
9805otherwise, report a bug so that the parser skeleton will be improved.
9806
9807
8405b70c
PB
9808@node Java Semantic Values
9809@subsection Java Semantic Values
9810@c - No %union, specify type in %type/%token.
9811@c - YYSTYPE
9812@c - Printer and destructor
9813
9814There is no @code{%union} directive in Java parsers. Instead, the
9815semantic values' types (class names) should be specified in the
9816@code{%type} or @code{%token} directive:
9817
9818@example
9819%type <Expression> expr assignment_expr term factor
9820%type <Integer> number
9821@end example
9822
9823By default, the semantic stack is declared to have @code{Object} members,
9824which means that the class types you specify can be of any class.
9825To improve the type safety of the parser, you can declare the common
67501061 9826superclass of all the semantic values using the @samp{%define stype}
e254a580 9827directive. For example, after the following declaration:
8405b70c
PB
9828
9829@example
e254a580 9830%define stype "ASTNode"
8405b70c
PB
9831@end example
9832
9833@noindent
9834any @code{%type} or @code{%token} specifying a semantic type which
9835is not a subclass of ASTNode, will cause a compile-time error.
9836
e254a580 9837@c FIXME: Documented bug.
8405b70c
PB
9838Types used in the directives may be qualified with a package name.
9839Primitive data types are accepted for Java version 1.5 or later. Note
9840that in this case the autoboxing feature of Java 1.5 will be used.
e254a580
DJ
9841Generic types may not be used; this is due to a limitation in the
9842implementation of Bison, and may change in future releases.
8405b70c
PB
9843
9844Java parsers do not support @code{%destructor}, since the language
9845adopts garbage collection. The parser will try to hold references
9846to semantic values for as little time as needed.
9847
9848Java parsers do not support @code{%printer}, as @code{toString()}
9849can be used to print the semantic values. This however may change
9850(in a backwards-compatible way) in future versions of Bison.
9851
9852
9853@node Java Location Values
9854@subsection Java Location Values
9855@c - %locations
9856@c - class Position
9857@c - class Location
9858
9859When the directive @code{%locations} is used, the Java parser
9860supports location tracking, see @ref{Locations, , Locations Overview}.
9861An auxiliary user-defined class defines a @dfn{position}, a single point
9862in a file; Bison itself defines a class representing a @dfn{location},
9863a range composed of a pair of positions (possibly spanning several
9864files). The location class is an inner class of the parser; the name
e254a580 9865is @code{Location} by default, and may also be renamed using
cf499cff 9866@samp{%define location_type "@var{class-name}"}.
8405b70c
PB
9867
9868The location class treats the position as a completely opaque value.
9869By default, the class name is @code{Position}, but this can be changed
67501061 9870with @samp{%define position_type "@var{class-name}"}. This class must
e254a580 9871be supplied by the user.
8405b70c
PB
9872
9873
e254a580
DJ
9874@deftypeivar {Location} {Position} begin
9875@deftypeivarx {Location} {Position} end
8405b70c 9876The first, inclusive, position of the range, and the first beyond.
e254a580
DJ
9877@end deftypeivar
9878
9879@deftypeop {Constructor} {Location} {} Location (Position @var{loc})
c265fd6b 9880Create a @code{Location} denoting an empty range located at a given point.
e254a580 9881@end deftypeop
8405b70c 9882
e254a580
DJ
9883@deftypeop {Constructor} {Location} {} Location (Position @var{begin}, Position @var{end})
9884Create a @code{Location} from the endpoints of the range.
9885@end deftypeop
9886
9887@deftypemethod {Location} {String} toString ()
8405b70c
PB
9888Prints the range represented by the location. For this to work
9889properly, the position class should override the @code{equals} and
9890@code{toString} methods appropriately.
9891@end deftypemethod
9892
9893
9894@node Java Parser Interface
9895@subsection Java Parser Interface
9896@c - define parser_class_name
9897@c - Ctor
9898@c - parse, error, set_debug_level, debug_level, set_debug_stream,
9899@c debug_stream.
9900@c - Reporting errors
9901
e254a580
DJ
9902The name of the generated parser class defaults to @code{YYParser}. The
9903@code{YY} prefix may be changed using the @code{%name-prefix} directive
9904or the @option{-p}/@option{--name-prefix} option. Alternatively, use
67501061 9905@samp{%define parser_class_name "@var{name}"} to give a custom name to
e254a580 9906the class. The interface of this class is detailed below.
8405b70c 9907
e254a580 9908By default, the parser class has package visibility. A declaration
67501061 9909@samp{%define public} will change to public visibility. Remember that,
e254a580
DJ
9910according to the Java language specification, the name of the @file{.java}
9911file should match the name of the class in this case. Similarly, you can
9912use @code{abstract}, @code{final} and @code{strictfp} with the
9913@code{%define} declaration to add other modifiers to the parser class.
67501061 9914A single @samp{%define annotations "@var{annotations}"} directive can
1979121c 9915be used to add any number of annotations to the parser class.
e254a580
DJ
9916
9917The Java package name of the parser class can be specified using the
67501061 9918@samp{%define package} directive. The superclass and the implemented
e254a580 9919interfaces of the parser class can be specified with the @code{%define
67501061 9920extends} and @samp{%define implements} directives.
e254a580
DJ
9921
9922The parser class defines an inner class, @code{Location}, that is used
9923for location tracking (see @ref{Java Location Values}), and a inner
9924interface, @code{Lexer} (see @ref{Java Scanner Interface}). Other than
9925these inner class/interface, and the members described in the interface
9926below, all the other members and fields are preceded with a @code{yy} or
9927@code{YY} prefix to avoid clashes with user code.
9928
e254a580
DJ
9929The parser class can be extended using the @code{%parse-param}
9930directive. Each occurrence of the directive will add a @code{protected
9931final} field to the parser class, and an argument to its constructor,
9932which initialize them automatically.
9933
e254a580
DJ
9934@deftypeop {Constructor} {YYParser} {} YYParser (@var{lex_param}, @dots{}, @var{parse_param}, @dots{})
9935Build a new parser object with embedded @code{%code lexer}. There are
2055a44e
AD
9936no parameters, unless @code{%param}s and/or @code{%parse-param}s and/or
9937@code{%lex-param}s are used.
1979121c
DJ
9938
9939Use @code{%code init} for code added to the start of the constructor
9940body. This is especially useful to initialize superclasses. Use
f50bfcd6 9941@samp{%define init_throws} to specify any uncaught exceptions.
e254a580
DJ
9942@end deftypeop
9943
9944@deftypeop {Constructor} {YYParser} {} YYParser (Lexer @var{lexer}, @var{parse_param}, @dots{})
9945Build a new parser object using the specified scanner. There are no
2055a44e
AD
9946additional parameters unless @code{%param}s and/or @code{%parse-param}s are
9947used.
e254a580
DJ
9948
9949If the scanner is defined by @code{%code lexer}, this constructor is
9950declared @code{protected} and is called automatically with a scanner
2055a44e 9951created with the correct @code{%param}s and/or @code{%lex-param}s.
1979121c
DJ
9952
9953Use @code{%code init} for code added to the start of the constructor
9954body. This is especially useful to initialize superclasses. Use
67501061 9955@samp{%define init_throws} to specify any uncatch exceptions.
e254a580 9956@end deftypeop
8405b70c
PB
9957
9958@deftypemethod {YYParser} {boolean} parse ()
9959Run the syntactic analysis, and return @code{true} on success,
9960@code{false} otherwise.
9961@end deftypemethod
9962
1979121c
DJ
9963@deftypemethod {YYParser} {boolean} getErrorVerbose ()
9964@deftypemethodx {YYParser} {void} setErrorVerbose (boolean @var{verbose})
9965Get or set the option to produce verbose error messages. These are only
cf499cff 9966available with @samp{%define parse.error verbose}, which also turns on
1979121c
DJ
9967verbose error messages.
9968@end deftypemethod
9969
9970@deftypemethod {YYParser} {void} yyerror (String @var{msg})
9971@deftypemethodx {YYParser} {void} yyerror (Position @var{pos}, String @var{msg})
9972@deftypemethodx {YYParser} {void} yyerror (Location @var{loc}, String @var{msg})
9973Print an error message using the @code{yyerror} method of the scanner
9974instance in use. The @code{Location} and @code{Position} parameters are
9975available only if location tracking is active.
9976@end deftypemethod
9977
01b477c6 9978@deftypemethod {YYParser} {boolean} recovering ()
8405b70c 9979During the syntactic analysis, return @code{true} if recovering
e254a580
DJ
9980from a syntax error.
9981@xref{Error Recovery}.
8405b70c
PB
9982@end deftypemethod
9983
9984@deftypemethod {YYParser} {java.io.PrintStream} getDebugStream ()
9985@deftypemethodx {YYParser} {void} setDebugStream (java.io.printStream @var{o})
9986Get or set the stream used for tracing the parsing. It defaults to
9987@code{System.err}.
9988@end deftypemethod
9989
9990@deftypemethod {YYParser} {int} getDebugLevel ()
9991@deftypemethodx {YYParser} {void} setDebugLevel (int @var{l})
9992Get or set the tracing level. Currently its value is either 0, no trace,
9993or nonzero, full tracing.
9994@end deftypemethod
9995
1979121c
DJ
9996@deftypecv {Constant} {YYParser} {String} {bisonVersion}
9997@deftypecvx {Constant} {YYParser} {String} {bisonSkeleton}
9998Identify the Bison version and skeleton used to generate this parser.
9999@end deftypecv
10000
8405b70c
PB
10001
10002@node Java Scanner Interface
10003@subsection Java Scanner Interface
01b477c6 10004@c - %code lexer
8405b70c 10005@c - %lex-param
01b477c6 10006@c - Lexer interface
8405b70c 10007
e254a580
DJ
10008There are two possible ways to interface a Bison-generated Java parser
10009with a scanner: the scanner may be defined by @code{%code lexer}, or
10010defined elsewhere. In either case, the scanner has to implement the
1979121c
DJ
10011@code{Lexer} inner interface of the parser class. This interface also
10012contain constants for all user-defined token names and the predefined
10013@code{EOF} token.
e254a580
DJ
10014
10015In the first case, the body of the scanner class is placed in
10016@code{%code lexer} blocks. If you want to pass parameters from the
10017parser constructor to the scanner constructor, specify them with
10018@code{%lex-param}; they are passed before @code{%parse-param}s to the
10019constructor.
01b477c6 10020
59c5ac72 10021In the second case, the scanner has to implement the @code{Lexer} interface,
01b477c6
PB
10022which is defined within the parser class (e.g., @code{YYParser.Lexer}).
10023The constructor of the parser object will then accept an object
10024implementing the interface; @code{%lex-param} is not used in this
10025case.
10026
10027In both cases, the scanner has to implement the following methods.
10028
e254a580
DJ
10029@deftypemethod {Lexer} {void} yyerror (Location @var{loc}, String @var{msg})
10030This method is defined by the user to emit an error message. The first
10031parameter is omitted if location tracking is not active. Its type can be
67501061 10032changed using @samp{%define location_type "@var{class-name}".}
8405b70c
PB
10033@end deftypemethod
10034
e254a580 10035@deftypemethod {Lexer} {int} yylex ()
8405b70c 10036Return the next token. Its type is the return value, its semantic
f50bfcd6 10037value and location are saved and returned by the their methods in the
e254a580
DJ
10038interface.
10039
67501061 10040Use @samp{%define lex_throws} to specify any uncaught exceptions.
e254a580 10041Default is @code{java.io.IOException}.
8405b70c
PB
10042@end deftypemethod
10043
10044@deftypemethod {Lexer} {Position} getStartPos ()
10045@deftypemethodx {Lexer} {Position} getEndPos ()
01b477c6
PB
10046Return respectively the first position of the last token that
10047@code{yylex} returned, and the first position beyond it. These
10048methods are not needed unless location tracking is active.
8405b70c 10049
67501061 10050The return type can be changed using @samp{%define position_type
8405b70c
PB
10051"@var{class-name}".}
10052@end deftypemethod
10053
10054@deftypemethod {Lexer} {Object} getLVal ()
f50bfcd6 10055Return the semantic value of the last token that yylex returned.
8405b70c 10056
67501061 10057The return type can be changed using @samp{%define stype
8405b70c
PB
10058"@var{class-name}".}
10059@end deftypemethod
10060
10061
e254a580
DJ
10062@node Java Action Features
10063@subsection Special Features for Use in Java Actions
10064
10065The following special constructs can be uses in Java actions.
10066Other analogous C action features are currently unavailable for Java.
10067
67501061 10068Use @samp{%define throws} to specify any uncaught exceptions from parser
e254a580
DJ
10069actions, and initial actions specified by @code{%initial-action}.
10070
10071@defvar $@var{n}
10072The semantic value for the @var{n}th component of the current rule.
10073This may not be assigned to.
10074@xref{Java Semantic Values}.
10075@end defvar
10076
10077@defvar $<@var{typealt}>@var{n}
10078Like @code{$@var{n}} but specifies a alternative type @var{typealt}.
10079@xref{Java Semantic Values}.
10080@end defvar
10081
10082@defvar $$
10083The semantic value for the grouping made by the current rule. As a
10084value, this is in the base type (@code{Object} or as specified by
67501061 10085@samp{%define stype}) as in not cast to the declared subtype because
e254a580
DJ
10086casts are not allowed on the left-hand side of Java assignments.
10087Use an explicit Java cast if the correct subtype is needed.
10088@xref{Java Semantic Values}.
10089@end defvar
10090
10091@defvar $<@var{typealt}>$
10092Same as @code{$$} since Java always allow assigning to the base type.
10093Perhaps we should use this and @code{$<>$} for the value and @code{$$}
10094for setting the value but there is currently no easy way to distinguish
10095these constructs.
10096@xref{Java Semantic Values}.
10097@end defvar
10098
10099@defvar @@@var{n}
10100The location information of the @var{n}th component of the current rule.
10101This may not be assigned to.
10102@xref{Java Location Values}.
10103@end defvar
10104
10105@defvar @@$
10106The location information of the grouping made by the current rule.
10107@xref{Java Location Values}.
10108@end defvar
10109
10110@deffn {Statement} {return YYABORT;}
10111Return immediately from the parser, indicating failure.
10112@xref{Java Parser Interface}.
10113@end deffn
8405b70c 10114
e254a580
DJ
10115@deffn {Statement} {return YYACCEPT;}
10116Return immediately from the parser, indicating success.
10117@xref{Java Parser Interface}.
10118@end deffn
8405b70c 10119
e254a580 10120@deffn {Statement} {return YYERROR;}
c265fd6b 10121Start error recovery without printing an error message.
e254a580
DJ
10122@xref{Error Recovery}.
10123@end deffn
8405b70c 10124
e254a580
DJ
10125@deftypefn {Function} {boolean} recovering ()
10126Return whether error recovery is being done. In this state, the parser
10127reads token until it reaches a known state, and then restarts normal
10128operation.
10129@xref{Error Recovery}.
10130@end deftypefn
8405b70c 10131
1979121c
DJ
10132@deftypefn {Function} {void} yyerror (String @var{msg})
10133@deftypefnx {Function} {void} yyerror (Position @var{loc}, String @var{msg})
10134@deftypefnx {Function} {void} yyerror (Location @var{loc}, String @var{msg})
e254a580 10135Print an error message using the @code{yyerror} method of the scanner
1979121c
DJ
10136instance in use. The @code{Location} and @code{Position} parameters are
10137available only if location tracking is active.
e254a580 10138@end deftypefn
8405b70c 10139
8405b70c 10140
8405b70c
PB
10141@node Java Differences
10142@subsection Differences between C/C++ and Java Grammars
10143
10144The different structure of the Java language forces several differences
10145between C/C++ grammars, and grammars designed for Java parsers. This
29553547 10146section summarizes these differences.
8405b70c
PB
10147
10148@itemize
10149@item
01b477c6 10150Java lacks a preprocessor, so the @code{YYERROR}, @code{YYACCEPT},
8405b70c 10151@code{YYABORT} symbols (@pxref{Table of Symbols}) cannot obviously be
01b477c6
PB
10152macros. Instead, they should be preceded by @code{return} when they
10153appear in an action. The actual definition of these symbols is
8405b70c
PB
10154opaque to the Bison grammar, and it might change in the future. The
10155only meaningful operation that you can do, is to return them.
e254a580 10156See @pxref{Java Action Features}.
8405b70c
PB
10157
10158Note that of these three symbols, only @code{YYACCEPT} and
10159@code{YYABORT} will cause a return from the @code{yyparse}
10160method@footnote{Java parsers include the actions in a separate
10161method than @code{yyparse} in order to have an intuitive syntax that
10162corresponds to these C macros.}.
10163
e254a580
DJ
10164@item
10165Java lacks unions, so @code{%union} has no effect. Instead, semantic
10166values have a common base type: @code{Object} or as specified by
f50bfcd6 10167@samp{%define stype}. Angle brackets on @code{%token}, @code{type},
e254a580
DJ
10168@code{$@var{n}} and @code{$$} specify subtypes rather than fields of
10169an union. The type of @code{$$}, even with angle brackets, is the base
10170type since Java casts are not allow on the left-hand side of assignments.
10171Also, @code{$@var{n}} and @code{@@@var{n}} are not allowed on the
10172left-hand side of assignments. See @pxref{Java Semantic Values} and
10173@pxref{Java Action Features}.
10174
8405b70c 10175@item
f50bfcd6 10176The prologue declarations have a different meaning than in C/C++ code.
01b477c6
PB
10177@table @asis
10178@item @code{%code imports}
10179blocks are placed at the beginning of the Java source code. They may
10180include copyright notices. For a @code{package} declarations, it is
67501061 10181suggested to use @samp{%define package} instead.
8405b70c 10182
01b477c6
PB
10183@item unqualified @code{%code}
10184blocks are placed inside the parser class.
10185
10186@item @code{%code lexer}
10187blocks, if specified, should include the implementation of the
10188scanner. If there is no such block, the scanner can be any class
10189that implements the appropriate interface (see @pxref{Java Scanner
10190Interface}).
29553547 10191@end table
8405b70c
PB
10192
10193Other @code{%code} blocks are not supported in Java parsers.
e254a580
DJ
10194In particular, @code{%@{ @dots{} %@}} blocks should not be used
10195and may give an error in future versions of Bison.
10196
01b477c6 10197The epilogue has the same meaning as in C/C++ code and it can
e254a580
DJ
10198be used to define other classes used by the parser @emph{outside}
10199the parser class.
8405b70c
PB
10200@end itemize
10201
e254a580
DJ
10202
10203@node Java Declarations Summary
10204@subsection Java Declarations Summary
10205
10206This summary only include declarations specific to Java or have special
10207meaning when used in a Java parser.
10208
10209@deffn {Directive} {%language "Java"}
10210Generate a Java class for the parser.
10211@end deffn
10212
10213@deffn {Directive} %lex-param @{@var{type} @var{name}@}
10214A parameter for the lexer class defined by @code{%code lexer}
10215@emph{only}, added as parameters to the lexer constructor and the parser
10216constructor that @emph{creates} a lexer. Default is none.
10217@xref{Java Scanner Interface}.
10218@end deffn
10219
10220@deffn {Directive} %name-prefix "@var{prefix}"
10221The prefix of the parser class name @code{@var{prefix}Parser} if
67501061 10222@samp{%define parser_class_name} is not used. Default is @code{YY}.
e254a580
DJ
10223@xref{Java Bison Interface}.
10224@end deffn
10225
10226@deffn {Directive} %parse-param @{@var{type} @var{name}@}
10227A parameter for the parser class added as parameters to constructor(s)
10228and as fields initialized by the constructor(s). Default is none.
10229@xref{Java Parser Interface}.
10230@end deffn
10231
10232@deffn {Directive} %token <@var{type}> @var{token} @dots{}
10233Declare tokens. Note that the angle brackets enclose a Java @emph{type}.
10234@xref{Java Semantic Values}.
10235@end deffn
10236
10237@deffn {Directive} %type <@var{type}> @var{nonterminal} @dots{}
10238Declare the type of nonterminals. Note that the angle brackets enclose
10239a Java @emph{type}.
10240@xref{Java Semantic Values}.
10241@end deffn
10242
10243@deffn {Directive} %code @{ @var{code} @dots{} @}
10244Code appended to the inside of the parser class.
10245@xref{Java Differences}.
10246@end deffn
10247
10248@deffn {Directive} {%code imports} @{ @var{code} @dots{} @}
10249Code inserted just after the @code{package} declaration.
10250@xref{Java Differences}.
10251@end deffn
10252
1979121c
DJ
10253@deffn {Directive} {%code init} @{ @var{code} @dots{} @}
10254Code inserted at the beginning of the parser constructor body.
10255@xref{Java Parser Interface}.
10256@end deffn
10257
e254a580
DJ
10258@deffn {Directive} {%code lexer} @{ @var{code} @dots{} @}
10259Code added to the body of a inner lexer class within the parser class.
10260@xref{Java Scanner Interface}.
10261@end deffn
10262
10263@deffn {Directive} %% @var{code} @dots{}
10264Code (after the second @code{%%}) appended to the end of the file,
10265@emph{outside} the parser class.
10266@xref{Java Differences}.
10267@end deffn
10268
10269@deffn {Directive} %@{ @var{code} @dots{} %@}
1979121c 10270Not supported. Use @code{%code imports} instead.
e254a580
DJ
10271@xref{Java Differences}.
10272@end deffn
10273
10274@deffn {Directive} {%define abstract}
10275Whether the parser class is declared @code{abstract}. Default is false.
10276@xref{Java Bison Interface}.
10277@end deffn
10278
1979121c
DJ
10279@deffn {Directive} {%define annotations} "@var{annotations}"
10280The Java annotations for the parser class. Default is none.
10281@xref{Java Bison Interface}.
10282@end deffn
10283
e254a580
DJ
10284@deffn {Directive} {%define extends} "@var{superclass}"
10285The superclass of the parser class. Default is none.
10286@xref{Java Bison Interface}.
10287@end deffn
10288
10289@deffn {Directive} {%define final}
10290Whether the parser class is declared @code{final}. Default is false.
10291@xref{Java Bison Interface}.
10292@end deffn
10293
10294@deffn {Directive} {%define implements} "@var{interfaces}"
10295The implemented interfaces of the parser class, a comma-separated list.
10296Default is none.
10297@xref{Java Bison Interface}.
10298@end deffn
10299
1979121c
DJ
10300@deffn {Directive} {%define init_throws} "@var{exceptions}"
10301The exceptions thrown by @code{%code init} from the parser class
10302constructor. Default is none.
10303@xref{Java Parser Interface}.
10304@end deffn
10305
e254a580
DJ
10306@deffn {Directive} {%define lex_throws} "@var{exceptions}"
10307The exceptions thrown by the @code{yylex} method of the lexer, a
10308comma-separated list. Default is @code{java.io.IOException}.
10309@xref{Java Scanner Interface}.
10310@end deffn
10311
10312@deffn {Directive} {%define location_type} "@var{class}"
10313The name of the class used for locations (a range between two
10314positions). This class is generated as an inner class of the parser
10315class by @command{bison}. Default is @code{Location}.
10316@xref{Java Location Values}.
10317@end deffn
10318
10319@deffn {Directive} {%define package} "@var{package}"
10320The package to put the parser class in. Default is none.
10321@xref{Java Bison Interface}.
10322@end deffn
10323
10324@deffn {Directive} {%define parser_class_name} "@var{name}"
10325The name of the parser class. Default is @code{YYParser} or
10326@code{@var{name-prefix}Parser}.
10327@xref{Java Bison Interface}.
10328@end deffn
10329
10330@deffn {Directive} {%define position_type} "@var{class}"
10331The name of the class used for positions. This class must be supplied by
10332the user. Default is @code{Position}.
10333@xref{Java Location Values}.
10334@end deffn
10335
10336@deffn {Directive} {%define public}
10337Whether the parser class is declared @code{public}. Default is false.
10338@xref{Java Bison Interface}.
10339@end deffn
10340
10341@deffn {Directive} {%define stype} "@var{class}"
10342The base type of semantic values. Default is @code{Object}.
10343@xref{Java Semantic Values}.
10344@end deffn
10345
10346@deffn {Directive} {%define strictfp}
10347Whether the parser class is declared @code{strictfp}. Default is false.
10348@xref{Java Bison Interface}.
10349@end deffn
10350
10351@deffn {Directive} {%define throws} "@var{exceptions}"
10352The exceptions thrown by user-supplied parser actions and
10353@code{%initial-action}, a comma-separated list. Default is none.
10354@xref{Java Parser Interface}.
10355@end deffn
10356
10357
12545799 10358@c ================================================= FAQ
d1a1114f
AD
10359
10360@node FAQ
10361@chapter Frequently Asked Questions
10362@cindex frequently asked questions
10363@cindex questions
10364
10365Several questions about Bison come up occasionally. Here some of them
10366are addressed.
10367
10368@menu
55ba27be
AD
10369* Memory Exhausted:: Breaking the Stack Limits
10370* How Can I Reset the Parser:: @code{yyparse} Keeps some State
10371* Strings are Destroyed:: @code{yylval} Loses Track of Strings
10372* Implementing Gotos/Loops:: Control Flow in the Calculator
ed2e6384 10373* Multiple start-symbols:: Factoring closely related grammars
8a4281b9 10374* Secure? Conform?:: Is Bison POSIX safe?
55ba27be
AD
10375* I can't build Bison:: Troubleshooting
10376* Where can I find help?:: Troubleshouting
10377* Bug Reports:: Troublereporting
8405b70c 10378* More Languages:: Parsers in C++, Java, and so on
55ba27be
AD
10379* Beta Testing:: Experimenting development versions
10380* Mailing Lists:: Meeting other Bison users
d1a1114f
AD
10381@end menu
10382
1a059451
PE
10383@node Memory Exhausted
10384@section Memory Exhausted
d1a1114f
AD
10385
10386@display
1a059451 10387My parser returns with error with a @samp{memory exhausted}
d1a1114f
AD
10388message. What can I do?
10389@end display
10390
10391This question is already addressed elsewhere, @xref{Recursion,
10392,Recursive Rules}.
10393
e64fec0a
PE
10394@node How Can I Reset the Parser
10395@section How Can I Reset the Parser
5b066063 10396
0e14ad77
PE
10397The following phenomenon has several symptoms, resulting in the
10398following typical questions:
5b066063
AD
10399
10400@display
10401I invoke @code{yyparse} several times, and on correct input it works
10402properly; but when a parse error is found, all the other calls fail
0e14ad77 10403too. How can I reset the error flag of @code{yyparse}?
5b066063
AD
10404@end display
10405
10406@noindent
10407or
10408
10409@display
0e14ad77 10410My parser includes support for an @samp{#include}-like feature, in
5b066063 10411which case I run @code{yyparse} from @code{yyparse}. This fails
67501061 10412although I did specify @samp{%define api.pure}.
5b066063
AD
10413@end display
10414
0e14ad77
PE
10415These problems typically come not from Bison itself, but from
10416Lex-generated scanners. Because these scanners use large buffers for
5b066063
AD
10417speed, they might not notice a change of input file. As a
10418demonstration, consider the following source file,
10419@file{first-line.l}:
10420
10421@verbatim
10422%{
10423#include <stdio.h>
10424#include <stdlib.h>
10425%}
10426%%
10427.*\n ECHO; return 1;
10428%%
10429int
0e14ad77 10430yyparse (char const *file)
5b066063
AD
10431{
10432 yyin = fopen (file, "r");
10433 if (!yyin)
10434 exit (2);
fa7e68c3 10435 /* One token only. */
5b066063 10436 yylex ();
0e14ad77 10437 if (fclose (yyin) != 0)
5b066063
AD
10438 exit (3);
10439 return 0;
10440}
10441
10442int
0e14ad77 10443main (void)
5b066063
AD
10444{
10445 yyparse ("input");
10446 yyparse ("input");
10447 return 0;
10448}
10449@end verbatim
10450
10451@noindent
10452If the file @file{input} contains
10453
10454@verbatim
10455input:1: Hello,
10456input:2: World!
10457@end verbatim
10458
10459@noindent
0e14ad77 10460then instead of getting the first line twice, you get:
5b066063
AD
10461
10462@example
10463$ @kbd{flex -ofirst-line.c first-line.l}
10464$ @kbd{gcc -ofirst-line first-line.c -ll}
10465$ @kbd{./first-line}
10466input:1: Hello,
10467input:2: World!
10468@end example
10469
0e14ad77
PE
10470Therefore, whenever you change @code{yyin}, you must tell the
10471Lex-generated scanner to discard its current buffer and switch to the
10472new one. This depends upon your implementation of Lex; see its
10473documentation for more. For Flex, it suffices to call
10474@samp{YY_FLUSH_BUFFER} after each change to @code{yyin}. If your
10475Flex-generated scanner needs to read from several input streams to
10476handle features like include files, you might consider using Flex
10477functions like @samp{yy_switch_to_buffer} that manipulate multiple
10478input buffers.
5b066063 10479
b165c324
AD
10480If your Flex-generated scanner uses start conditions (@pxref{Start
10481conditions, , Start conditions, flex, The Flex Manual}), you might
10482also want to reset the scanner's state, i.e., go back to the initial
10483start condition, through a call to @samp{BEGIN (0)}.
10484
fef4cb51
AD
10485@node Strings are Destroyed
10486@section Strings are Destroyed
10487
10488@display
c7e441b4 10489My parser seems to destroy old strings, or maybe it loses track of
fef4cb51
AD
10490them. Instead of reporting @samp{"foo", "bar"}, it reports
10491@samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
10492@end display
10493
10494This error is probably the single most frequent ``bug report'' sent to
10495Bison lists, but is only concerned with a misunderstanding of the role
8c5b881d 10496of the scanner. Consider the following Lex code:
fef4cb51
AD
10497
10498@verbatim
10499%{
10500#include <stdio.h>
10501char *yylval = NULL;
10502%}
10503%%
10504.* yylval = yytext; return 1;
10505\n /* IGNORE */
10506%%
10507int
10508main ()
10509{
fa7e68c3 10510 /* Similar to using $1, $2 in a Bison action. */
fef4cb51
AD
10511 char *fst = (yylex (), yylval);
10512 char *snd = (yylex (), yylval);
10513 printf ("\"%s\", \"%s\"\n", fst, snd);
10514 return 0;
10515}
10516@end verbatim
10517
10518If you compile and run this code, you get:
10519
10520@example
10521$ @kbd{flex -osplit-lines.c split-lines.l}
10522$ @kbd{gcc -osplit-lines split-lines.c -ll}
10523$ @kbd{printf 'one\ntwo\n' | ./split-lines}
10524"one
10525two", "two"
10526@end example
10527
10528@noindent
10529this is because @code{yytext} is a buffer provided for @emph{reading}
10530in the action, but if you want to keep it, you have to duplicate it
10531(e.g., using @code{strdup}). Note that the output may depend on how
10532your implementation of Lex handles @code{yytext}. For instance, when
10533given the Lex compatibility option @option{-l} (which triggers the
10534option @samp{%array}) Flex generates a different behavior:
10535
10536@example
10537$ @kbd{flex -l -osplit-lines.c split-lines.l}
10538$ @kbd{gcc -osplit-lines split-lines.c -ll}
10539$ @kbd{printf 'one\ntwo\n' | ./split-lines}
10540"two", "two"
10541@end example
10542
10543
2fa09258
AD
10544@node Implementing Gotos/Loops
10545@section Implementing Gotos/Loops
a06ea4aa
AD
10546
10547@display
10548My simple calculator supports variables, assignments, and functions,
2fa09258 10549but how can I implement gotos, or loops?
a06ea4aa
AD
10550@end display
10551
10552Although very pedagogical, the examples included in the document blur
a1c84f45 10553the distinction to make between the parser---whose job is to recover
a06ea4aa 10554the structure of a text and to transmit it to subsequent modules of
a1c84f45 10555the program---and the processing (such as the execution) of this
a06ea4aa
AD
10556structure. This works well with so called straight line programs,
10557i.e., precisely those that have a straightforward execution model:
10558execute simple instructions one after the others.
10559
10560@cindex abstract syntax tree
8a4281b9 10561@cindex AST
a06ea4aa
AD
10562If you want a richer model, you will probably need to use the parser
10563to construct a tree that does represent the structure it has
10564recovered; this tree is usually called the @dfn{abstract syntax tree},
8a4281b9 10565or @dfn{AST} for short. Then, walking through this tree,
a06ea4aa
AD
10566traversing it in various ways, will enable treatments such as its
10567execution or its translation, which will result in an interpreter or a
10568compiler.
10569
10570This topic is way beyond the scope of this manual, and the reader is
10571invited to consult the dedicated literature.
10572
10573
ed2e6384
AD
10574@node Multiple start-symbols
10575@section Multiple start-symbols
10576
10577@display
10578I have several closely related grammars, and I would like to share their
10579implementations. In fact, I could use a single grammar but with
10580multiple entry points.
10581@end display
10582
10583Bison does not support multiple start-symbols, but there is a very
10584simple means to simulate them. If @code{foo} and @code{bar} are the two
10585pseudo start-symbols, then introduce two new tokens, say
10586@code{START_FOO} and @code{START_BAR}, and use them as switches from the
10587real start-symbol:
10588
10589@example
10590%token START_FOO START_BAR;
10591%start start;
10592start: START_FOO foo
10593 | START_BAR bar;
10594@end example
10595
10596These tokens prevents the introduction of new conflicts. As far as the
10597parser goes, that is all that is needed.
10598
10599Now the difficult part is ensuring that the scanner will send these
10600tokens first. If your scanner is hand-written, that should be
10601straightforward. If your scanner is generated by Lex, them there is
10602simple means to do it: recall that anything between @samp{%@{ ... %@}}
10603after the first @code{%%} is copied verbatim in the top of the generated
10604@code{yylex} function. Make sure a variable @code{start_token} is
10605available in the scanner (e.g., a global variable or using
10606@code{%lex-param} etc.), and use the following:
10607
10608@example
10609 /* @r{Prologue.} */
10610%%
10611%@{
10612 if (start_token)
10613 @{
10614 int t = start_token;
10615 start_token = 0;
10616 return t;
10617 @}
10618%@}
10619 /* @r{The rules.} */
10620@end example
10621
10622
55ba27be
AD
10623@node Secure? Conform?
10624@section Secure? Conform?
10625
10626@display
10627Is Bison secure? Does it conform to POSIX?
10628@end display
10629
10630If you're looking for a guarantee or certification, we don't provide it.
10631However, Bison is intended to be a reliable program that conforms to the
8a4281b9 10632POSIX specification for Yacc. If you run into problems,
55ba27be
AD
10633please send us a bug report.
10634
10635@node I can't build Bison
10636@section I can't build Bison
10637
10638@display
8c5b881d
PE
10639I can't build Bison because @command{make} complains that
10640@code{msgfmt} is not found.
55ba27be
AD
10641What should I do?
10642@end display
10643
10644Like most GNU packages with internationalization support, that feature
10645is turned on by default. If you have problems building in the @file{po}
10646subdirectory, it indicates that your system's internationalization
10647support is lacking. You can re-configure Bison with
10648@option{--disable-nls} to turn off this support, or you can install GNU
10649gettext from @url{ftp://ftp.gnu.org/gnu/gettext/} and re-configure
10650Bison. See the file @file{ABOUT-NLS} for more information.
10651
10652
10653@node Where can I find help?
10654@section Where can I find help?
10655
10656@display
10657I'm having trouble using Bison. Where can I find help?
10658@end display
10659
10660First, read this fine manual. Beyond that, you can send mail to
10661@email{help-bison@@gnu.org}. This mailing list is intended to be
10662populated with people who are willing to answer questions about using
10663and installing Bison. Please keep in mind that (most of) the people on
10664the list have aspects of their lives which are not related to Bison (!),
10665so you may not receive an answer to your question right away. This can
10666be frustrating, but please try not to honk them off; remember that any
10667help they provide is purely voluntary and out of the kindness of their
10668hearts.
10669
10670@node Bug Reports
10671@section Bug Reports
10672
10673@display
10674I found a bug. What should I include in the bug report?
10675@end display
10676
10677Before you send a bug report, make sure you are using the latest
10678version. Check @url{ftp://ftp.gnu.org/pub/gnu/bison/} or one of its
10679mirrors. Be sure to include the version number in your bug report. If
10680the bug is present in the latest version but not in a previous version,
10681try to determine the most recent version which did not contain the bug.
10682
10683If the bug is parser-related, you should include the smallest grammar
10684you can which demonstrates the bug. The grammar file should also be
10685complete (i.e., I should be able to run it through Bison without having
10686to edit or add anything). The smaller and simpler the grammar, the
10687easier it will be to fix the bug.
10688
10689Include information about your compilation environment, including your
10690operating system's name and version and your compiler's name and
10691version. If you have trouble compiling, you should also include a
10692transcript of the build session, starting with the invocation of
10693`configure'. Depending on the nature of the bug, you may be asked to
10694send additional files as well (such as `config.h' or `config.cache').
10695
10696Patches are most welcome, but not required. That is, do not hesitate to
10697send a bug report just because you can not provide a fix.
10698
10699Send bug reports to @email{bug-bison@@gnu.org}.
10700
8405b70c
PB
10701@node More Languages
10702@section More Languages
55ba27be
AD
10703
10704@display
8405b70c 10705Will Bison ever have C++ and Java support? How about @var{insert your
55ba27be
AD
10706favorite language here}?
10707@end display
10708
8405b70c 10709C++ and Java support is there now, and is documented. We'd love to add other
55ba27be
AD
10710languages; contributions are welcome.
10711
10712@node Beta Testing
10713@section Beta Testing
10714
10715@display
10716What is involved in being a beta tester?
10717@end display
10718
10719It's not terribly involved. Basically, you would download a test
10720release, compile it, and use it to build and run a parser or two. After
10721that, you would submit either a bug report or a message saying that
10722everything is okay. It is important to report successes as well as
10723failures because test releases eventually become mainstream releases,
10724but only if they are adequately tested. If no one tests, development is
10725essentially halted.
10726
10727Beta testers are particularly needed for operating systems to which the
10728developers do not have easy access. They currently have easy access to
10729recent GNU/Linux and Solaris versions. Reports about other operating
10730systems are especially welcome.
10731
10732@node Mailing Lists
10733@section Mailing Lists
10734
10735@display
10736How do I join the help-bison and bug-bison mailing lists?
10737@end display
10738
10739See @url{http://lists.gnu.org/}.
a06ea4aa 10740
d1a1114f
AD
10741@c ================================================= Table of Symbols
10742
342b8b6e 10743@node Table of Symbols
bfa74976
RS
10744@appendix Bison Symbols
10745@cindex Bison symbols, table of
10746@cindex symbols in Bison, table of
10747
18b519c0 10748@deffn {Variable} @@$
3ded9a63 10749In an action, the location of the left-hand side of the rule.
88bce5a2 10750@xref{Locations, , Locations Overview}.
18b519c0 10751@end deffn
3ded9a63 10752
18b519c0 10753@deffn {Variable} @@@var{n}
3ded9a63
AD
10754In an action, the location of the @var{n}-th symbol of the right-hand
10755side of the rule. @xref{Locations, , Locations Overview}.
18b519c0 10756@end deffn
3ded9a63 10757
d013372c
AR
10758@deffn {Variable} @@@var{name}
10759In an action, the location of a symbol addressed by name.
10760@xref{Locations, , Locations Overview}.
10761@end deffn
10762
10763@deffn {Variable} @@[@var{name}]
10764In an action, the location of a symbol addressed by name.
10765@xref{Locations, , Locations Overview}.
10766@end deffn
10767
18b519c0 10768@deffn {Variable} $$
3ded9a63
AD
10769In an action, the semantic value of the left-hand side of the rule.
10770@xref{Actions}.
18b519c0 10771@end deffn
3ded9a63 10772
18b519c0 10773@deffn {Variable} $@var{n}
3ded9a63
AD
10774In an action, the semantic value of the @var{n}-th symbol of the
10775right-hand side of the rule. @xref{Actions}.
18b519c0 10776@end deffn
3ded9a63 10777
d013372c
AR
10778@deffn {Variable} $@var{name}
10779In an action, the semantic value of a symbol addressed by name.
10780@xref{Actions}.
10781@end deffn
10782
10783@deffn {Variable} $[@var{name}]
10784In an action, the semantic value of a symbol addressed by name.
10785@xref{Actions}.
10786@end deffn
10787
dd8d9022
AD
10788@deffn {Delimiter} %%
10789Delimiter used to separate the grammar rule section from the
10790Bison declarations section or the epilogue.
10791@xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
18b519c0 10792@end deffn
bfa74976 10793
dd8d9022
AD
10794@c Don't insert spaces, or check the DVI output.
10795@deffn {Delimiter} %@{@var{code}%@}
ff7571c0
JD
10796All code listed between @samp{%@{} and @samp{%@}} is copied verbatim
10797to the parser implementation file. Such code forms the prologue of
10798the grammar file. @xref{Grammar Outline, ,Outline of a Bison
dd8d9022 10799Grammar}.
18b519c0 10800@end deffn
bfa74976 10801
ca2a6d15
PH
10802@deffn {Directive} %?@{@var{expression}@}
10803Predicate actions. This is a type of action clause that may appear in
10804rules. The expression is evaluated, and if false, causes a syntax error. In
8a4281b9 10805GLR parsers during nondeterministic operation,
ca2a6d15
PH
10806this silently causes an alternative parse to die. During deterministic
10807operation, it is the same as the effect of YYERROR.
10808@xref{Semantic Predicates}.
10809
10810This feature is experimental.
10811More user feedback will help to determine whether it should become a permanent
10812feature.
10813@end deffn
10814
dd8d9022
AD
10815@deffn {Construct} /*@dots{}*/
10816Comment delimiters, as in C.
18b519c0 10817@end deffn
bfa74976 10818
dd8d9022
AD
10819@deffn {Delimiter} :
10820Separates a rule's result from its components. @xref{Rules, ,Syntax of
10821Grammar Rules}.
18b519c0 10822@end deffn
bfa74976 10823
dd8d9022
AD
10824@deffn {Delimiter} ;
10825Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
18b519c0 10826@end deffn
bfa74976 10827
dd8d9022
AD
10828@deffn {Delimiter} |
10829Separates alternate rules for the same result nonterminal.
10830@xref{Rules, ,Syntax of Grammar Rules}.
18b519c0 10831@end deffn
bfa74976 10832
12e35840
JD
10833@deffn {Directive} <*>
10834Used to define a default tagged @code{%destructor} or default tagged
10835@code{%printer}.
85894313
JD
10836
10837This feature is experimental.
10838More user feedback will help to determine whether it should become a permanent
10839feature.
10840
12e35840
JD
10841@xref{Destructor Decl, , Freeing Discarded Symbols}.
10842@end deffn
10843
3ebecc24 10844@deffn {Directive} <>
12e35840
JD
10845Used to define a default tagless @code{%destructor} or default tagless
10846@code{%printer}.
85894313
JD
10847
10848This feature is experimental.
10849More user feedback will help to determine whether it should become a permanent
10850feature.
10851
12e35840
JD
10852@xref{Destructor Decl, , Freeing Discarded Symbols}.
10853@end deffn
10854
dd8d9022
AD
10855@deffn {Symbol} $accept
10856The predefined nonterminal whose only rule is @samp{$accept: @var{start}
10857$end}, where @var{start} is the start symbol. @xref{Start Decl, , The
10858Start-Symbol}. It cannot be used in the grammar.
18b519c0 10859@end deffn
bfa74976 10860
136a0f76 10861@deffn {Directive} %code @{@var{code}@}
148d66d8
JD
10862@deffnx {Directive} %code @var{qualifier} @{@var{code}@}
10863Insert @var{code} verbatim into output parser source.
10864@xref{Decl Summary,,%code}.
9bc0dd67
JD
10865@end deffn
10866
10867@deffn {Directive} %debug
10868Equip the parser for debugging. @xref{Decl Summary}.
10869@end deffn
10870
91d2c560 10871@ifset defaultprec
22fccf95
PE
10872@deffn {Directive} %default-prec
10873Assign a precedence to rules that lack an explicit @samp{%prec}
10874modifier. @xref{Contextual Precedence, ,Context-Dependent
10875Precedence}.
39a06c25 10876@end deffn
91d2c560 10877@end ifset
39a06c25 10878
148d66d8
JD
10879@deffn {Directive} %define @var{define-variable}
10880@deffnx {Directive} %define @var{define-variable} @var{value}
cf499cff 10881@deffnx {Directive} %define @var{define-variable} "@var{value}"
148d66d8
JD
10882Define a variable to adjust Bison's behavior.
10883@xref{Decl Summary,,%define}.
10884@end deffn
10885
18b519c0 10886@deffn {Directive} %defines
ff7571c0
JD
10887Bison declaration to create a parser header file, which is usually
10888meant for the scanner. @xref{Decl Summary}.
18b519c0 10889@end deffn
6deb4447 10890
02975b9a
JD
10891@deffn {Directive} %defines @var{defines-file}
10892Same as above, but save in the file @var{defines-file}.
10893@xref{Decl Summary}.
10894@end deffn
10895
18b519c0 10896@deffn {Directive} %destructor
258b75ca 10897Specify how the parser should reclaim the memory associated to
fa7e68c3 10898discarded symbols. @xref{Destructor Decl, , Freeing Discarded Symbols}.
18b519c0 10899@end deffn
72f889cc 10900
18b519c0 10901@deffn {Directive} %dprec
676385e2 10902Bison declaration to assign a precedence to a rule that is used at parse
c827f760 10903time to resolve reduce/reduce conflicts. @xref{GLR Parsers, ,Writing
8a4281b9 10904GLR Parsers}.
18b519c0 10905@end deffn
676385e2 10906
dd8d9022
AD
10907@deffn {Symbol} $end
10908The predefined token marking the end of the token stream. It cannot be
10909used in the grammar.
10910@end deffn
10911
10912@deffn {Symbol} error
10913A token name reserved for error recovery. This token may be used in
10914grammar rules so as to allow the Bison parser to recognize an error in
10915the grammar without halting the process. In effect, a sentence
10916containing an error may be recognized as valid. On a syntax error, the
742e4900
JD
10917token @code{error} becomes the current lookahead token. Actions
10918corresponding to @code{error} are then executed, and the lookahead
dd8d9022
AD
10919token is reset to the token that originally caused the violation.
10920@xref{Error Recovery}.
18d192f0
AD
10921@end deffn
10922
18b519c0 10923@deffn {Directive} %error-verbose
cf499cff 10924An obsolete directive standing for @samp{%define parse.error verbose}.
18b519c0 10925@end deffn
2a8d363a 10926
02975b9a 10927@deffn {Directive} %file-prefix "@var{prefix}"
72d2299c 10928Bison declaration to set the prefix of the output files. @xref{Decl
d8988b2f 10929Summary}.
18b519c0 10930@end deffn
d8988b2f 10931
18b519c0 10932@deffn {Directive} %glr-parser
8a4281b9
JD
10933Bison declaration to produce a GLR parser. @xref{GLR
10934Parsers, ,Writing GLR Parsers}.
18b519c0 10935@end deffn
676385e2 10936
dd8d9022
AD
10937@deffn {Directive} %initial-action
10938Run user code before parsing. @xref{Initial Action Decl, , Performing Actions before Parsing}.
10939@end deffn
10940
e6e704dc
JD
10941@deffn {Directive} %language
10942Specify the programming language for the generated parser.
10943@xref{Decl Summary}.
10944@end deffn
10945
18b519c0 10946@deffn {Directive} %left
d78f0ac9 10947Bison declaration to assign precedence and left associativity to token(s).
bfa74976 10948@xref{Precedence Decl, ,Operator Precedence}.
18b519c0 10949@end deffn
bfa74976 10950
2055a44e
AD
10951@deffn {Directive} %lex-param @{@var{argument-declaration}@} @dots{}
10952Bison declaration to specifying additional arguments that
2a8d363a
AD
10953@code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
10954for Pure Parsers}.
18b519c0 10955@end deffn
2a8d363a 10956
18b519c0 10957@deffn {Directive} %merge
676385e2 10958Bison declaration to assign a merging function to a rule. If there is a
fae437e8 10959reduce/reduce conflict with a rule having the same merging function, the
676385e2 10960function is applied to the two semantic values to get a single result.
8a4281b9 10961@xref{GLR Parsers, ,Writing GLR Parsers}.
18b519c0 10962@end deffn
676385e2 10963
02975b9a 10964@deffn {Directive} %name-prefix "@var{prefix}"
72d2299c 10965Bison declaration to rename the external symbols. @xref{Decl Summary}.
18b519c0 10966@end deffn
d8988b2f 10967
91d2c560 10968@ifset defaultprec
22fccf95
PE
10969@deffn {Directive} %no-default-prec
10970Do not assign a precedence to rules that lack an explicit @samp{%prec}
10971modifier. @xref{Contextual Precedence, ,Context-Dependent
10972Precedence}.
10973@end deffn
91d2c560 10974@end ifset
22fccf95 10975
18b519c0 10976@deffn {Directive} %no-lines
931c7513 10977Bison declaration to avoid generating @code{#line} directives in the
ff7571c0 10978parser implementation file. @xref{Decl Summary}.
18b519c0 10979@end deffn
931c7513 10980
18b519c0 10981@deffn {Directive} %nonassoc
d78f0ac9 10982Bison declaration to assign precedence and nonassociativity to token(s).
bfa74976 10983@xref{Precedence Decl, ,Operator Precedence}.
18b519c0 10984@end deffn
bfa74976 10985
02975b9a 10986@deffn {Directive} %output "@var{file}"
ff7571c0
JD
10987Bison declaration to set the name of the parser implementation file.
10988@xref{Decl Summary}.
18b519c0 10989@end deffn
d8988b2f 10990
2055a44e
AD
10991@deffn {Directive} %param @{@var{argument-declaration}@} @dots{}
10992Bison declaration to specify additional arguments that both
10993@code{yylex} and @code{yyparse} should accept. @xref{Parser Function,, The
10994Parser Function @code{yyparse}}.
10995@end deffn
10996
10997@deffn {Directive} %parse-param @{@var{argument-declaration}@} @dots{}
10998Bison declaration to specify additional arguments that @code{yyparse}
10999should accept. @xref{Parser Function,, The Parser Function @code{yyparse}}.
18b519c0 11000@end deffn
2a8d363a 11001
18b519c0 11002@deffn {Directive} %prec
bfa74976
RS
11003Bison declaration to assign a precedence to a specific rule.
11004@xref{Contextual Precedence, ,Context-Dependent Precedence}.
18b519c0 11005@end deffn
bfa74976 11006
d78f0ac9
AD
11007@deffn {Directive} %precedence
11008Bison declaration to assign precedence to token(s), but no associativity
11009@xref{Precedence Decl, ,Operator Precedence}.
11010@end deffn
11011
18b519c0 11012@deffn {Directive} %pure-parser
67501061 11013Deprecated version of @samp{%define api.pure} (@pxref{Decl Summary, ,%define}),
d9df47b6 11014for which Bison is more careful to warn about unreasonable usage.
18b519c0 11015@end deffn
bfa74976 11016
b50d2359 11017@deffn {Directive} %require "@var{version}"
9b8a5ce0
AD
11018Require version @var{version} or higher of Bison. @xref{Require Decl, ,
11019Require a Version of Bison}.
b50d2359
AD
11020@end deffn
11021
18b519c0 11022@deffn {Directive} %right
d78f0ac9 11023Bison declaration to assign precedence and right associativity to token(s).
bfa74976 11024@xref{Precedence Decl, ,Operator Precedence}.
18b519c0 11025@end deffn
bfa74976 11026
e6e704dc
JD
11027@deffn {Directive} %skeleton
11028Specify the skeleton to use; usually for development.
11029@xref{Decl Summary}.
11030@end deffn
11031
18b519c0 11032@deffn {Directive} %start
704a47c4
AD
11033Bison declaration to specify the start symbol. @xref{Start Decl, ,The
11034Start-Symbol}.
18b519c0 11035@end deffn
bfa74976 11036
18b519c0 11037@deffn {Directive} %token
bfa74976
RS
11038Bison declaration to declare token(s) without specifying precedence.
11039@xref{Token Decl, ,Token Type Names}.
18b519c0 11040@end deffn
bfa74976 11041
18b519c0 11042@deffn {Directive} %token-table
ff7571c0
JD
11043Bison declaration to include a token name table in the parser
11044implementation file. @xref{Decl Summary}.
18b519c0 11045@end deffn
931c7513 11046
18b519c0 11047@deffn {Directive} %type
704a47c4
AD
11048Bison declaration to declare nonterminals. @xref{Type Decl,
11049,Nonterminal Symbols}.
18b519c0 11050@end deffn
bfa74976 11051
dd8d9022
AD
11052@deffn {Symbol} $undefined
11053The predefined token onto which all undefined values returned by
11054@code{yylex} are mapped. It cannot be used in the grammar, rather, use
11055@code{error}.
11056@end deffn
11057
18b519c0 11058@deffn {Directive} %union
bfa74976
RS
11059Bison declaration to specify several possible data types for semantic
11060values. @xref{Union Decl, ,The Collection of Value Types}.
18b519c0 11061@end deffn
bfa74976 11062
dd8d9022
AD
11063@deffn {Macro} YYABORT
11064Macro to pretend that an unrecoverable syntax error has occurred, by
11065making @code{yyparse} return 1 immediately. The error reporting
11066function @code{yyerror} is not called. @xref{Parser Function, ,The
11067Parser Function @code{yyparse}}.
8405b70c
PB
11068
11069For Java parsers, this functionality is invoked using @code{return YYABORT;}
11070instead.
dd8d9022 11071@end deffn
3ded9a63 11072
dd8d9022
AD
11073@deffn {Macro} YYACCEPT
11074Macro to pretend that a complete utterance of the language has been
11075read, by making @code{yyparse} return 0 immediately.
11076@xref{Parser Function, ,The Parser Function @code{yyparse}}.
8405b70c
PB
11077
11078For Java parsers, this functionality is invoked using @code{return YYACCEPT;}
11079instead.
dd8d9022 11080@end deffn
bfa74976 11081
dd8d9022 11082@deffn {Macro} YYBACKUP
742e4900 11083Macro to discard a value from the parser stack and fake a lookahead
dd8d9022 11084token. @xref{Action Features, ,Special Features for Use in Actions}.
18b519c0 11085@end deffn
bfa74976 11086
dd8d9022 11087@deffn {Variable} yychar
32c29292 11088External integer variable that contains the integer value of the
742e4900 11089lookahead token. (In a pure parser, it is a local variable within
dd8d9022
AD
11090@code{yyparse}.) Error-recovery rule actions may examine this variable.
11091@xref{Action Features, ,Special Features for Use in Actions}.
18b519c0 11092@end deffn
bfa74976 11093
dd8d9022
AD
11094@deffn {Variable} yyclearin
11095Macro used in error-recovery rule actions. It clears the previous
742e4900 11096lookahead token. @xref{Error Recovery}.
18b519c0 11097@end deffn
bfa74976 11098
dd8d9022
AD
11099@deffn {Macro} YYDEBUG
11100Macro to define to equip the parser with tracing code. @xref{Tracing,
11101,Tracing Your Parser}.
18b519c0 11102@end deffn
bfa74976 11103
dd8d9022
AD
11104@deffn {Variable} yydebug
11105External integer variable set to zero by default. If @code{yydebug}
11106is given a nonzero value, the parser will output information on input
11107symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
18b519c0 11108@end deffn
bfa74976 11109
dd8d9022
AD
11110@deffn {Macro} yyerrok
11111Macro to cause parser to recover immediately to its normal mode
11112after a syntax error. @xref{Error Recovery}.
11113@end deffn
11114
11115@deffn {Macro} YYERROR
11116Macro to pretend that a syntax error has just been detected: call
11117@code{yyerror} and then perform normal error recovery if possible
11118(@pxref{Error Recovery}), or (if recovery is impossible) make
11119@code{yyparse} return 1. @xref{Error Recovery}.
8405b70c
PB
11120
11121For Java parsers, this functionality is invoked using @code{return YYERROR;}
11122instead.
dd8d9022
AD
11123@end deffn
11124
11125@deffn {Function} yyerror
11126User-supplied function to be called by @code{yyparse} on error.
71b00ed8 11127@xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
dd8d9022
AD
11128@end deffn
11129
11130@deffn {Macro} YYERROR_VERBOSE
71b00ed8
AD
11131An obsolete macro used in the @file{yacc.c} skeleton, that you define
11132with @code{#define} in the prologue to request verbose, specific error
11133message strings when @code{yyerror} is called. It doesn't matter what
11134definition you use for @code{YYERROR_VERBOSE}, just whether you define
cf499cff 11135it. Using @samp{%define parse.error verbose} is preferred
31b850d2 11136(@pxref{Error Reporting, ,The Error Reporting Function @code{yyerror}}).
dd8d9022
AD
11137@end deffn
11138
11139@deffn {Macro} YYINITDEPTH
11140Macro for specifying the initial size of the parser stack.
1a059451 11141@xref{Memory Management}.
dd8d9022
AD
11142@end deffn
11143
11144@deffn {Function} yylex
11145User-supplied lexical analyzer function, called with no arguments to get
11146the next token. @xref{Lexical, ,The Lexical Analyzer Function
11147@code{yylex}}.
11148@end deffn
11149
11150@deffn {Macro} YYLEX_PARAM
11151An obsolete macro for specifying an extra argument (or list of extra
32c29292 11152arguments) for @code{yyparse} to pass to @code{yylex}. The use of this
dd8d9022
AD
11153macro is deprecated, and is supported only for Yacc like parsers.
11154@xref{Pure Calling,, Calling Conventions for Pure Parsers}.
11155@end deffn
11156
11157@deffn {Variable} yylloc
11158External variable in which @code{yylex} should place the line and column
11159numbers associated with a token. (In a pure parser, it is a local
11160variable within @code{yyparse}, and its address is passed to
32c29292
JD
11161@code{yylex}.)
11162You can ignore this variable if you don't use the @samp{@@} feature in the
11163grammar actions.
11164@xref{Token Locations, ,Textual Locations of Tokens}.
742e4900 11165In semantic actions, it stores the location of the lookahead token.
32c29292 11166@xref{Actions and Locations, ,Actions and Locations}.
dd8d9022
AD
11167@end deffn
11168
11169@deffn {Type} YYLTYPE
11170Data type of @code{yylloc}; by default, a structure with four
11171members. @xref{Location Type, , Data Types of Locations}.
11172@end deffn
11173
11174@deffn {Variable} yylval
11175External variable in which @code{yylex} should place the semantic
11176value associated with a token. (In a pure parser, it is a local
11177variable within @code{yyparse}, and its address is passed to
32c29292
JD
11178@code{yylex}.)
11179@xref{Token Values, ,Semantic Values of Tokens}.
742e4900 11180In semantic actions, it stores the semantic value of the lookahead token.
32c29292 11181@xref{Actions, ,Actions}.
dd8d9022
AD
11182@end deffn
11183
11184@deffn {Macro} YYMAXDEPTH
1a059451
PE
11185Macro for specifying the maximum size of the parser stack. @xref{Memory
11186Management}.
dd8d9022
AD
11187@end deffn
11188
11189@deffn {Variable} yynerrs
8a2800e7 11190Global variable which Bison increments each time it reports a syntax error.
f4101aa6 11191(In a pure parser, it is a local variable within @code{yyparse}. In a
9987d1b3 11192pure push parser, it is a member of yypstate.)
dd8d9022
AD
11193@xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
11194@end deffn
11195
11196@deffn {Function} yyparse
11197The parser function produced by Bison; call this function to start
11198parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
11199@end deffn
11200
9987d1b3 11201@deffn {Function} yypstate_delete
f4101aa6 11202The function to delete a parser instance, produced by Bison in push mode;
9987d1b3 11203call this function to delete the memory associated with a parser.
f4101aa6 11204@xref{Parser Delete Function, ,The Parser Delete Function
9987d1b3 11205@code{yypstate_delete}}.
59da312b
JD
11206(The current push parsing interface is experimental and may evolve.
11207More user feedback will help to stabilize it.)
9987d1b3
JD
11208@end deffn
11209
11210@deffn {Function} yypstate_new
f4101aa6 11211The function to create a parser instance, produced by Bison in push mode;
9987d1b3 11212call this function to create a new parser.
f4101aa6 11213@xref{Parser Create Function, ,The Parser Create Function
9987d1b3 11214@code{yypstate_new}}.
59da312b
JD
11215(The current push parsing interface is experimental and may evolve.
11216More user feedback will help to stabilize it.)
9987d1b3
JD
11217@end deffn
11218
11219@deffn {Function} yypull_parse
f4101aa6
AD
11220The parser function produced by Bison in push mode; call this function to
11221parse the rest of the input stream.
11222@xref{Pull Parser Function, ,The Pull Parser Function
9987d1b3 11223@code{yypull_parse}}.
59da312b
JD
11224(The current push parsing interface is experimental and may evolve.
11225More user feedback will help to stabilize it.)
9987d1b3
JD
11226@end deffn
11227
11228@deffn {Function} yypush_parse
f4101aa6
AD
11229The parser function produced by Bison in push mode; call this function to
11230parse a single token. @xref{Push Parser Function, ,The Push Parser Function
9987d1b3 11231@code{yypush_parse}}.
59da312b
JD
11232(The current push parsing interface is experimental and may evolve.
11233More user feedback will help to stabilize it.)
9987d1b3
JD
11234@end deffn
11235
dd8d9022
AD
11236@deffn {Macro} YYPARSE_PARAM
11237An obsolete macro for specifying the name of a parameter that
11238@code{yyparse} should accept. The use of this macro is deprecated, and
11239is supported only for Yacc like parsers. @xref{Pure Calling,, Calling
11240Conventions for Pure Parsers}.
11241@end deffn
11242
11243@deffn {Macro} YYRECOVERING
02103984
PE
11244The expression @code{YYRECOVERING ()} yields 1 when the parser
11245is recovering from a syntax error, and 0 otherwise.
11246@xref{Action Features, ,Special Features for Use in Actions}.
dd8d9022
AD
11247@end deffn
11248
11249@deffn {Macro} YYSTACK_USE_ALLOCA
eb45ef3b
JD
11250Macro used to control the use of @code{alloca} when the
11251deterministic parser in C needs to extend its stacks. If defined to 0,
d7e14fc0
PE
11252the parser will use @code{malloc} to extend its stacks. If defined to
112531, the parser will use @code{alloca}. Values other than 0 and 1 are
11254reserved for future Bison extensions. If not defined,
11255@code{YYSTACK_USE_ALLOCA} defaults to 0.
11256
55289366 11257In the all-too-common case where your code may run on a host with a
d7e14fc0
PE
11258limited stack and with unreliable stack-overflow checking, you should
11259set @code{YYMAXDEPTH} to a value that cannot possibly result in
11260unchecked stack overflow on any of your target hosts when
11261@code{alloca} is called. You can inspect the code that Bison
11262generates in order to determine the proper numeric values. This will
11263require some expertise in low-level implementation details.
dd8d9022
AD
11264@end deffn
11265
11266@deffn {Type} YYSTYPE
11267Data type of semantic values; @code{int} by default.
11268@xref{Value Type, ,Data Types of Semantic Values}.
18b519c0 11269@end deffn
bfa74976 11270
342b8b6e 11271@node Glossary
bfa74976
RS
11272@appendix Glossary
11273@cindex glossary
11274
11275@table @asis
eb45ef3b
JD
11276@item Accepting State
11277A state whose only action is the accept action.
11278The accepting state is thus a consistent state.
11279@xref{Understanding,,}.
11280
8a4281b9 11281@item Backus-Naur Form (BNF; also called ``Backus Normal Form'')
c827f760
PE
11282Formal method of specifying context-free grammars originally proposed
11283by John Backus, and slightly improved by Peter Naur in his 1960-01-02
11284committee document contributing to what became the Algol 60 report.
11285@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
bfa74976 11286
eb45ef3b
JD
11287@item Consistent State
11288A state containing only one possible action.
5bab9d08 11289@xref{Decl Summary,,lr.default-reductions}.
eb45ef3b 11290
bfa74976
RS
11291@item Context-free grammars
11292Grammars specified as rules that can be applied regardless of context.
11293Thus, if there is a rule which says that an integer can be used as an
11294expression, integers are allowed @emph{anywhere} an expression is
89cab50d
AD
11295permitted. @xref{Language and Grammar, ,Languages and Context-Free
11296Grammars}.
bfa74976 11297
110ef36a
JD
11298@item Default Reduction
11299The reduction that a parser should perform if the current parser state
eb45ef3b 11300contains no other action for the lookahead token.
110ef36a
JD
11301In permitted parser states, Bison declares the reduction with the
11302largest lookahead set to be the default reduction and removes that
11303lookahead set.
5bab9d08 11304@xref{Decl Summary,,lr.default-reductions}.
eb45ef3b 11305
bfa74976
RS
11306@item Dynamic allocation
11307Allocation of memory that occurs during execution, rather than at
11308compile time or on entry to a function.
11309
11310@item Empty string
11311Analogous to the empty set in set theory, the empty string is a
11312character string of length zero.
11313
11314@item Finite-state stack machine
11315A ``machine'' that has discrete states in which it is said to exist at
11316each instant in time. As input to the machine is processed, the
11317machine moves from state to state as specified by the logic of the
11318machine. In the case of the parser, the input is the language being
11319parsed, and the states correspond to various stages in the grammar
c827f760 11320rules. @xref{Algorithm, ,The Bison Parser Algorithm}.
bfa74976 11321
8a4281b9 11322@item Generalized LR (GLR)
676385e2 11323A parsing algorithm that can handle all context-free grammars, including those
8a4281b9 11324that are not LR(1). It resolves situations that Bison's
eb45ef3b 11325deterministic parsing
676385e2
PH
11326algorithm cannot by effectively splitting off multiple parsers, trying all
11327possible parsers, and discarding those that fail in the light of additional
c827f760 11328right context. @xref{Generalized LR Parsing, ,Generalized
8a4281b9 11329LR Parsing}.
676385e2 11330
bfa74976
RS
11331@item Grouping
11332A language construct that is (in general) grammatically divisible;
c827f760 11333for example, `expression' or `declaration' in C@.
bfa74976
RS
11334@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11335
8a4281b9
JD
11336@item IELR(1)
11337A minimal LR(1) parser table generation algorithm.
11338That is, given any context-free grammar, IELR(1) generates
eb45ef3b 11339parser tables with the full language recognition power of canonical
8a4281b9
JD
11340LR(1) but with nearly the same number of parser states as
11341LALR(1).
eb45ef3b 11342This reduction in parser states is often an order of magnitude.
8a4281b9 11343More importantly, because canonical LR(1)'s extra parser
eb45ef3b 11344states may contain duplicate conflicts in the case of
8a4281b9
JD
11345non-LR(1) grammars, the number of conflicts for
11346IELR(1) is often an order of magnitude less as well.
eb45ef3b
JD
11347This can significantly reduce the complexity of developing of a grammar.
11348@xref{Decl Summary,,lr.type}.
11349
bfa74976
RS
11350@item Infix operator
11351An arithmetic operator that is placed between the operands on which it
11352performs some operation.
11353
11354@item Input stream
11355A continuous flow of data between devices or programs.
11356
8a4281b9 11357@item LAC (Lookahead Correction)
fcf834f9
JD
11358A parsing mechanism that fixes the problem of delayed syntax error
11359detection, which is caused by LR state merging, default reductions, and
11360the use of @code{%nonassoc}. Delayed syntax error detection results in
11361unexpected semantic actions, initiation of error recovery in the wrong
11362syntactic context, and an incorrect list of expected tokens in a verbose
11363syntax error message. @xref{Decl Summary,,parse.lac}.
11364
bfa74976
RS
11365@item Language construct
11366One of the typical usage schemas of the language. For example, one of
11367the constructs of the C language is the @code{if} statement.
11368@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
11369
11370@item Left associativity
11371Operators having left associativity are analyzed from left to right:
11372@samp{a+b+c} first computes @samp{a+b} and then combines with
11373@samp{c}. @xref{Precedence, ,Operator Precedence}.
11374
11375@item Left recursion
89cab50d
AD
11376A rule whose result symbol is also its first component symbol; for
11377example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
11378Rules}.
bfa74976
RS
11379
11380@item Left-to-right parsing
11381Parsing a sentence of a language by analyzing it token by token from
c827f760 11382left to right. @xref{Algorithm, ,The Bison Parser Algorithm}.
bfa74976
RS
11383
11384@item Lexical analyzer (scanner)
11385A function that reads an input stream and returns tokens one by one.
11386@xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
11387
11388@item Lexical tie-in
11389A flag, set by actions in the grammar rules, which alters the way
11390tokens are parsed. @xref{Lexical Tie-ins}.
11391
931c7513 11392@item Literal string token
14ded682 11393A token which consists of two or more fixed characters. @xref{Symbols}.
931c7513 11394
742e4900
JD
11395@item Lookahead token
11396A token already read but not yet shifted. @xref{Lookahead, ,Lookahead
89cab50d 11397Tokens}.
bfa74976 11398
8a4281b9 11399@item LALR(1)
bfa74976 11400The class of context-free grammars that Bison (like most other parser
8a4281b9 11401generators) can handle by default; a subset of LR(1).
eb45ef3b 11402@xref{Mystery Conflicts, ,Mysterious Reduce/Reduce Conflicts}.
bfa74976 11403
8a4281b9 11404@item LR(1)
bfa74976 11405The class of context-free grammars in which at most one token of
742e4900 11406lookahead is needed to disambiguate the parsing of any piece of input.
bfa74976
RS
11407
11408@item Nonterminal symbol
11409A grammar symbol standing for a grammatical construct that can
11410be expressed through rules in terms of smaller constructs; in other
11411words, a construct that is not a token. @xref{Symbols}.
11412
bfa74976
RS
11413@item Parser
11414A function that recognizes valid sentences of a language by analyzing
11415the syntax structure of a set of tokens passed to it from a lexical
11416analyzer.
11417
11418@item Postfix operator
11419An arithmetic operator that is placed after the operands upon which it
11420performs some operation.
11421
11422@item Reduction
11423Replacing a string of nonterminals and/or terminals with a single
89cab50d 11424nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
c827f760 11425Parser Algorithm}.
bfa74976
RS
11426
11427@item Reentrant
11428A reentrant subprogram is a subprogram which can be in invoked any
11429number of times in parallel, without interference between the various
11430invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
11431
11432@item Reverse polish notation
11433A language in which all operators are postfix operators.
11434
11435@item Right recursion
89cab50d
AD
11436A rule whose result symbol is also its last component symbol; for
11437example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
11438Rules}.
bfa74976
RS
11439
11440@item Semantics
11441In computer languages, the semantics are specified by the actions
11442taken for each instance of the language, i.e., the meaning of
11443each statement. @xref{Semantics, ,Defining Language Semantics}.
11444
11445@item Shift
11446A parser is said to shift when it makes the choice of analyzing
11447further input from the stream rather than reducing immediately some
c827f760 11448already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm}.
bfa74976
RS
11449
11450@item Single-character literal
11451A single character that is recognized and interpreted as is.
11452@xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
11453
11454@item Start symbol
11455The nonterminal symbol that stands for a complete valid utterance in
11456the language being parsed. The start symbol is usually listed as the
13863333 11457first nonterminal symbol in a language specification.
bfa74976
RS
11458@xref{Start Decl, ,The Start-Symbol}.
11459
11460@item Symbol table
11461A data structure where symbol names and associated data are stored
11462during parsing to allow for recognition and use of existing
11463information in repeated uses of a symbol. @xref{Multi-function Calc}.
11464
6e649e65
PE
11465@item Syntax error
11466An error encountered during parsing of an input stream due to invalid
11467syntax. @xref{Error Recovery}.
11468
bfa74976
RS
11469@item Token
11470A basic, grammatically indivisible unit of a language. The symbol
11471that describes a token in the grammar is a terminal symbol.
11472The input of the Bison parser is a stream of tokens which comes from
11473the lexical analyzer. @xref{Symbols}.
11474
11475@item Terminal symbol
89cab50d
AD
11476A grammar symbol that has no rules in the grammar and therefore is
11477grammatically indivisible. The piece of text it represents is a token.
11478@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
bfa74976
RS
11479@end table
11480
342b8b6e 11481@node Copying This Manual
f2b5126e 11482@appendix Copying This Manual
f2b5126e
PB
11483@include fdl.texi
11484
342b8b6e 11485@node Index
bfa74976
RS
11486@unnumbered Index
11487
11488@printindex cp
11489
bfa74976 11490@bye
a06ea4aa 11491
6b5a0de9
AD
11492@c LocalWords: texinfo setfilename settitle setchapternewpage finalout texi FSF
11493@c LocalWords: ifinfo smallbook shorttitlepage titlepage GPL FIXME iftex FSF's
11494@c LocalWords: akim fn cp syncodeindex vr tp synindex dircategory direntry Naur
11495@c LocalWords: ifset vskip pt filll insertcopying sp ISBN Etienne Suvasa Multi
11496@c LocalWords: ifnottex yyparse detailmenu GLR RPN Calc var Decls Rpcalc multi
11497@c LocalWords: rpcalc Lexer Expr ltcalc mfcalc yylex defaultprec Donnelly Gotos
11498@c LocalWords: yyerror pxref LR yylval cindex dfn LALR samp gpl BNF xref yypush
11499@c LocalWords: const int paren ifnotinfo AC noindent emph expr stmt findex lr
11500@c LocalWords: glr YYSTYPE TYPENAME prog dprec printf decl init stmtMerge POSIX
11501@c LocalWords: pre STDC GNUC endif yy YY alloca lf stddef stdlib YYDEBUG yypull
11502@c LocalWords: NUM exp subsubsection kbd Ctrl ctype EOF getchar isdigit nonfree
11503@c LocalWords: ungetc stdin scanf sc calc ulator ls lm cc NEG prec yyerrok rr
11504@c LocalWords: longjmp fprintf stderr yylloc YYLTYPE cos ln Stallman Destructor
11505@c LocalWords: smallexample symrec val tptr FNCT fnctptr func struct sym enum
11506@c LocalWords: fnct putsym getsym fname arith fncts atan ptr malloc sizeof Lex
11507@c LocalWords: strlen strcpy fctn strcmp isalpha symbuf realloc isalnum DOTDOT
11508@c LocalWords: ptypes itype YYPRINT trigraphs yytname expseq vindex dtype Unary
11509@c LocalWords: Rhs YYRHSLOC LE nonassoc op deffn typeless yynerrs nonterminal
11510@c LocalWords: yychar yydebug msg YYNTOKENS YYNNTS YYNRULES YYNSTATES reentrant
11511@c LocalWords: cparse clex deftypefun NE defmac YYACCEPT YYABORT param yypstate
11512@c LocalWords: strncmp intval tindex lvalp locp llocp typealt YYBACKUP subrange
11513@c LocalWords: YYEMPTY YYEOF YYRECOVERING yyclearin GE def UMINUS maybeword loc
11514@c LocalWords: Johnstone Shamsa Sadaf Hussain Tomita TR uref YYMAXDEPTH inline
11515@c LocalWords: YYINITDEPTH stmnts ref stmnt initdcl maybeasm notype Lookahead
11516@c LocalWords: hexflag STR exdent itemset asis DYYDEBUG YYFPRINTF args Autoconf
11517@c LocalWords: infile ypp yxx outfile itemx tex leaderfill Troubleshouting sqrt
11518@c LocalWords: hbox hss hfill tt ly yyin fopen fclose ofirst gcc ll lookahead
11519@c LocalWords: nbar yytext fst snd osplit ntwo strdup AST Troublereporting th
11520@c LocalWords: YYSTACK DVI fdl printindex IELR nondeterministic nonterminals ps
fcf834f9 11521@c LocalWords: subexpressions declarator nondeferred config libintl postfix LAC
6b5a0de9 11522@c LocalWords: preprocessor nonpositive unary nonnumeric typedef extern rhs
ff7571c0 11523@c LocalWords: yytokentype destructor multicharacter nonnull EBCDIC
6b5a0de9
AD
11524@c LocalWords: lvalue nonnegative XNUM CHR chr TAGLESS tagless stdout api TOK
11525@c LocalWords: destructors Reentrancy nonreentrant subgrammar nonassociative
11526@c LocalWords: deffnx namespace xml goto lalr ielr runtime lex yacc yyps env
11527@c LocalWords: yystate variadic Unshift NLS gettext po UTF Automake LOCALEDIR
11528@c LocalWords: YYENABLE bindtextdomain Makefile DEFS CPPFLAGS DBISON DeRemer
11529@c LocalWords: autoreconf Pennello multisets nondeterminism Generalised baz
11530@c LocalWords: redeclare automata Dparse localedir datadir XSLT midrule Wno
ff7571c0 11531@c LocalWords: Graphviz multitable headitem hh basename Doxygen fno
6b5a0de9
AD
11532@c LocalWords: doxygen ival sval deftypemethod deallocate pos deftypemethodx
11533@c LocalWords: Ctor defcv defcvx arg accessors arithmetics CPP ifndef CALCXX
11534@c LocalWords: lexer's calcxx bool LPAREN RPAREN deallocation cerrno climits
11535@c LocalWords: cstdlib Debian undef yywrap unput noyywrap nounput zA yyleng
11536@c LocalWords: errno strtol ERANGE str strerror iostream argc argv Javadoc
11537@c LocalWords: bytecode initializers superclass stype ASTNode autoboxing nls
11538@c LocalWords: toString deftypeivar deftypeivarx deftypeop YYParser strictfp
11539@c LocalWords: superclasses boolean getErrorVerbose setErrorVerbose deftypecv
11540@c LocalWords: getDebugStream setDebugStream getDebugLevel setDebugLevel url
11541@c LocalWords: bisonVersion deftypecvx bisonSkeleton getStartPos getEndPos
679e9935 11542@c LocalWords: getLVal defvar deftypefn deftypefnx gotos msgfmt Corbett
6b5a0de9 11543@c LocalWords: subdirectory Solaris nonassociativity
e944aaff
AD
11544
11545@c Local Variables:
11546@c ispell-dictionary: "american"
11547@c fill-column: 76
11548@c End: