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