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