]> git.saurik.com Git - bison.git/blame - doc/bison.texinfo
Playing with autoscan.
[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
bfa74976
RS
15@c Set following if you have the new `shorttitlepage' command
16@c @clear shorttitlepage-enabled
17@c @set shorttitlepage-enabled
18
19@c ISPELL CHECK: done, 14 Jan 1993 --bob
20
21@c Check COPYRIGHT dates. should be updated in the titlepage, ifinfo
22@c titlepage; should NOT be changed in the GPL. --mew
23
ec3bc396 24@c FIXME: I don't understand this `iftex'. Obsolete? --akim.
bfa74976
RS
25@iftex
26@syncodeindex fn cp
27@syncodeindex vr cp
28@syncodeindex tp cp
29@end iftex
30@ifinfo
31@synindex fn cp
32@synindex vr cp
33@synindex tp cp
34@end ifinfo
35@comment %**end of header
36
fae437e8 37@copying
bd773d73 38
fae437e8
AD
39This manual is for GNU Bison (version @value{VERSION}, @value{UPDATED}),
40the GNU parser generator.
41
42Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
431999, 2000, 2001, 2002 Free Software Foundation, Inc.
44
45@quotation
46Permission is granted to copy, distribute and/or modify this document
47under the terms of the GNU Free Documentation License, Version 1.1 or
48any later version published by the Free Software Foundation; with no
49Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
50and with the Back-Cover Texts as in (a) below. A copy of the
51license is included in the section entitled ``GNU Free Documentation
52License.''
53
54(a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
55this GNU Manual, like GNU software. Copies published by the Free
56Software Foundation raise funds for GNU development.''
57@end quotation
58@end copying
59
60@dircategory GNU programming tools
61@direntry
62* bison: (bison). GNU parser generator (yacc replacement).
63@end direntry
bfa74976
RS
64
65@ifset shorttitlepage-enabled
66@shorttitlepage Bison
67@end ifset
68@titlepage
69@title Bison
70@subtitle The YACC-compatible Parser Generator
df1af54c 71@subtitle @value{UPDATED}, Bison Version @value{VERSION}
bfa74976
RS
72
73@author by Charles Donnelly and Richard Stallman
74
75@page
76@vskip 0pt plus 1filll
fae437e8 77@insertcopying
bfa74976
RS
78@sp 2
79Published by the Free Software Foundation @*
931c7513
RS
8059 Temple Place, Suite 330 @*
81Boston, MA 02111-1307 USA @*
9ecbd125
JT
82Printed copies are available from the Free Software Foundation.@*
83ISBN 1-882114-44-2
bfa74976
RS
84@sp 2
85Cover art by Etienne Suvasa.
86@end titlepage
d5796688
JT
87
88@contents
bfa74976 89
342b8b6e
AD
90@ifnottex
91@node Top
92@top Bison
fae437e8 93@insertcopying
342b8b6e 94@end ifnottex
bfa74976
RS
95
96@menu
13863333
AD
97* Introduction::
98* Conditions::
bfa74976
RS
99* Copying:: The GNU General Public License says
100 how you can copy and share Bison
101
102Tutorial sections:
103* Concepts:: Basic concepts for understanding Bison.
104* Examples:: Three simple explained examples of using Bison.
105
106Reference sections:
107* Grammar File:: Writing Bison declarations and rules.
108* Interface:: C-language interface to the parser function @code{yyparse}.
109* Algorithm:: How the Bison parser works at run-time.
110* Error Recovery:: Writing rules for error recovery.
111* Context Dependency:: What to do if your language syntax is too
112 messy for Bison to handle straightforwardly.
ec3bc396 113* Debugging:: Understanding or debugging Bison parsers.
bfa74976
RS
114* Invocation:: How to run Bison (to produce the parser source file).
115* Table of Symbols:: All the keywords of the Bison language are explained.
116* Glossary:: Basic concepts are explained.
f2b5126e 117* Copying This Manual:: License for copying this manual.
bfa74976
RS
118* Index:: Cross-references to the text.
119
342b8b6e 120@detailmenu --- The Detailed Node Listing ---
bfa74976
RS
121
122The Concepts of Bison
123
124* Language and Grammar:: Languages and context-free grammars,
125 as mathematical ideas.
126* Grammar in Bison:: How we represent grammars for Bison's sake.
127* Semantic Values:: Each token or syntactic grouping can have
128 a semantic value (the value of an integer,
129 the name of an identifier, etc.).
130* Semantic Actions:: Each rule can have an action containing C code.
131* Bison Parser:: What are Bison's input and output,
132 how is the output used?
133* Stages:: Stages in writing and running Bison grammars.
134* Grammar Layout:: Overall structure of a Bison grammar file.
135
136Examples
137
138* RPN Calc:: Reverse polish notation calculator;
139 a first example with no operator precedence.
140* Infix Calc:: Infix (algebraic) notation calculator.
141 Operator precedence is introduced.
142* Simple Error Recovery:: Continuing after syntax errors.
342b8b6e 143* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
bfa74976
RS
144* Multi-function Calc:: Calculator with memory and trig functions.
145 It uses multiple data-types for semantic values.
146* Exercises:: Ideas for improving the multi-function calculator.
147
148Reverse Polish Notation Calculator
149
75f5aaea 150* Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
bfa74976
RS
151* Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
152* Lexer: Rpcalc Lexer. The lexical analyzer.
153* Main: Rpcalc Main. The controlling function.
154* Error: Rpcalc Error. The error reporting function.
155* Gen: Rpcalc Gen. Running Bison on the grammar file.
156* Comp: Rpcalc Compile. Run the C compiler on the output code.
157
158Grammar Rules for @code{rpcalc}
159
13863333
AD
160* Rpcalc Input::
161* Rpcalc Line::
162* Rpcalc Expr::
bfa74976 163
342b8b6e
AD
164Location Tracking Calculator: @code{ltcalc}
165
166* Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
167* Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
168* Lexer: Ltcalc Lexer. The lexical analyzer.
169
bfa74976
RS
170Multi-Function Calculator: @code{mfcalc}
171
172* Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
173* Rules: Mfcalc Rules. Grammar rules for the calculator.
174* Symtab: Mfcalc Symtab. Symbol table management subroutines.
175
176Bison Grammar Files
177
178* Grammar Outline:: Overall layout of the grammar file.
179* Symbols:: Terminal and nonterminal symbols.
180* Rules:: How to write grammar rules.
181* Recursion:: Writing recursive rules.
182* Semantics:: Semantic values and actions.
183* Declarations:: All kinds of Bison declarations are described here.
184* Multiple Parsers:: Putting more than one Bison parser in one program.
185
186Outline of a Bison Grammar
187
75f5aaea 188* Prologue:: Syntax and usage of the prologue (declarations section).
bfa74976
RS
189* Bison Declarations:: Syntax and usage of the Bison declarations section.
190* Grammar Rules:: Syntax and usage of the grammar rules section.
75f5aaea 191* Epilogue:: Syntax and usage of the epilogue (additional code section).
bfa74976
RS
192
193Defining Language Semantics
194
195* Value Type:: Specifying one data type for all semantic values.
196* Multiple Types:: Specifying several alternative data types.
197* Actions:: An action is the semantic definition of a grammar rule.
198* Action Types:: Specifying data types for actions to operate on.
199* Mid-Rule Actions:: Most actions go at the end of a rule.
200 This says when, why and how to use the exceptional
201 action in the middle of a rule.
202
203Bison Declarations
204
205* Token Decl:: Declaring terminal symbols.
206* Precedence Decl:: Declaring terminals with precedence and associativity.
207* Union Decl:: Declaring the set of all semantic value types.
208* Type Decl:: Declaring the choice of type for a nonterminal symbol.
209* Expect Decl:: Suppressing warnings about shift/reduce conflicts.
210* Start Decl:: Specifying the start symbol.
211* Pure Decl:: Requesting a reentrant parser.
212* Decl Summary:: Table of all Bison declarations.
213
214Parser C-Language Interface
215
216* Parser Function:: How to call @code{yyparse} and what it returns.
13863333 217* Lexical:: You must supply a function @code{yylex}
bfa74976
RS
218 which reads tokens.
219* Error Reporting:: You must supply a function @code{yyerror}.
220* Action Features:: Special features for use in actions.
221
222The Lexical Analyzer Function @code{yylex}
223
224* Calling Convention:: How @code{yyparse} calls @code{yylex}.
225* Token Values:: How @code{yylex} must return the semantic value
226 of the token it has read.
227* Token Positions:: How @code{yylex} must return the text position
228 (line number, etc.) of the token, if the
229 actions want that.
230* Pure Calling:: How the calling convention differs
231 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
232
13863333 233The Bison Parser Algorithm
bfa74976
RS
234
235* Look-Ahead:: Parser looks one token ahead when deciding what to do.
236* Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
237* Precedence:: Operator precedence works by resolving conflicts.
238* Contextual Precedence:: When an operator's precedence depends on context.
239* Parser States:: The parser is a finite-state-machine with stack.
240* Reduce/Reduce:: When two rules are applicable in the same situation.
241* Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
676385e2 242* Generalized LR Parsing:: Parsing arbitrary context-free grammars.
bfa74976
RS
243* Stack Overflow:: What happens when stack gets full. How to avoid it.
244
245Operator Precedence
246
247* Why Precedence:: An example showing why precedence is needed.
248* Using Precedence:: How to specify precedence in Bison grammars.
249* Precedence Examples:: How these features are used in the previous example.
250* How Precedence:: How they work.
251
252Handling Context Dependencies
253
254* Semantic Tokens:: Token parsing can depend on the semantic context.
255* Lexical Tie-ins:: Token parsing can depend on the syntactic context.
256* Tie-in Recovery:: Lexical tie-ins have implications for how
257 error recovery rules must be written.
258
ec3bc396
AD
259Understanding or Debugging Your Parser
260
261* Understanding:: Understanding the structure of your parser.
262* Tracing:: Tracing the execution of your parser.
263
bfa74976
RS
264Invoking Bison
265
13863333 266* Bison Options:: All the options described in detail,
bfa74976
RS
267 in alphabetical order by short options.
268* Option Cross Key:: Alphabetical list of long options.
269* VMS Invocation:: Bison command syntax on VMS.
f2b5126e
PB
270
271Copying This Manual
272
273* GNU Free Documentation License:: License for copying this manual.
274
342b8b6e 275@end detailmenu
bfa74976
RS
276@end menu
277
342b8b6e 278@node Introduction
bfa74976
RS
279@unnumbered Introduction
280@cindex introduction
281
282@dfn{Bison} is a general-purpose parser generator that converts a
283grammar description for an LALR(1) context-free grammar into a C
284program to parse that grammar. Once you are proficient with Bison,
285you may use it to develop a wide range of language parsers, from those
286used in simple desk calculators to complex programming languages.
287
288Bison is upward compatible with Yacc: all properly-written Yacc grammars
289ought to work with Bison with no change. Anyone familiar with Yacc
290should be able to use Bison with little trouble. You need to be fluent in
291C programming in order to use Bison or to understand this manual.
292
293We begin with tutorial chapters that explain the basic concepts of using
294Bison and show three explained examples, each building on the last. If you
295don't know Bison or Yacc, start by reading these chapters. Reference
296chapters follow which describe specific aspects of Bison in detail.
297
931c7513
RS
298Bison was written primarily by Robert Corbett; Richard Stallman made it
299Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
14ded682 300multi-character string literals and other features.
931c7513 301
df1af54c 302This edition corresponds to version @value{VERSION} of Bison.
bfa74976 303
342b8b6e 304@node Conditions
bfa74976
RS
305@unnumbered Conditions for Using Bison
306
a31239f1 307As of Bison version 1.24, we have changed the distribution terms for
262aa8dd
PE
308@code{yyparse} to permit using Bison's output in nonfree programs when
309Bison is generating C code for LALR(1) parsers. Formerly, these
310parsers could be used only in programs that were free software.
a31239f1
RS
311
312The other GNU programming tools, such as the GNU C compiler, have never
9ecbd125 313had such a requirement. They could always be used for nonfree
a31239f1
RS
314software. The reason Bison was different was not due to a special
315policy decision; it resulted from applying the usual General Public
316License to all of the Bison source code.
317
318The output of the Bison utility---the Bison parser file---contains a
319verbatim copy of a sizable piece of Bison, which is the code for the
320@code{yyparse} function. (The actions from your grammar are inserted
321into this function at one point, but the rest of the function is not
322changed.) When we applied the GPL terms to the code for @code{yyparse},
323the effect was to restrict the use of Bison output to free software.
324
325We didn't change the terms because of sympathy for people who want to
326make software proprietary. @strong{Software should be free.} But we
327concluded that limiting Bison's use to free software was doing little to
328encourage people to make other software free. So we decided to make the
329practical conditions for using Bison match the practical conditions for
330using the other GNU tools.
bfa74976 331
262aa8dd
PE
332This exception applies only when Bison is generating C code for a
333LALR(1) parser; otherwise, the GPL terms operate as usual. You can
334tell whether the exception applies to your @samp{.c} output file by
335inspecting it to see whether it says ``As a special exception, when
336this file is copied by Bison into a Bison output file, you may use
337that output file without restriction.''
338
c67a198d 339@include gpl.texi
bfa74976 340
342b8b6e 341@node Concepts
bfa74976
RS
342@chapter The Concepts of Bison
343
344This chapter introduces many of the basic concepts without which the
345details of Bison will not make sense. If you do not already know how to
346use Bison or Yacc, we suggest you start by reading this chapter carefully.
347
348@menu
349* Language and Grammar:: Languages and context-free grammars,
350 as mathematical ideas.
351* Grammar in Bison:: How we represent grammars for Bison's sake.
352* Semantic Values:: Each token or syntactic grouping can have
353 a semantic value (the value of an integer,
354 the name of an identifier, etc.).
355* Semantic Actions:: Each rule can have an action containing C code.
676385e2 356* GLR Parsers:: Writing parsers for general context-free languages
847bf1f5 357* Locations Overview:: Tracking Locations.
bfa74976
RS
358* Bison Parser:: What are Bison's input and output,
359 how is the output used?
360* Stages:: Stages in writing and running Bison grammars.
361* Grammar Layout:: Overall structure of a Bison grammar file.
362@end menu
363
342b8b6e 364@node Language and Grammar
bfa74976
RS
365@section Languages and Context-Free Grammars
366
bfa74976
RS
367@cindex context-free grammar
368@cindex grammar, context-free
369In order for Bison to parse a language, it must be described by a
370@dfn{context-free grammar}. This means that you specify one or more
371@dfn{syntactic groupings} and give rules for constructing them from their
372parts. For example, in the C language, one kind of grouping is called an
373`expression'. One rule for making an expression might be, ``An expression
374can be made of a minus sign and another expression''. Another would be,
375``An expression can be an integer''. As you can see, rules are often
376recursive, but there must be at least one rule which leads out of the
377recursion.
378
379@cindex BNF
380@cindex Backus-Naur form
381The most common formal system for presenting such rules for humans to read
382is @dfn{Backus-Naur Form} or ``BNF'', which was developed in order to
383specify the language Algol 60. Any grammar expressed in BNF is a
384context-free grammar. The input to Bison is essentially machine-readable
385BNF.
386
676385e2
PH
387@cindex LALR(1) grammars
388@cindex LR(1) grammars
389There are various important subclasses of context-free grammar. Although it
390can handle almost all context-free grammars, Bison is optimized for what
391are called LALR(1) grammars.
392In brief, in these grammars, it must be possible to
bfa74976
RS
393tell how to parse any portion of an input string with just a single
394token of look-ahead. Strictly speaking, that is a description of an
395LR(1) grammar, and LALR(1) involves additional restrictions that are
396hard to explain simply; but it is rare in actual practice to find an
397LR(1) grammar that fails to be LALR(1). @xref{Mystery Conflicts, ,
398Mysterious Reduce/Reduce Conflicts}, for more information on this.
399
676385e2
PH
400@cindex GLR parsing
401@cindex generalized LR (GLR) parsing
402@cindex ambiguous grammars
403@cindex non-deterministic parsing
404Parsers for LALR(1) grammars are @dfn{deterministic}, meaning roughly that
fae437e8 405the next grammar rule to apply at any point in the input is uniquely
676385e2
PH
406determined by the preceding input and a fixed, finite portion (called
407a @dfn{look-ahead}) of the remaining input.
fae437e8 408A context-free grammar can be @dfn{ambiguous}, meaning that
676385e2
PH
409there are multiple ways to apply the grammar rules to get the some inputs.
410Even unambiguous grammars can be @dfn{non-deterministic}, meaning that no
411fixed look-ahead always suffices to determine the next grammar rule to apply.
fae437e8
AD
412With the proper declarations, Bison is also able to parse these more general
413context-free grammars, using a technique known as GLR parsing (for
414Generalized LR). Bison's GLR parsers are able to handle any context-free
415grammar for which the number of possible parses of any given string
416is finite.
676385e2 417
bfa74976
RS
418@cindex symbols (abstract)
419@cindex token
420@cindex syntactic grouping
421@cindex grouping, syntactic
422In the formal grammatical rules for a language, each kind of syntactic unit
423or grouping is named by a @dfn{symbol}. Those which are built by grouping
424smaller constructs according to grammatical rules are called
425@dfn{nonterminal symbols}; those which can't be subdivided are called
426@dfn{terminal symbols} or @dfn{token types}. We call a piece of input
427corresponding to a single terminal symbol a @dfn{token}, and a piece
e0c471a9 428corresponding to a single nonterminal symbol a @dfn{grouping}.
bfa74976
RS
429
430We can use the C language as an example of what symbols, terminal and
431nonterminal, mean. The tokens of C are identifiers, constants (numeric and
432string), and the various keywords, arithmetic operators and punctuation
433marks. So the terminal symbols of a grammar for C include `identifier',
434`number', `string', plus one symbol for each keyword, operator or
435punctuation mark: `if', `return', `const', `static', `int', `char',
436`plus-sign', `open-brace', `close-brace', `comma' and many more. (These
437tokens can be subdivided into characters, but that is a matter of
438lexicography, not grammar.)
439
440Here is a simple C function subdivided into tokens:
441
9edcd895
AD
442@ifinfo
443@example
444int /* @r{keyword `int'} */
445square (int x) /* @r{identifier, open-paren, identifier,}
446 @r{identifier, close-paren} */
447@{ /* @r{open-brace} */
448 return x * x; /* @r{keyword `return', identifier, asterisk,
449 identifier, semicolon} */
450@} /* @r{close-brace} */
451@end example
452@end ifinfo
453@ifnotinfo
bfa74976
RS
454@example
455int /* @r{keyword `int'} */
9edcd895 456square (int x) /* @r{identifier, open-paren, identifier, identifier, close-paren} */
bfa74976 457@{ /* @r{open-brace} */
9edcd895 458 return x * x; /* @r{keyword `return', identifier, asterisk, identifier, semicolon} */
bfa74976
RS
459@} /* @r{close-brace} */
460@end example
9edcd895 461@end ifnotinfo
bfa74976
RS
462
463The syntactic groupings of C include the expression, the statement, the
464declaration, and the function definition. These are represented in the
465grammar of C by nonterminal symbols `expression', `statement',
466`declaration' and `function definition'. The full grammar uses dozens of
467additional language constructs, each with its own nonterminal symbol, in
468order to express the meanings of these four. The example above is a
469function definition; it contains one declaration, and one statement. In
470the statement, each @samp{x} is an expression and so is @samp{x * x}.
471
472Each nonterminal symbol must have grammatical rules showing how it is made
473out of simpler constructs. For example, one kind of C statement is the
474@code{return} statement; this would be described with a grammar rule which
475reads informally as follows:
476
477@quotation
478A `statement' can be made of a `return' keyword, an `expression' and a
479`semicolon'.
480@end quotation
481
482@noindent
483There would be many other rules for `statement', one for each kind of
484statement in C.
485
486@cindex start symbol
487One nonterminal symbol must be distinguished as the special one which
488defines a complete utterance in the language. It is called the @dfn{start
489symbol}. In a compiler, this means a complete input program. In the C
490language, the nonterminal symbol `sequence of definitions and declarations'
491plays this role.
492
493For example, @samp{1 + 2} is a valid C expression---a valid part of a C
494program---but it is not valid as an @emph{entire} C program. In the
495context-free grammar of C, this follows from the fact that `expression' is
496not the start symbol.
497
498The Bison parser reads a sequence of tokens as its input, and groups the
499tokens using the grammar rules. If the input is valid, the end result is
500that the entire token sequence reduces to a single grouping whose symbol is
501the grammar's start symbol. If we use a grammar for C, the entire input
502must be a `sequence of definitions and declarations'. If not, the parser
503reports a syntax error.
504
342b8b6e 505@node Grammar in Bison
bfa74976
RS
506@section From Formal Rules to Bison Input
507@cindex Bison grammar
508@cindex grammar, Bison
509@cindex formal grammar
510
511A formal grammar is a mathematical construct. To define the language
512for Bison, you must write a file expressing the grammar in Bison syntax:
513a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
514
515A nonterminal symbol in the formal grammar is represented in Bison input
516as an identifier, like an identifier in C. By convention, it should be
517in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
518
519The Bison representation for a terminal symbol is also called a @dfn{token
520type}. Token types as well can be represented as C-like identifiers. By
521convention, these identifiers should be upper case to distinguish them from
522nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
523@code{RETURN}. A terminal symbol that stands for a particular keyword in
524the language should be named after that keyword converted to upper case.
525The terminal symbol @code{error} is reserved for error recovery.
931c7513 526@xref{Symbols}.
bfa74976
RS
527
528A terminal symbol can also be represented as a character literal, just like
529a C character constant. You should do this whenever a token is just a
530single character (parenthesis, plus-sign, etc.): use that same character in
531a literal as the terminal symbol for that token.
532
931c7513
RS
533A third way to represent a terminal symbol is with a C string constant
534containing several characters. @xref{Symbols}, for more information.
535
bfa74976
RS
536The grammar rules also have an expression in Bison syntax. For example,
537here is the Bison rule for a C @code{return} statement. The semicolon in
538quotes is a literal character token, representing part of the C syntax for
539the statement; the naked semicolon, and the colon, are Bison punctuation
540used in every rule.
541
542@example
543stmt: RETURN expr ';'
544 ;
545@end example
546
547@noindent
548@xref{Rules, ,Syntax of Grammar Rules}.
549
342b8b6e 550@node Semantic Values
bfa74976
RS
551@section Semantic Values
552@cindex semantic value
553@cindex value, semantic
554
555A formal grammar selects tokens only by their classifications: for example,
556if a rule mentions the terminal symbol `integer constant', it means that
557@emph{any} integer constant is grammatically valid in that position. The
558precise value of the constant is irrelevant to how to parse the input: if
559@samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
e0c471a9 560grammatical.
bfa74976
RS
561
562But the precise value is very important for what the input means once it is
563parsed. A compiler is useless if it fails to distinguish between 4, 1 and
5643989 as constants in the program! Therefore, each token in a Bison grammar
565has both a token type and a @dfn{semantic value}. @xref{Semantics, ,Defining Language Semantics},
566for details.
567
568The token type is a terminal symbol defined in the grammar, such as
569@code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
570you need to know to decide where the token may validly appear and how to
571group it with other tokens. The grammar rules know nothing about tokens
e0c471a9 572except their types.
bfa74976
RS
573
574The semantic value has all the rest of the information about the
575meaning of the token, such as the value of an integer, or the name of an
576identifier. (A token such as @code{','} which is just punctuation doesn't
577need to have any semantic value.)
578
579For example, an input token might be classified as token type
580@code{INTEGER} and have the semantic value 4. Another input token might
581have the same token type @code{INTEGER} but value 3989. When a grammar
582rule says that @code{INTEGER} is allowed, either of these tokens is
583acceptable because each is an @code{INTEGER}. When the parser accepts the
584token, it keeps track of the token's semantic value.
585
586Each grouping can also have a semantic value as well as its nonterminal
587symbol. For example, in a calculator, an expression typically has a
588semantic value that is a number. In a compiler for a programming
589language, an expression typically has a semantic value that is a tree
590structure describing the meaning of the expression.
591
342b8b6e 592@node Semantic Actions
bfa74976
RS
593@section Semantic Actions
594@cindex semantic actions
595@cindex actions, semantic
596
597In order to be useful, a program must do more than parse input; it must
598also produce some output based on the input. In a Bison grammar, a grammar
599rule can have an @dfn{action} made up of C statements. Each time the
600parser recognizes a match for that rule, the action is executed.
601@xref{Actions}.
13863333 602
bfa74976
RS
603Most of the time, the purpose of an action is to compute the semantic value
604of the whole construct from the semantic values of its parts. For example,
605suppose we have a rule which says an expression can be the sum of two
606expressions. When the parser recognizes such a sum, each of the
607subexpressions has a semantic value which describes how it was built up.
608The action for this rule should create a similar sort of value for the
609newly recognized larger expression.
610
611For example, here is a rule that says an expression can be the sum of
612two subexpressions:
613
614@example
615expr: expr '+' expr @{ $$ = $1 + $3; @}
616 ;
617@end example
618
619@noindent
620The action says how to produce the semantic value of the sum expression
621from the values of the two subexpressions.
622
676385e2
PH
623@node GLR Parsers
624@section Writing GLR Parsers
625@cindex GLR parsing
626@cindex generalized LR (GLR) parsing
627@findex %glr-parser
628@cindex conflicts
629@cindex shift/reduce conflicts
630
631In some grammars, there will be cases where Bison's standard LALR(1)
632parsing algorithm cannot decide whether to apply a certain grammar rule
633at a given point. That is, it may not be able to decide (on the basis
634of the input read so far) which of two possible reductions (applications
635of a grammar rule) applies, or whether to apply a reduction or read more
636of the input and apply a reduction later in the input. These are known
637respectively as @dfn{reduce/reduce} conflicts (@pxref{Reduce/Reduce}),
638and @dfn{shift/reduce} conflicts (@pxref{Shift/Reduce}).
639
640To use a grammar that is not easily modified to be LALR(1), a more
641general parsing algorithm is sometimes necessary. If you include
642@code{%glr-parser} among the Bison declarations in your file
643(@pxref{Grammar Outline}), the result will be a Generalized LR (GLR)
644parser. These parsers handle Bison grammars that contain no unresolved
645conflicts (i.e., after applying precedence declarations) identically to
646LALR(1) parsers. However, when faced with unresolved shift/reduce and
647reduce/reduce conflicts, GLR parsers use the simple expedient of doing
648both, effectively cloning the parser to follow both possibilities. Each
649of the resulting parsers can again split, so that at any given time,
650there can be any number of possible parses being explored. The parsers
651proceed in lockstep; that is, all of them consume (shift) a given input
652symbol before any of them proceed to the next. Each of the cloned
653parsers eventually meets one of two possible fates: either it runs into
654a parsing error, in which case it simply vanishes, or it merges with
655another parser, because the two of them have reduced the input to an
656identical set of symbols.
657
658During the time that there are multiple parsers, semantic actions are
659recorded, but not performed. When a parser disappears, its recorded
660semantic actions disappear as well, and are never performed. When a
661reduction makes two parsers identical, causing them to merge, Bison
662records both sets of semantic actions. Whenever the last two parsers
663merge, reverting to the single-parser case, Bison resolves all the
664outstanding actions either by precedences given to the grammar rules
665involved, or by performing both actions, and then calling a designated
666user-defined function on the resulting values to produce an arbitrary
667merged result.
668
fae437e8 669Let's consider an example, vastly simplified from C++.
676385e2
PH
670
671@example
672%@{
673 #define YYSTYPE const char*
674%@}
675
676%token TYPENAME ID
677
678%right '='
679%left '+'
680
681%glr-parser
682
683%%
684
fae437e8 685prog :
676385e2
PH
686 | prog stmt @{ printf ("\n"); @}
687 ;
688
689stmt : expr ';' %dprec 1
690 | decl %dprec 2
691 ;
692
693expr : ID @{ printf ("%s ", $$); @}
fae437e8 694 | TYPENAME '(' expr ')'
676385e2
PH
695 @{ printf ("%s <cast> ", $1); @}
696 | expr '+' expr @{ printf ("+ "); @}
697 | expr '=' expr @{ printf ("= "); @}
698 ;
699
fae437e8 700decl : TYPENAME declarator ';'
676385e2
PH
701 @{ printf ("%s <declare> ", $1); @}
702 | TYPENAME declarator '=' expr ';'
703 @{ printf ("%s <init-declare> ", $1); @}
704 ;
705
706declarator : ID @{ printf ("\"%s\" ", $1); @}
707 | '(' declarator ')'
708 ;
709@end example
710
711@noindent
712This models a problematic part of the C++ grammar---the ambiguity between
713certain declarations and statements. For example,
714
715@example
716T (x) = y+z;
717@end example
718
719@noindent
720parses as either an @code{expr} or a @code{stmt}
721(assuming that @samp{T} is recognized as a TYPENAME and @samp{x} as an ID).
722Bison detects this as a reduce/reduce conflict between the rules
fae437e8
AD
723@code{expr : ID} and @code{declarator : ID}, which it cannot resolve at the
724time it encounters @code{x} in the example above. The two @code{%dprec}
725declarations, however, give precedence to interpreting the example as a
676385e2
PH
726@code{decl}, which implies that @code{x} is a declarator.
727The parser therefore prints
728
729@example
fae437e8 730"x" y z + T <init-declare>
676385e2
PH
731@end example
732
733Consider a different input string for this parser:
734
735@example
736T (x) + y;
737@end example
738
739@noindent
740Here, there is no ambiguity (this cannot be parsed as a declaration).
741However, at the time the Bison parser encounters @code{x}, it does not
742have enough information to resolve the reduce/reduce conflict (again,
743between @code{x} as an @code{expr} or a @code{declarator}). In this
744case, no precedence declaration is used. Instead, the parser splits
745into two, one assuming that @code{x} is an @code{expr}, and the other
746assuming @code{x} is a @code{declarator}. The second of these parsers
747then vanishes when it sees @code{+}, and the parser prints
748
749@example
fae437e8 750x T <cast> y +
676385e2
PH
751@end example
752
753Suppose that instead of resolving the ambiguity, you wanted to see all
754the possibilities. For this purpose, we must @dfn{merge} the semantic
755actions of the two possible parsers, rather than choosing one over the
756other. To do so, you could change the declaration of @code{stmt} as
757follows:
758
759@example
760stmt : expr ';' %merge <stmtMerge>
761 | decl %merge <stmtMerge>
762 ;
763@end example
764
765@noindent
766
767and define the @code{stmtMerge} function as:
768
769@example
770static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1)
771@{
772 printf ("<OR> ");
773 return "";
774@}
775@end example
776
777@noindent
778with an accompanying forward declaration
779in the C declarations at the beginning of the file:
780
781@example
782%@{
783 #define YYSTYPE const char*
784 static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
785%@}
786@end example
787
788@noindent
789With these declarations, the resulting parser will parse the first example
790as both an @code{expr} and a @code{decl}, and print
791
792@example
fae437e8 793"x" y z + T <init-declare> x T <cast> y z + = <OR>
676385e2
PH
794@end example
795
796
342b8b6e 797@node Locations Overview
847bf1f5
AD
798@section Locations
799@cindex location
800@cindex textual position
801@cindex position, textual
802
803Many applications, like interpreters or compilers, have to produce verbose
804and useful error messages. To achieve this, one must be able to keep track of
805the @dfn{textual position}, or @dfn{location}, of each syntactic construct.
806Bison provides a mechanism for handling these locations.
807
808Each token has a semantic value. In a similar fashion, each token has an
809associated location, but the type of locations is the same for all tokens and
810groupings. Moreover, the output parser is equipped with a default data
811structure for storing locations (@pxref{Locations}, for more details).
812
813Like semantic values, locations can be reached in actions using a dedicated
814set of constructs. In the example above, the location of the whole grouping
815is @code{@@$}, while the locations of the subexpressions are @code{@@1} and
816@code{@@3}.
817
818When a rule is matched, a default action is used to compute the semantic value
819of its left hand side (@pxref{Actions}). In the same way, another default
820action is used for locations. However, the action for locations is general
821enough for most cases, meaning there is usually no need to describe for each
822rule how @code{@@$} should be formed. When building a new location for a given
823grouping, the default behavior of the output parser is to take the beginning
824of the first symbol, and the end of the last symbol.
825
342b8b6e 826@node Bison Parser
bfa74976
RS
827@section Bison Output: the Parser File
828@cindex Bison parser
829@cindex Bison utility
830@cindex lexical analyzer, purpose
831@cindex parser
832
833When you run Bison, you give it a Bison grammar file as input. The output
834is a C source file that parses the language described by the grammar.
835This file is called a @dfn{Bison parser}. Keep in mind that the Bison
836utility and the Bison parser are two distinct programs: the Bison utility
837is a program whose output is the Bison parser that becomes part of your
838program.
839
840The job of the Bison parser is to group tokens into groupings according to
841the grammar rules---for example, to build identifiers and operators into
842expressions. As it does this, it runs the actions for the grammar rules it
843uses.
844
704a47c4
AD
845The tokens come from a function called the @dfn{lexical analyzer} that
846you must supply in some fashion (such as by writing it in C). The Bison
847parser calls the lexical analyzer each time it wants a new token. It
848doesn't know what is ``inside'' the tokens (though their semantic values
849may reflect this). Typically the lexical analyzer makes the tokens by
850parsing characters of text, but Bison does not depend on this.
851@xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
bfa74976
RS
852
853The Bison parser file is C code which defines a function named
854@code{yyparse} which implements that grammar. This function does not make
855a complete C program: you must supply some additional functions. One is
856the lexical analyzer. Another is an error-reporting function which the
857parser calls to report an error. In addition, a complete C program must
858start with a function called @code{main}; you have to provide this, and
859arrange for it to call @code{yyparse} or the parser will never run.
860@xref{Interface, ,Parser C-Language Interface}.
861
862Aside from the token type names and the symbols in the actions you
7093d0f5 863write, all symbols defined in the Bison parser file itself
bfa74976
RS
864begin with @samp{yy} or @samp{YY}. This includes interface functions
865such as the lexical analyzer function @code{yylex}, the error reporting
866function @code{yyerror} and the parser function @code{yyparse} itself.
867This also includes numerous identifiers used for internal purposes.
868Therefore, you should avoid using C identifiers starting with @samp{yy}
869or @samp{YY} in the Bison grammar file except for the ones defined in
870this manual.
871
7093d0f5
AD
872In some cases the Bison parser file includes system headers, and in
873those cases your code should respect the identifiers reserved by those
874headers. On some non-@sc{gnu} hosts, @code{<alloca.h>},
875@code{<stddef.h>}, and @code{<stdlib.h>} are included as needed to
ec3bc396
AD
876declare memory allocators and related types. Other system headers may
877be included if you define @code{YYDEBUG} to a nonzero value
878(@pxref{Tracing, ,Tracing Your Parser}).
7093d0f5 879
342b8b6e 880@node Stages
bfa74976
RS
881@section Stages in Using Bison
882@cindex stages in using Bison
883@cindex using Bison
884
885The actual language-design process using Bison, from grammar specification
886to a working compiler or interpreter, has these parts:
887
888@enumerate
889@item
890Formally specify the grammar in a form recognized by Bison
704a47c4
AD
891(@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule
892in the language, describe the action that is to be taken when an
893instance of that rule is recognized. The action is described by a
894sequence of C statements.
bfa74976
RS
895
896@item
704a47c4
AD
897Write a lexical analyzer to process input and pass tokens to the parser.
898The lexical analyzer may be written by hand in C (@pxref{Lexical, ,The
899Lexical Analyzer Function @code{yylex}}). It could also be produced
900using Lex, but the use of Lex is not discussed in this manual.
bfa74976
RS
901
902@item
903Write a controlling function that calls the Bison-produced parser.
904
905@item
906Write error-reporting routines.
907@end enumerate
908
909To turn this source code as written into a runnable program, you
910must follow these steps:
911
912@enumerate
913@item
914Run Bison on the grammar to produce the parser.
915
916@item
917Compile the code output by Bison, as well as any other source files.
918
919@item
920Link the object files to produce the finished product.
921@end enumerate
922
342b8b6e 923@node Grammar Layout
bfa74976
RS
924@section The Overall Layout of a Bison Grammar
925@cindex grammar file
926@cindex file format
927@cindex format of grammar file
928@cindex layout of Bison grammar
929
930The input file for the Bison utility is a @dfn{Bison grammar file}. The
931general form of a Bison grammar file is as follows:
932
933@example
934%@{
08e49d20 935@var{Prologue}
bfa74976
RS
936%@}
937
938@var{Bison declarations}
939
940%%
941@var{Grammar rules}
942%%
08e49d20 943@var{Epilogue}
bfa74976
RS
944@end example
945
946@noindent
947The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
948in every Bison grammar file to separate the sections.
949
342b8b6e
AD
950The prologue may define types and variables used in the actions. You can
951also use preprocessor commands to define macros used there, and use
bfa74976
RS
952@code{#include} to include header files that do any of these things.
953
954The Bison declarations declare the names of the terminal and nonterminal
955symbols, and may also describe operator precedence and the data types of
956semantic values of various symbols.
957
958The grammar rules define how to construct each nonterminal symbol from its
959parts.
960
342b8b6e
AD
961The epilogue can contain any code you want to use. Often the definition of
962the lexical analyzer @code{yylex} goes here, plus subroutines called by the
963actions in the grammar rules. In a simple program, all the rest of the
75f5aaea 964program can go here.
bfa74976 965
342b8b6e 966@node Examples
bfa74976
RS
967@chapter Examples
968@cindex simple examples
969@cindex examples, simple
970
971Now we show and explain three sample programs written using Bison: a
972reverse polish notation calculator, an algebraic (infix) notation
973calculator, and a multi-function calculator. All three have been tested
974under BSD Unix 4.3; each produces a usable, though limited, interactive
975desk-top calculator.
976
977These examples are simple, but Bison grammars for real programming
978languages are written the same way.
979@ifinfo
980You can copy these examples out of the Info file and into a source file
981to try them.
982@end ifinfo
983
984@menu
985* RPN Calc:: Reverse polish notation calculator;
986 a first example with no operator precedence.
987* Infix Calc:: Infix (algebraic) notation calculator.
988 Operator precedence is introduced.
989* Simple Error Recovery:: Continuing after syntax errors.
342b8b6e 990* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
bfa74976
RS
991* Multi-function Calc:: Calculator with memory and trig functions.
992 It uses multiple data-types for semantic values.
993* Exercises:: Ideas for improving the multi-function calculator.
994@end menu
995
342b8b6e 996@node RPN Calc
bfa74976
RS
997@section Reverse Polish Notation Calculator
998@cindex reverse polish notation
999@cindex polish notation calculator
1000@cindex @code{rpcalc}
1001@cindex calculator, simple
1002
1003The first example is that of a simple double-precision @dfn{reverse polish
1004notation} calculator (a calculator using postfix operators). This example
1005provides a good starting point, since operator precedence is not an issue.
1006The second example will illustrate how operator precedence is handled.
1007
1008The source code for this calculator is named @file{rpcalc.y}. The
1009@samp{.y} extension is a convention used for Bison input files.
1010
1011@menu
75f5aaea 1012* Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
bfa74976
RS
1013* Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1014* Lexer: Rpcalc Lexer. The lexical analyzer.
1015* Main: Rpcalc Main. The controlling function.
1016* Error: Rpcalc Error. The error reporting function.
1017* Gen: Rpcalc Gen. Running Bison on the grammar file.
1018* Comp: Rpcalc Compile. Run the C compiler on the output code.
1019@end menu
1020
342b8b6e 1021@node Rpcalc Decls
bfa74976
RS
1022@subsection Declarations for @code{rpcalc}
1023
1024Here are the C and Bison declarations for the reverse polish notation
1025calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
1026
1027@example
1028/* Reverse polish notation calculator. */
1029
1030%@{
1031#define YYSTYPE double
1032#include <math.h>
1033%@}
1034
1035%token NUM
1036
1037%% /* Grammar rules and actions follow */
1038@end example
1039
75f5aaea 1040The declarations section (@pxref{Prologue, , The prologue}) contains two
bfa74976
RS
1041preprocessor directives.
1042
1043The @code{#define} directive defines the macro @code{YYSTYPE}, thus
1964ad8c
AD
1044specifying the C data type for semantic values of both tokens and
1045groupings (@pxref{Value Type, ,Data Types of Semantic Values}). The
1046Bison parser will use whatever type @code{YYSTYPE} is defined as; if you
1047don't define it, @code{int} is the default. Because we specify
1048@code{double}, each token and each expression has an associated value,
1049which is a floating point number.
bfa74976
RS
1050
1051The @code{#include} directive is used to declare the exponentiation
1052function @code{pow}.
1053
704a47c4
AD
1054The second section, Bison declarations, provides information to Bison
1055about the token types (@pxref{Bison Declarations, ,The Bison
1056Declarations Section}). Each terminal symbol that is not a
1057single-character literal must be declared here. (Single-character
bfa74976
RS
1058literals normally don't need to be declared.) In this example, all the
1059arithmetic operators are designated by single-character literals, so the
1060only terminal symbol that needs to be declared is @code{NUM}, the token
1061type for numeric constants.
1062
342b8b6e 1063@node Rpcalc Rules
bfa74976
RS
1064@subsection Grammar Rules for @code{rpcalc}
1065
1066Here are the grammar rules for the reverse polish notation calculator.
1067
1068@example
1069input: /* empty */
1070 | input line
1071;
1072
1073line: '\n'
1074 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1075;
1076
1077exp: NUM @{ $$ = $1; @}
1078 | exp exp '+' @{ $$ = $1 + $2; @}
1079 | exp exp '-' @{ $$ = $1 - $2; @}
1080 | exp exp '*' @{ $$ = $1 * $2; @}
1081 | exp exp '/' @{ $$ = $1 / $2; @}
1082 /* Exponentiation */
1083 | exp exp '^' @{ $$ = pow ($1, $2); @}
1084 /* Unary minus */
1085 | exp 'n' @{ $$ = -$1; @}
1086;
1087%%
1088@end example
1089
1090The groupings of the rpcalc ``language'' defined here are the expression
1091(given the name @code{exp}), the line of input (@code{line}), and the
1092complete input transcript (@code{input}). Each of these nonterminal
1093symbols has several alternate rules, joined by the @samp{|} punctuator
1094which is read as ``or''. The following sections explain what these rules
1095mean.
1096
1097The semantics of the language is determined by the actions taken when a
1098grouping is recognized. The actions are the C code that appears inside
1099braces. @xref{Actions}.
1100
1101You must specify these actions in C, but Bison provides the means for
1102passing semantic values between the rules. In each action, the
1103pseudo-variable @code{$$} stands for the semantic value for the grouping
1104that the rule is going to construct. Assigning a value to @code{$$} is the
1105main job of most actions. The semantic values of the components of the
1106rule are referred to as @code{$1}, @code{$2}, and so on.
1107
1108@menu
13863333
AD
1109* Rpcalc Input::
1110* Rpcalc Line::
1111* Rpcalc Expr::
bfa74976
RS
1112@end menu
1113
342b8b6e 1114@node Rpcalc Input
bfa74976
RS
1115@subsubsection Explanation of @code{input}
1116
1117Consider the definition of @code{input}:
1118
1119@example
1120input: /* empty */
1121 | input line
1122;
1123@end example
1124
1125This definition reads as follows: ``A complete input is either an empty
1126string, or a complete input followed by an input line''. Notice that
1127``complete input'' is defined in terms of itself. This definition is said
1128to be @dfn{left recursive} since @code{input} appears always as the
1129leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
1130
1131The first alternative is empty because there are no symbols between the
1132colon and the first @samp{|}; this means that @code{input} can match an
1133empty string of input (no tokens). We write the rules this way because it
1134is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
1135It's conventional to put an empty alternative first and write the comment
1136@samp{/* empty */} in it.
1137
1138The second alternate rule (@code{input line}) handles all nontrivial input.
1139It means, ``After reading any number of lines, read one more line if
1140possible.'' The left recursion makes this rule into a loop. Since the
1141first alternative matches empty input, the loop can be executed zero or
1142more times.
1143
1144The parser function @code{yyparse} continues to process input until a
1145grammatical error is seen or the lexical analyzer says there are no more
1146input tokens; we will arrange for the latter to happen at end of file.
1147
342b8b6e 1148@node Rpcalc Line
bfa74976
RS
1149@subsubsection Explanation of @code{line}
1150
1151Now consider the definition of @code{line}:
1152
1153@example
1154line: '\n'
1155 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1156;
1157@end example
1158
1159The first alternative is a token which is a newline character; this means
1160that rpcalc accepts a blank line (and ignores it, since there is no
1161action). The second alternative is an expression followed by a newline.
1162This is the alternative that makes rpcalc useful. The semantic value of
1163the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
1164question is the first symbol in the alternative. The action prints this
1165value, which is the result of the computation the user asked for.
1166
1167This action is unusual because it does not assign a value to @code{$$}. As
1168a consequence, the semantic value associated with the @code{line} is
1169uninitialized (its value will be unpredictable). This would be a bug if
1170that value were ever used, but we don't use it: once rpcalc has printed the
1171value of the user's input line, that value is no longer needed.
1172
342b8b6e 1173@node Rpcalc Expr
bfa74976
RS
1174@subsubsection Explanation of @code{expr}
1175
1176The @code{exp} grouping has several rules, one for each kind of expression.
1177The first rule handles the simplest expressions: those that are just numbers.
1178The second handles an addition-expression, which looks like two expressions
1179followed by a plus-sign. The third handles subtraction, and so on.
1180
1181@example
1182exp: NUM
1183 | exp exp '+' @{ $$ = $1 + $2; @}
1184 | exp exp '-' @{ $$ = $1 - $2; @}
1185 @dots{}
1186 ;
1187@end example
1188
1189We have used @samp{|} to join all the rules for @code{exp}, but we could
1190equally well have written them separately:
1191
1192@example
1193exp: NUM ;
1194exp: exp exp '+' @{ $$ = $1 + $2; @} ;
1195exp: exp exp '-' @{ $$ = $1 - $2; @} ;
1196 @dots{}
1197@end example
1198
1199Most of the rules have actions that compute the value of the expression in
1200terms of the value of its parts. For example, in the rule for addition,
1201@code{$1} refers to the first component @code{exp} and @code{$2} refers to
1202the second one. The third component, @code{'+'}, has no meaningful
1203associated semantic value, but if it had one you could refer to it as
1204@code{$3}. When @code{yyparse} recognizes a sum expression using this
1205rule, the sum of the two subexpressions' values is produced as the value of
1206the entire expression. @xref{Actions}.
1207
1208You don't have to give an action for every rule. When a rule has no
1209action, Bison by default copies the value of @code{$1} into @code{$$}.
1210This is what happens in the first rule (the one that uses @code{NUM}).
1211
1212The formatting shown here is the recommended convention, but Bison does
1213not require it. You can add or change whitespace as much as you wish.
1214For example, this:
1215
1216@example
1217exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{}
1218@end example
1219
1220@noindent
1221means the same thing as this:
1222
1223@example
1224exp: NUM
1225 | exp exp '+' @{ $$ = $1 + $2; @}
1226 | @dots{}
1227@end example
1228
1229@noindent
1230The latter, however, is much more readable.
1231
342b8b6e 1232@node Rpcalc Lexer
bfa74976
RS
1233@subsection The @code{rpcalc} Lexical Analyzer
1234@cindex writing a lexical analyzer
1235@cindex lexical analyzer, writing
1236
704a47c4
AD
1237The lexical analyzer's job is low-level parsing: converting characters
1238or sequences of characters into tokens. The Bison parser gets its
1239tokens by calling the lexical analyzer. @xref{Lexical, ,The Lexical
1240Analyzer Function @code{yylex}}.
bfa74976
RS
1241
1242Only a simple lexical analyzer is needed for the RPN calculator. This
1243lexical analyzer skips blanks and tabs, then reads in numbers as
1244@code{double} and returns them as @code{NUM} tokens. Any other character
1245that isn't part of a number is a separate token. Note that the token-code
1246for such a single-character token is the character itself.
1247
1248The return value of the lexical analyzer function is a numeric code which
1249represents a token type. The same text used in Bison rules to stand for
1250this token type is also a C expression for the numeric code for the type.
1251This works in two ways. If the token type is a character literal, then its
e966383b 1252numeric code is that of the character; you can use the same
bfa74976
RS
1253character literal in the lexical analyzer to express the number. If the
1254token type is an identifier, that identifier is defined by Bison as a C
1255macro whose definition is the appropriate number. In this example,
1256therefore, @code{NUM} becomes a macro for @code{yylex} to use.
1257
1964ad8c
AD
1258The semantic value of the token (if it has one) is stored into the
1259global variable @code{yylval}, which is where the Bison parser will look
1260for it. (The C data type of @code{yylval} is @code{YYSTYPE}, which was
1261defined at the beginning of the grammar; @pxref{Rpcalc Decls,
1262,Declarations for @code{rpcalc}}.)
bfa74976
RS
1263
1264A token type code of zero is returned if the end-of-file is encountered.
1265(Bison recognizes any nonpositive value as indicating the end of the
1266input.)
1267
1268Here is the code for the lexical analyzer:
1269
1270@example
1271@group
13863333 1272/* Lexical analyzer returns a double floating point
e966383b
PE
1273 number on the stack and the token NUM, or the numeric code
1274 of the character read if not a number. Skips all blanks
bfa74976
RS
1275 and tabs, returns 0 for EOF. */
1276
1277#include <ctype.h>
1278@end group
1279
1280@group
13863333
AD
1281int
1282yylex (void)
bfa74976
RS
1283@{
1284 int c;
1285
1286 /* skip white space */
13863333 1287 while ((c = getchar ()) == ' ' || c == '\t')
bfa74976
RS
1288 ;
1289@end group
1290@group
1291 /* process numbers */
13863333 1292 if (c == '.' || isdigit (c))
bfa74976
RS
1293 @{
1294 ungetc (c, stdin);
1295 scanf ("%lf", &yylval);
1296 return NUM;
1297 @}
1298@end group
1299@group
1300 /* return end-of-file */
13863333 1301 if (c == EOF)
bfa74976
RS
1302 return 0;
1303 /* return single chars */
13863333 1304 return c;
bfa74976
RS
1305@}
1306@end group
1307@end example
1308
342b8b6e 1309@node Rpcalc Main
bfa74976
RS
1310@subsection The Controlling Function
1311@cindex controlling function
1312@cindex main function in simple example
1313
1314In keeping with the spirit of this example, the controlling function is
1315kept to the bare minimum. The only requirement is that it call
1316@code{yyparse} to start the process of parsing.
1317
1318@example
1319@group
13863333
AD
1320int
1321main (void)
bfa74976 1322@{
13863333 1323 return yyparse ();
bfa74976
RS
1324@}
1325@end group
1326@end example
1327
342b8b6e 1328@node Rpcalc Error
bfa74976
RS
1329@subsection The Error Reporting Routine
1330@cindex error reporting routine
1331
1332When @code{yyparse} detects a syntax error, it calls the error reporting
13863333
AD
1333function @code{yyerror} to print an error message (usually but not
1334always @code{"parse error"}). It is up to the programmer to supply
1335@code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
1336here is the definition we will use:
bfa74976
RS
1337
1338@example
1339@group
1340#include <stdio.h>
1341
13863333
AD
1342void
1343yyerror (const char *s) /* Called by yyparse on error */
bfa74976
RS
1344@{
1345 printf ("%s\n", s);
1346@}
1347@end group
1348@end example
1349
1350After @code{yyerror} returns, the Bison parser may recover from the error
1351and continue parsing if the grammar contains a suitable error rule
1352(@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
1353have not written any error rules in this example, so any invalid input will
1354cause the calculator program to exit. This is not clean behavior for a
9ecbd125 1355real calculator, but it is adequate for the first example.
bfa74976 1356
342b8b6e 1357@node Rpcalc Gen
bfa74976
RS
1358@subsection Running Bison to Make the Parser
1359@cindex running Bison (introduction)
1360
ceed8467
AD
1361Before running Bison to produce a parser, we need to decide how to
1362arrange all the source code in one or more source files. For such a
1363simple example, the easiest thing is to put everything in one file. The
1364definitions of @code{yylex}, @code{yyerror} and @code{main} go at the
342b8b6e 1365end, in the epilogue of the file
75f5aaea 1366(@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
bfa74976
RS
1367
1368For a large project, you would probably have several source files, and use
1369@code{make} to arrange to recompile them.
1370
1371With all the source in a single file, you use the following command to
1372convert it into a parser file:
1373
1374@example
1375bison @var{file_name}.y
1376@end example
1377
1378@noindent
1379In this example the file was called @file{rpcalc.y} (for ``Reverse Polish
1380CALCulator''). Bison produces a file named @file{@var{file_name}.tab.c},
1381removing the @samp{.y} from the original file name. The file output by
1382Bison contains the source code for @code{yyparse}. The additional
1383functions in the input file (@code{yylex}, @code{yyerror} and @code{main})
1384are copied verbatim to the output.
1385
342b8b6e 1386@node Rpcalc Compile
bfa74976
RS
1387@subsection Compiling the Parser File
1388@cindex compiling the parser
1389
1390Here is how to compile and run the parser file:
1391
1392@example
1393@group
1394# @r{List files in current directory.}
9edcd895 1395$ @kbd{ls}
bfa74976
RS
1396rpcalc.tab.c rpcalc.y
1397@end group
1398
1399@group
1400# @r{Compile the Bison parser.}
1401# @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
9edcd895 1402$ @kbd{cc rpcalc.tab.c -lm -o rpcalc}
bfa74976
RS
1403@end group
1404
1405@group
1406# @r{List files again.}
9edcd895 1407$ @kbd{ls}
bfa74976
RS
1408rpcalc rpcalc.tab.c rpcalc.y
1409@end group
1410@end example
1411
1412The file @file{rpcalc} now contains the executable code. Here is an
1413example session using @code{rpcalc}.
1414
1415@example
9edcd895
AD
1416$ @kbd{rpcalc}
1417@kbd{4 9 +}
bfa74976 141813
9edcd895 1419@kbd{3 7 + 3 4 5 *+-}
bfa74976 1420-13
9edcd895 1421@kbd{3 7 + 3 4 5 * + - n} @r{Note the unary minus, @samp{n}}
bfa74976 142213
9edcd895 1423@kbd{5 6 / 4 n +}
bfa74976 1424-3.166666667
9edcd895 1425@kbd{3 4 ^} @r{Exponentiation}
bfa74976 142681
9edcd895
AD
1427@kbd{^D} @r{End-of-file indicator}
1428$
bfa74976
RS
1429@end example
1430
342b8b6e 1431@node Infix Calc
bfa74976
RS
1432@section Infix Notation Calculator: @code{calc}
1433@cindex infix notation calculator
1434@cindex @code{calc}
1435@cindex calculator, infix notation
1436
1437We now modify rpcalc to handle infix operators instead of postfix. Infix
1438notation involves the concept of operator precedence and the need for
1439parentheses nested to arbitrary depth. Here is the Bison code for
1440@file{calc.y}, an infix desk-top calculator.
1441
1442@example
1443/* Infix notation calculator--calc */
1444
1445%@{
1446#define YYSTYPE double
1447#include <math.h>
1448%@}
1449
1450/* BISON Declarations */
1451%token NUM
1452%left '-' '+'
1453%left '*' '/'
1454%left NEG /* negation--unary minus */
1455%right '^' /* exponentiation */
1456
1457/* Grammar follows */
1458%%
1459input: /* empty string */
1460 | input line
1461;
1462
1463line: '\n'
1464 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1465;
1466
1467exp: NUM @{ $$ = $1; @}
1468 | exp '+' exp @{ $$ = $1 + $3; @}
1469 | exp '-' exp @{ $$ = $1 - $3; @}
1470 | exp '*' exp @{ $$ = $1 * $3; @}
1471 | exp '/' exp @{ $$ = $1 / $3; @}
1472 | '-' exp %prec NEG @{ $$ = -$2; @}
1473 | exp '^' exp @{ $$ = pow ($1, $3); @}
1474 | '(' exp ')' @{ $$ = $2; @}
1475;
1476%%
1477@end example
1478
1479@noindent
ceed8467
AD
1480The functions @code{yylex}, @code{yyerror} and @code{main} can be the
1481same as before.
bfa74976
RS
1482
1483There are two important new features shown in this code.
1484
1485In the second section (Bison declarations), @code{%left} declares token
1486types and says they are left-associative operators. The declarations
1487@code{%left} and @code{%right} (right associativity) take the place of
1488@code{%token} which is used to declare a token type name without
1489associativity. (These tokens are single-character literals, which
1490ordinarily don't need to be declared. We declare them here to specify
1491the associativity.)
1492
1493Operator precedence is determined by the line ordering of the
1494declarations; the higher the line number of the declaration (lower on
1495the page or screen), the higher the precedence. Hence, exponentiation
1496has the highest precedence, unary minus (@code{NEG}) is next, followed
704a47c4
AD
1497by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator
1498Precedence}.
bfa74976 1499
704a47c4
AD
1500The other important new feature is the @code{%prec} in the grammar
1501section for the unary minus operator. The @code{%prec} simply instructs
1502Bison that the rule @samp{| '-' exp} has the same precedence as
1503@code{NEG}---in this case the next-to-highest. @xref{Contextual
1504Precedence, ,Context-Dependent Precedence}.
bfa74976
RS
1505
1506Here is a sample run of @file{calc.y}:
1507
1508@need 500
1509@example
9edcd895
AD
1510$ @kbd{calc}
1511@kbd{4 + 4.5 - (34/(8*3+-3))}
bfa74976 15126.880952381
9edcd895 1513@kbd{-56 + 2}
bfa74976 1514-54
9edcd895 1515@kbd{3 ^ 2}
bfa74976
RS
15169
1517@end example
1518
342b8b6e 1519@node Simple Error Recovery
bfa74976
RS
1520@section Simple Error Recovery
1521@cindex error recovery, simple
1522
1523Up to this point, this manual has not addressed the issue of @dfn{error
1524recovery}---how to continue parsing after the parser detects a syntax
ceed8467
AD
1525error. All we have handled is error reporting with @code{yyerror}.
1526Recall that by default @code{yyparse} returns after calling
1527@code{yyerror}. This means that an erroneous input line causes the
1528calculator program to exit. Now we show how to rectify this deficiency.
bfa74976
RS
1529
1530The Bison language itself includes the reserved word @code{error}, which
1531may be included in the grammar rules. In the example below it has
1532been added to one of the alternatives for @code{line}:
1533
1534@example
1535@group
1536line: '\n'
1537 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1538 | error '\n' @{ yyerrok; @}
1539;
1540@end group
1541@end example
1542
ceed8467
AD
1543This addition to the grammar allows for simple error recovery in the
1544event of a parse error. If an expression that cannot be evaluated is
1545read, the error will be recognized by the third rule for @code{line},
1546and parsing will continue. (The @code{yyerror} function is still called
1547upon to print its message as well.) The action executes the statement
1548@code{yyerrok}, a macro defined automatically by Bison; its meaning is
1549that error recovery is complete (@pxref{Error Recovery}). Note the
1550difference between @code{yyerrok} and @code{yyerror}; neither one is a
e0c471a9 1551misprint.
bfa74976
RS
1552
1553This form of error recovery deals with syntax errors. There are other
1554kinds of errors; for example, division by zero, which raises an exception
1555signal that is normally fatal. A real calculator program must handle this
1556signal and use @code{longjmp} to return to @code{main} and resume parsing
1557input lines; it would also have to discard the rest of the current line of
1558input. We won't discuss this issue further because it is not specific to
1559Bison programs.
1560
342b8b6e
AD
1561@node Location Tracking Calc
1562@section Location Tracking Calculator: @code{ltcalc}
1563@cindex location tracking calculator
1564@cindex @code{ltcalc}
1565@cindex calculator, location tracking
1566
9edcd895
AD
1567This example extends the infix notation calculator with location
1568tracking. This feature will be used to improve the error messages. For
1569the sake of clarity, this example is a simple integer calculator, since
1570most of the work needed to use locations will be done in the lexical
1571analyser.
342b8b6e
AD
1572
1573@menu
1574* Decls: Ltcalc Decls. Bison and C declarations for ltcalc.
1575* Rules: Ltcalc Rules. Grammar rules for ltcalc, with explanations.
1576* Lexer: Ltcalc Lexer. The lexical analyzer.
1577@end menu
1578
1579@node Ltcalc Decls
1580@subsection Declarations for @code{ltcalc}
1581
9edcd895
AD
1582The C and Bison declarations for the location tracking calculator are
1583the same as the declarations for the infix notation calculator.
342b8b6e
AD
1584
1585@example
1586/* Location tracking calculator. */
1587
1588%@{
1589#define YYSTYPE int
1590#include <math.h>
1591%@}
1592
1593/* Bison declarations. */
1594%token NUM
1595
1596%left '-' '+'
1597%left '*' '/'
1598%left NEG
1599%right '^'
1600
1601%% /* Grammar follows */
1602@end example
1603
9edcd895
AD
1604@noindent
1605Note there are no declarations specific to locations. Defining a data
1606type for storing locations is not needed: we will use the type provided
1607by default (@pxref{Location Type, ,Data Types of Locations}), which is a
1608four member structure with the following integer fields:
1609@code{first_line}, @code{first_column}, @code{last_line} and
1610@code{last_column}.
342b8b6e
AD
1611
1612@node Ltcalc Rules
1613@subsection Grammar Rules for @code{ltcalc}
1614
9edcd895
AD
1615Whether handling locations or not has no effect on the syntax of your
1616language. Therefore, grammar rules for this example will be very close
1617to those of the previous example: we will only modify them to benefit
1618from the new information.
342b8b6e 1619
9edcd895
AD
1620Here, we will use locations to report divisions by zero, and locate the
1621wrong expressions or subexpressions.
342b8b6e
AD
1622
1623@example
1624@group
1625input : /* empty */
1626 | input line
1627;
1628@end group
1629
1630@group
1631line : '\n'
1632 | exp '\n' @{ printf ("%d\n", $1); @}
1633;
1634@end group
1635
1636@group
1637exp : NUM @{ $$ = $1; @}
1638 | exp '+' exp @{ $$ = $1 + $3; @}
1639 | exp '-' exp @{ $$ = $1 - $3; @}
1640 | exp '*' exp @{ $$ = $1 * $3; @}
1641@end group
342b8b6e 1642@group
9edcd895 1643 | exp '/' exp
342b8b6e
AD
1644 @{
1645 if ($3)
1646 $$ = $1 / $3;
1647 else
1648 @{
1649 $$ = 1;
9edcd895
AD
1650 fprintf (stderr, "%d.%d-%d.%d: division by zero",
1651 @@3.first_line, @@3.first_column,
1652 @@3.last_line, @@3.last_column);
342b8b6e
AD
1653 @}
1654 @}
1655@end group
1656@group
1657 | '-' exp %preg NEG @{ $$ = -$2; @}
1658 | exp '^' exp @{ $$ = pow ($1, $3); @}
1659 | '(' exp ')' @{ $$ = $2; @}
1660@end group
1661@end example
1662
1663This code shows how to reach locations inside of semantic actions, by
1664using the pseudo-variables @code{@@@var{n}} for rule components, and the
1665pseudo-variable @code{@@$} for groupings.
1666
9edcd895
AD
1667We don't need to assign a value to @code{@@$}: the output parser does it
1668automatically. By default, before executing the C code of each action,
1669@code{@@$} is set to range from the beginning of @code{@@1} to the end
1670of @code{@@@var{n}}, for a rule with @var{n} components. This behavior
1671can be redefined (@pxref{Location Default Action, , Default Action for
1672Locations}), and for very specific rules, @code{@@$} can be computed by
1673hand.
342b8b6e
AD
1674
1675@node Ltcalc Lexer
1676@subsection The @code{ltcalc} Lexical Analyzer.
1677
9edcd895
AD
1678Until now, we relied on Bison's defaults to enable location
1679tracking. The next step is to rewrite the lexical analyser, and make it
1680able to feed the parser with the token locations, as it already does for
1681semantic values.
342b8b6e 1682
9edcd895
AD
1683To this end, we must take into account every single character of the
1684input text, to avoid the computed locations of being fuzzy or wrong:
342b8b6e
AD
1685
1686@example
1687@group
1688int
1689yylex (void)
1690@{
1691 int c;
1692
1693 /* skip white space */
1694 while ((c = getchar ()) == ' ' || c == '\t')
1695 ++yylloc.last_column;
1696
1697 /* step */
1698 yylloc.first_line = yylloc.last_line;
1699 yylloc.first_column = yylloc.last_column;
1700@end group
1701
1702@group
1703 /* process numbers */
1704 if (isdigit (c))
1705 @{
1706 yylval = c - '0';
1707 ++yylloc.last_column;
1708 while (isdigit (c = getchar ()))
1709 @{
1710 ++yylloc.last_column;
1711 yylval = yylval * 10 + c - '0';
1712 @}
1713 ungetc (c, stdin);
1714 return NUM;
1715 @}
1716@end group
1717
1718 /* return end-of-file */
1719 if (c == EOF)
1720 return 0;
1721
1722 /* return single chars and update location */
1723 if (c == '\n')
1724 @{
1725 ++yylloc.last_line;
1726 yylloc.last_column = 0;
1727 @}
1728 else
1729 ++yylloc.last_column;
1730 return c;
1731@}
1732@end example
1733
9edcd895
AD
1734Basically, the lexical analyzer performs the same processing as before:
1735it skips blanks and tabs, and reads numbers or single-character tokens.
1736In addition, it updates @code{yylloc}, the global variable (of type
1737@code{YYLTYPE}) containing the token's location.
342b8b6e 1738
9edcd895
AD
1739Now, each time this function returns a token, the parser has its number
1740as well as its semantic value, and its location in the text. The last
1741needed change is to initialize @code{yylloc}, for example in the
1742controlling function:
342b8b6e
AD
1743
1744@example
9edcd895 1745@group
342b8b6e
AD
1746int
1747main (void)
1748@{
1749 yylloc.first_line = yylloc.last_line = 1;
1750 yylloc.first_column = yylloc.last_column = 0;
1751 return yyparse ();
1752@}
9edcd895 1753@end group
342b8b6e
AD
1754@end example
1755
9edcd895
AD
1756Remember that computing locations is not a matter of syntax. Every
1757character must be associated to a location update, whether it is in
1758valid input, in comments, in literal strings, and so on.
342b8b6e
AD
1759
1760@node Multi-function Calc
bfa74976
RS
1761@section Multi-Function Calculator: @code{mfcalc}
1762@cindex multi-function calculator
1763@cindex @code{mfcalc}
1764@cindex calculator, multi-function
1765
1766Now that the basics of Bison have been discussed, it is time to move on to
1767a more advanced problem. The above calculators provided only five
1768functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
1769be nice to have a calculator that provides other mathematical functions such
1770as @code{sin}, @code{cos}, etc.
1771
1772It is easy to add new operators to the infix calculator as long as they are
1773only single-character literals. The lexical analyzer @code{yylex} passes
9ecbd125 1774back all nonnumber characters as tokens, so new grammar rules suffice for
bfa74976
RS
1775adding a new operator. But we want something more flexible: built-in
1776functions whose syntax has this form:
1777
1778@example
1779@var{function_name} (@var{argument})
1780@end example
1781
1782@noindent
1783At the same time, we will add memory to the calculator, by allowing you
1784to create named variables, store values in them, and use them later.
1785Here is a sample session with the multi-function calculator:
1786
1787@example
9edcd895
AD
1788$ @kbd{mfcalc}
1789@kbd{pi = 3.141592653589}
bfa74976 17903.1415926536
9edcd895 1791@kbd{sin(pi)}
bfa74976 17920.0000000000
9edcd895 1793@kbd{alpha = beta1 = 2.3}
bfa74976 17942.3000000000
9edcd895 1795@kbd{alpha}
bfa74976 17962.3000000000
9edcd895 1797@kbd{ln(alpha)}
bfa74976 17980.8329091229
9edcd895 1799@kbd{exp(ln(beta1))}
bfa74976 18002.3000000000
9edcd895 1801$
bfa74976
RS
1802@end example
1803
1804Note that multiple assignment and nested function calls are permitted.
1805
1806@menu
1807* Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
1808* Rules: Mfcalc Rules. Grammar rules for the calculator.
1809* Symtab: Mfcalc Symtab. Symbol table management subroutines.
1810@end menu
1811
342b8b6e 1812@node Mfcalc Decl
bfa74976
RS
1813@subsection Declarations for @code{mfcalc}
1814
1815Here are the C and Bison declarations for the multi-function calculator.
1816
1817@smallexample
1818%@{
1819#include <math.h> /* For math functions, cos(), sin(), etc. */
1820#include "calc.h" /* Contains definition of `symrec' */
1821%@}
1822%union @{
1823double val; /* For returning numbers. */
1824symrec *tptr; /* For returning symbol-table pointers */
1825@}
1826
1827%token <val> NUM /* Simple double precision number */
1828%token <tptr> VAR FNCT /* Variable and Function */
1829%type <val> exp
1830
1831%right '='
1832%left '-' '+'
1833%left '*' '/'
1834%left NEG /* Negation--unary minus */
1835%right '^' /* Exponentiation */
1836
1837/* Grammar follows */
1838
1839%%
1840@end smallexample
1841
1842The above grammar introduces only two new features of the Bison language.
1843These features allow semantic values to have various data types
1844(@pxref{Multiple Types, ,More Than One Value Type}).
1845
1846The @code{%union} declaration specifies the entire list of possible types;
1847this is instead of defining @code{YYSTYPE}. The allowable types are now
1848double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
1849the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
1850
1851Since values can now have various types, it is necessary to associate a
1852type with each grammar symbol whose semantic value is used. These symbols
1853are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
1854declarations are augmented with information about their data type (placed
1855between angle brackets).
1856
704a47c4
AD
1857The Bison construct @code{%type} is used for declaring nonterminal
1858symbols, just as @code{%token} is used for declaring token types. We
1859have not used @code{%type} before because nonterminal symbols are
1860normally declared implicitly by the rules that define them. But
1861@code{exp} must be declared explicitly so we can specify its value type.
1862@xref{Type Decl, ,Nonterminal Symbols}.
bfa74976 1863
342b8b6e 1864@node Mfcalc Rules
bfa74976
RS
1865@subsection Grammar Rules for @code{mfcalc}
1866
1867Here are the grammar rules for the multi-function calculator.
1868Most of them are copied directly from @code{calc}; three rules,
1869those which mention @code{VAR} or @code{FNCT}, are new.
1870
1871@smallexample
1872input: /* empty */
1873 | input line
1874;
1875
1876line:
1877 '\n'
1878 | exp '\n' @{ printf ("\t%.10g\n", $1); @}
1879 | error '\n' @{ yyerrok; @}
1880;
1881
1882exp: NUM @{ $$ = $1; @}
1883 | VAR @{ $$ = $1->value.var; @}
1884 | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
1885 | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
1886 | exp '+' exp @{ $$ = $1 + $3; @}
1887 | exp '-' exp @{ $$ = $1 - $3; @}
1888 | exp '*' exp @{ $$ = $1 * $3; @}
1889 | exp '/' exp @{ $$ = $1 / $3; @}
1890 | '-' exp %prec NEG @{ $$ = -$2; @}
1891 | exp '^' exp @{ $$ = pow ($1, $3); @}
1892 | '(' exp ')' @{ $$ = $2; @}
1893;
1894/* End of grammar */
1895%%
1896@end smallexample
1897
342b8b6e 1898@node Mfcalc Symtab
bfa74976
RS
1899@subsection The @code{mfcalc} Symbol Table
1900@cindex symbol table example
1901
1902The multi-function calculator requires a symbol table to keep track of the
1903names and meanings of variables and functions. This doesn't affect the
1904grammar rules (except for the actions) or the Bison declarations, but it
1905requires some additional C functions for support.
1906
1907The symbol table itself consists of a linked list of records. Its
1908definition, which is kept in the header @file{calc.h}, is as follows. It
1909provides for either functions or variables to be placed in the table.
1910
1911@smallexample
1912@group
32dfccf8
AD
1913/* Fonctions type. */
1914typedef double (*func_t) (double);
1915
bfa74976
RS
1916/* Data type for links in the chain of symbols. */
1917struct symrec
1918@{
1919 char *name; /* name of symbol */
1920 int type; /* type of symbol: either VAR or FNCT */
32dfccf8
AD
1921 union
1922 @{
1923 double var; /* value of a VAR */
1924 func_t fnctptr; /* value of a FNCT */
bfa74976
RS
1925 @} value;
1926 struct symrec *next; /* link field */
1927@};
1928@end group
1929
1930@group
1931typedef struct symrec symrec;
1932
1933/* The symbol table: a chain of `struct symrec'. */
1934extern symrec *sym_table;
1935
32dfccf8
AD
1936symrec *putsym (const char *, func_t);
1937symrec *getsym (const char *);
bfa74976
RS
1938@end group
1939@end smallexample
1940
1941The new version of @code{main} includes a call to @code{init_table}, a
1942function that initializes the symbol table. Here it is, and
1943@code{init_table} as well:
1944
1945@smallexample
1946@group
1947#include <stdio.h>
1948
13863333
AD
1949int
1950main (void)
bfa74976
RS
1951@{
1952 init_table ();
13863333 1953 return yyparse ();
bfa74976
RS
1954@}
1955@end group
1956
1957@group
13863333
AD
1958void
1959yyerror (const char *s) /* Called by yyparse on error */
bfa74976
RS
1960@{
1961 printf ("%s\n", s);
1962@}
1963
1964struct init
1965@{
1966 char *fname;
32dfccf8 1967 double (*fnct)(double);
bfa74976
RS
1968@};
1969@end group
1970
1971@group
13863333
AD
1972struct init arith_fncts[] =
1973@{
32dfccf8
AD
1974 "sin", sin,
1975 "cos", cos,
13863333 1976 "atan", atan,
32dfccf8
AD
1977 "ln", log,
1978 "exp", exp,
13863333
AD
1979 "sqrt", sqrt,
1980 0, 0
1981@};
bfa74976
RS
1982
1983/* The symbol table: a chain of `struct symrec'. */
32dfccf8 1984symrec *sym_table = (symrec *) 0;
bfa74976
RS
1985@end group
1986
1987@group
13863333
AD
1988/* Put arithmetic functions in table. */
1989void
1990init_table (void)
bfa74976
RS
1991@{
1992 int i;
1993 symrec *ptr;
1994 for (i = 0; arith_fncts[i].fname != 0; i++)
1995 @{
1996 ptr = putsym (arith_fncts[i].fname, FNCT);
1997 ptr->value.fnctptr = arith_fncts[i].fnct;
1998 @}
1999@}
2000@end group
2001@end smallexample
2002
2003By simply editing the initialization list and adding the necessary include
2004files, you can add additional functions to the calculator.
2005
2006Two important functions allow look-up and installation of symbols in the
2007symbol table. The function @code{putsym} is passed a name and the type
2008(@code{VAR} or @code{FNCT}) of the object to be installed. The object is
2009linked to the front of the list, and a pointer to the object is returned.
2010The function @code{getsym} is passed the name of the symbol to look up. If
2011found, a pointer to that symbol is returned; otherwise zero is returned.
2012
2013@smallexample
2014symrec *
13863333 2015putsym (char *sym_name, int sym_type)
bfa74976
RS
2016@{
2017 symrec *ptr;
2018 ptr = (symrec *) malloc (sizeof (symrec));
2019 ptr->name = (char *) malloc (strlen (sym_name) + 1);
2020 strcpy (ptr->name,sym_name);
2021 ptr->type = sym_type;
2022 ptr->value.var = 0; /* set value to 0 even if fctn. */
2023 ptr->next = (struct symrec *)sym_table;
2024 sym_table = ptr;
2025 return ptr;
2026@}
2027
2028symrec *
13863333 2029getsym (const char *sym_name)
bfa74976
RS
2030@{
2031 symrec *ptr;
2032 for (ptr = sym_table; ptr != (symrec *) 0;
2033 ptr = (symrec *)ptr->next)
2034 if (strcmp (ptr->name,sym_name) == 0)
2035 return ptr;
2036 return 0;
2037@}
2038@end smallexample
2039
2040The function @code{yylex} must now recognize variables, numeric values, and
2041the single-character arithmetic operators. Strings of alphanumeric
14ded682 2042characters with a leading non-digit are recognized as either variables or
bfa74976
RS
2043functions depending on what the symbol table says about them.
2044
2045The string is passed to @code{getsym} for look up in the symbol table. If
2046the name appears in the table, a pointer to its location and its type
2047(@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
2048already in the table, then it is installed as a @code{VAR} using
2049@code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
e0c471a9 2050returned to @code{yyparse}.
bfa74976
RS
2051
2052No change is needed in the handling of numeric values and arithmetic
2053operators in @code{yylex}.
2054
2055@smallexample
2056@group
2057#include <ctype.h>
13863333
AD
2058
2059int
2060yylex (void)
bfa74976
RS
2061@{
2062 int c;
2063
2064 /* Ignore whitespace, get first nonwhite character. */
2065 while ((c = getchar ()) == ' ' || c == '\t');
2066
2067 if (c == EOF)
2068 return 0;
2069@end group
2070
2071@group
2072 /* Char starts a number => parse the number. */
2073 if (c == '.' || isdigit (c))
2074 @{
2075 ungetc (c, stdin);
2076 scanf ("%lf", &yylval.val);
2077 return NUM;
2078 @}
2079@end group
2080
2081@group
2082 /* Char starts an identifier => read the name. */
2083 if (isalpha (c))
2084 @{
2085 symrec *s;
2086 static char *symbuf = 0;
2087 static int length = 0;
2088 int i;
2089@end group
2090
2091@group
2092 /* Initially make the buffer long enough
2093 for a 40-character symbol name. */
2094 if (length == 0)
2095 length = 40, symbuf = (char *)malloc (length + 1);
2096
2097 i = 0;
2098 do
2099@end group
2100@group
2101 @{
2102 /* If buffer is full, make it bigger. */
2103 if (i == length)
2104 @{
2105 length *= 2;
2106 symbuf = (char *)realloc (symbuf, length + 1);
2107 @}
2108 /* Add this character to the buffer. */
2109 symbuf[i++] = c;
2110 /* Get another character. */
2111 c = getchar ();
2112 @}
2113@end group
2114@group
2115 while (c != EOF && isalnum (c));
2116
2117 ungetc (c, stdin);
2118 symbuf[i] = '\0';
2119@end group
2120
2121@group
2122 s = getsym (symbuf);
2123 if (s == 0)
2124 s = putsym (symbuf, VAR);
2125 yylval.tptr = s;
2126 return s->type;
2127 @}
2128
2129 /* Any other character is a token by itself. */
2130 return c;
2131@}
2132@end group
2133@end smallexample
2134
2135This program is both powerful and flexible. You may easily add new
704a47c4
AD
2136functions, and it is a simple job to modify this code to install
2137predefined variables such as @code{pi} or @code{e} as well.
bfa74976 2138
342b8b6e 2139@node Exercises
bfa74976
RS
2140@section Exercises
2141@cindex exercises
2142
2143@enumerate
2144@item
2145Add some new functions from @file{math.h} to the initialization list.
2146
2147@item
2148Add another array that contains constants and their values. Then
2149modify @code{init_table} to add these constants to the symbol table.
2150It will be easiest to give the constants type @code{VAR}.
2151
2152@item
2153Make the program report an error if the user refers to an
2154uninitialized variable in any way except to store a value in it.
2155@end enumerate
2156
342b8b6e 2157@node Grammar File
bfa74976
RS
2158@chapter Bison Grammar Files
2159
2160Bison takes as input a context-free grammar specification and produces a
2161C-language function that recognizes correct instances of the grammar.
2162
2163The Bison grammar input file conventionally has a name ending in @samp{.y}.
234a3be3 2164@xref{Invocation, ,Invoking Bison}.
bfa74976
RS
2165
2166@menu
2167* Grammar Outline:: Overall layout of the grammar file.
2168* Symbols:: Terminal and nonterminal symbols.
2169* Rules:: How to write grammar rules.
2170* Recursion:: Writing recursive rules.
2171* Semantics:: Semantic values and actions.
847bf1f5 2172* Locations:: Locations and actions.
bfa74976
RS
2173* Declarations:: All kinds of Bison declarations are described here.
2174* Multiple Parsers:: Putting more than one Bison parser in one program.
2175@end menu
2176
342b8b6e 2177@node Grammar Outline
bfa74976
RS
2178@section Outline of a Bison Grammar
2179
2180A Bison grammar file has four main sections, shown here with the
2181appropriate delimiters:
2182
2183@example
2184%@{
75f5aaea 2185@var{Prologue}
bfa74976
RS
2186%@}
2187
2188@var{Bison declarations}
2189
2190%%
2191@var{Grammar rules}
2192%%
2193
75f5aaea 2194@var{Epilogue}
bfa74976
RS
2195@end example
2196
2197Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
2198
2199@menu
75f5aaea 2200* Prologue:: Syntax and usage of the prologue.
bfa74976
RS
2201* Bison Declarations:: Syntax and usage of the Bison declarations section.
2202* Grammar Rules:: Syntax and usage of the grammar rules section.
75f5aaea 2203* Epilogue:: Syntax and usage of the epilogue.
bfa74976
RS
2204@end menu
2205
75f5aaea
MA
2206@node Prologue, Bison Declarations, , Grammar Outline
2207@subsection The prologue
2208@cindex declarations section
2209@cindex Prologue
2210@cindex declarations
bfa74976 2211
08e49d20 2212The @var{Prologue} section contains macro definitions and
bfa74976
RS
2213declarations of functions and variables that are used in the actions in the
2214grammar rules. These are copied to the beginning of the parser file so
2215that they precede the definition of @code{yyparse}. You can use
2216@samp{#include} to get the declarations from a header file. If you don't
2217need any C declarations, you may omit the @samp{%@{} and @samp{%@}}
2218delimiters that bracket this section.
2219
c732d2c6
AD
2220You may have more than one @var{Prologue} section, intermixed with the
2221@var{Bison declarations}. This allows you to have C and Bison
2222declarations that refer to each other. For example, the @code{%union}
2223declaration may use types defined in a header file, and you may wish to
2224prototype functions that take arguments of type @code{YYSTYPE}. This
2225can be done with two @var{Prologue} blocks, one before and one after the
2226@code{%union} declaration.
2227
2228@smallexample
2229%@{
2230#include <stdio.h>
2231#include "ptypes.h"
2232%@}
2233
2234%union @{
2235 long n;
2236 tree t; /* @r{@code{tree} is defined in @file{ptypes.h}.} */
2237@}
2238
2239%@{
2240static void yyprint(FILE *, int, YYSTYPE);
2241#define YYPRINT(F, N, L) yyprint(F, N, L)
2242%@}
2243
2244@dots{}
2245@end smallexample
2246
342b8b6e 2247@node Bison Declarations
bfa74976
RS
2248@subsection The Bison Declarations Section
2249@cindex Bison declarations (introduction)
2250@cindex declarations, Bison (introduction)
2251
2252The @var{Bison declarations} section contains declarations that define
2253terminal and nonterminal symbols, specify precedence, and so on.
2254In some simple grammars you may not need any declarations.
2255@xref{Declarations, ,Bison Declarations}.
2256
342b8b6e 2257@node Grammar Rules
bfa74976
RS
2258@subsection The Grammar Rules Section
2259@cindex grammar rules section
2260@cindex rules section for grammar
2261
2262The @dfn{grammar rules} section contains one or more Bison grammar
2263rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
2264
2265There must always be at least one grammar rule, and the first
2266@samp{%%} (which precedes the grammar rules) may never be omitted even
2267if it is the first thing in the file.
2268
75f5aaea
MA
2269@node Epilogue, , Grammar Rules, Grammar Outline
2270@subsection The epilogue
bfa74976 2271@cindex additional C code section
75f5aaea 2272@cindex epilogue
bfa74976
RS
2273@cindex C code, section for additional
2274
08e49d20
PE
2275The @var{Epilogue} is copied verbatim to the end of the parser file, just as
2276the @var{Prologue} is copied to the beginning. This is the most convenient
342b8b6e
AD
2277place to put anything that you want to have in the parser file but which need
2278not come before the definition of @code{yyparse}. For example, the
2279definitions of @code{yylex} and @code{yyerror} often go here.
75f5aaea 2280@xref{Interface, ,Parser C-Language Interface}.
bfa74976
RS
2281
2282If the last section is empty, you may omit the @samp{%%} that separates it
2283from the grammar rules.
2284
2285The Bison parser itself contains many static variables whose names start
2286with @samp{yy} and many macros whose names start with @samp{YY}. It is a
2287good idea to avoid using any such names (except those documented in this
75f5aaea 2288manual) in the epilogue of the grammar file.
bfa74976 2289
342b8b6e 2290@node Symbols
bfa74976
RS
2291@section Symbols, Terminal and Nonterminal
2292@cindex nonterminal symbol
2293@cindex terminal symbol
2294@cindex token type
2295@cindex symbol
2296
2297@dfn{Symbols} in Bison grammars represent the grammatical classifications
2298of the language.
2299
2300A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
2301class of syntactically equivalent tokens. You use the symbol in grammar
2302rules to mean that a token in that class is allowed. The symbol is
2303represented in the Bison parser by a numeric code, and the @code{yylex}
2304function returns a token type code to indicate what kind of token has been
2305read. You don't need to know what the code value is; you can use the
2306symbol to stand for it.
2307
2308A @dfn{nonterminal symbol} stands for a class of syntactically equivalent
2309groupings. The symbol name is used in writing grammar rules. By convention,
2310it should be all lower case.
2311
2312Symbol names can contain letters, digits (not at the beginning),
2313underscores and periods. Periods make sense only in nonterminals.
2314
931c7513 2315There are three ways of writing terminal symbols in the grammar:
bfa74976
RS
2316
2317@itemize @bullet
2318@item
2319A @dfn{named token type} is written with an identifier, like an
2320identifier in C. By convention, it should be all upper case. Each
2321such name must be defined with a Bison declaration such as
2322@code{%token}. @xref{Token Decl, ,Token Type Names}.
2323
2324@item
2325@cindex character token
2326@cindex literal token
2327@cindex single-character literal
931c7513
RS
2328A @dfn{character token type} (or @dfn{literal character token}) is
2329written in the grammar using the same syntax used in C for character
2330constants; for example, @code{'+'} is a character token type. A
2331character token type doesn't need to be declared unless you need to
2332specify its semantic value data type (@pxref{Value Type, ,Data Types of
2333Semantic Values}), associativity, or precedence (@pxref{Precedence,
2334,Operator Precedence}).
bfa74976
RS
2335
2336By convention, a character token type is used only to represent a
2337token that consists of that particular character. Thus, the token
2338type @code{'+'} is used to represent the character @samp{+} as a
2339token. Nothing enforces this convention, but if you depart from it,
2340your program will confuse other readers.
2341
2342All the usual escape sequences used in character literals in C can be
2343used in Bison as well, but you must not use the null character as a
e966383b 2344character literal because its numeric code, zero, is the code @code{yylex}
931c7513
RS
2345returns for end-of-input (@pxref{Calling Convention, ,Calling Convention
2346for @code{yylex}}).
2347
2348@item
2349@cindex string token
2350@cindex literal string token
9ecbd125 2351@cindex multicharacter literal
931c7513
RS
2352A @dfn{literal string token} is written like a C string constant; for
2353example, @code{"<="} is a literal string token. A literal string token
2354doesn't need to be declared unless you need to specify its semantic
14ded682 2355value data type (@pxref{Value Type}), associativity, or precedence
931c7513
RS
2356(@pxref{Precedence}).
2357
2358You can associate the literal string token with a symbolic name as an
2359alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token
2360Declarations}). If you don't do that, the lexical analyzer has to
2361retrieve the token number for the literal string token from the
2362@code{yytname} table (@pxref{Calling Convention}).
2363
2364@strong{WARNING}: literal string tokens do not work in Yacc.
2365
2366By convention, a literal string token is used only to represent a token
2367that consists of that particular string. Thus, you should use the token
2368type @code{"<="} to represent the string @samp{<=} as a token. Bison
9ecbd125 2369does not enforce this convention, but if you depart from it, people who
931c7513
RS
2370read your program will be confused.
2371
2372All the escape sequences used in string literals in C can be used in
2373Bison as well. A literal string token must contain two or more
2374characters; for a token containing just one character, use a character
2375token (see above).
bfa74976
RS
2376@end itemize
2377
2378How you choose to write a terminal symbol has no effect on its
2379grammatical meaning. That depends only on where it appears in rules and
2380on when the parser function returns that symbol.
2381
2382The value returned by @code{yylex} is always one of the terminal symbols
2383(or 0 for end-of-input). Whichever way you write the token type in the
2384grammar rules, you write it the same way in the definition of @code{yylex}.
e966383b 2385The numeric code for a character token type is simply the numeric code of
bfa74976
RS
2386the character, so @code{yylex} can use the identical character constant to
2387generate the requisite code. Each named token type becomes a C macro in
2388the parser file, so @code{yylex} can use the name to stand for the code.
13863333 2389(This is why periods don't make sense in terminal symbols.)
bfa74976
RS
2390@xref{Calling Convention, ,Calling Convention for @code{yylex}}.
2391
2392If @code{yylex} is defined in a separate file, you need to arrange for the
2393token-type macro definitions to be available there. Use the @samp{-d}
2394option when you run Bison, so that it will write these macro definitions
2395into a separate header file @file{@var{name}.tab.h} which you can include
2396in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
2397
e966383b
PE
2398The @code{yylex} function must use the same character set and encoding
2399that was used by Bison. For example, if you run Bison in an
2400@sc{ascii} environment, but then compile and run the resulting program
2401in an environment that uses an incompatible character set like
2402@sc{ebcdic}, the resulting program will probably not work because the
2403tables generated by Bison will assume @sc{ascii} numeric values for
2404character tokens. Portable grammars should avoid non-@sc{ascii}
2405character tokens, as implementations in practice often use different
2406and incompatible extensions in this area. However, it is standard
2407practice for software distributions to contain C source files that
2408were generated by Bison in an @sc{ascii} environment, so installers on
2409platforms that are incompatible with @sc{ascii} must rebuild those
2410files before compiling them.
2411
bfa74976
RS
2412The symbol @code{error} is a terminal symbol reserved for error recovery
2413(@pxref{Error Recovery}); you shouldn't use it for any other purpose.
23c5a174
AD
2414In particular, @code{yylex} should never return this value. The default
2415value of the error token is 256, unless you explicitly assigned 256 to
2416one of your tokens with a @code{%token} declaration.
bfa74976 2417
342b8b6e 2418@node Rules
bfa74976
RS
2419@section Syntax of Grammar Rules
2420@cindex rule syntax
2421@cindex grammar rule syntax
2422@cindex syntax of grammar rules
2423
2424A Bison grammar rule has the following general form:
2425
2426@example
e425e872 2427@group
bfa74976
RS
2428@var{result}: @var{components}@dots{}
2429 ;
e425e872 2430@end group
bfa74976
RS
2431@end example
2432
2433@noindent
9ecbd125 2434where @var{result} is the nonterminal symbol that this rule describes,
bfa74976 2435and @var{components} are various terminal and nonterminal symbols that
13863333 2436are put together by this rule (@pxref{Symbols}).
bfa74976
RS
2437
2438For example,
2439
2440@example
2441@group
2442exp: exp '+' exp
2443 ;
2444@end group
2445@end example
2446
2447@noindent
2448says that two groupings of type @code{exp}, with a @samp{+} token in between,
2449can be combined into a larger grouping of type @code{exp}.
2450
2451Whitespace in rules is significant only to separate symbols. You can add
2452extra whitespace as you wish.
2453
2454Scattered among the components can be @var{actions} that determine
2455the semantics of the rule. An action looks like this:
2456
2457@example
2458@{@var{C statements}@}
2459@end example
2460
2461@noindent
2462Usually there is only one action and it follows the components.
2463@xref{Actions}.
2464
2465@findex |
2466Multiple rules for the same @var{result} can be written separately or can
2467be joined with the vertical-bar character @samp{|} as follows:
2468
2469@ifinfo
2470@example
2471@var{result}: @var{rule1-components}@dots{}
2472 | @var{rule2-components}@dots{}
2473 @dots{}
2474 ;
2475@end example
2476@end ifinfo
2477@iftex
2478@example
2479@group
2480@var{result}: @var{rule1-components}@dots{}
2481 | @var{rule2-components}@dots{}
2482 @dots{}
2483 ;
2484@end group
2485@end example
2486@end iftex
2487
2488@noindent
2489They are still considered distinct rules even when joined in this way.
2490
2491If @var{components} in a rule is empty, it means that @var{result} can
2492match the empty string. For example, here is how to define a
2493comma-separated sequence of zero or more @code{exp} groupings:
2494
2495@example
2496@group
2497expseq: /* empty */
2498 | expseq1
2499 ;
2500@end group
2501
2502@group
2503expseq1: exp
2504 | expseq1 ',' exp
2505 ;
2506@end group
2507@end example
2508
2509@noindent
2510It is customary to write a comment @samp{/* empty */} in each rule
2511with no components.
2512
342b8b6e 2513@node Recursion
bfa74976
RS
2514@section Recursive Rules
2515@cindex recursive rule
2516
2517A rule is called @dfn{recursive} when its @var{result} nonterminal appears
2518also on its right hand side. Nearly all Bison grammars need to use
2519recursion, because that is the only way to define a sequence of any number
9ecbd125
JT
2520of a particular thing. Consider this recursive definition of a
2521comma-separated sequence of one or more expressions:
bfa74976
RS
2522
2523@example
2524@group
2525expseq1: exp
2526 | expseq1 ',' exp
2527 ;
2528@end group
2529@end example
2530
2531@cindex left recursion
2532@cindex right recursion
2533@noindent
2534Since the recursive use of @code{expseq1} is the leftmost symbol in the
2535right hand side, we call this @dfn{left recursion}. By contrast, here
2536the same construct is defined using @dfn{right recursion}:
2537
2538@example
2539@group
2540expseq1: exp
2541 | exp ',' expseq1
2542 ;
2543@end group
2544@end example
2545
2546@noindent
ec3bc396
AD
2547Any kind of sequence can be defined using either left recursion or right
2548recursion, but you should always use left recursion, because it can
2549parse a sequence of any number of elements with bounded stack space.
2550Right recursion uses up space on the Bison stack in proportion to the
2551number of elements in the sequence, because all the elements must be
2552shifted onto the stack before the rule can be applied even once.
2553@xref{Algorithm, ,The Bison Parser Algorithm}, for further explanation
2554of this.
bfa74976
RS
2555
2556@cindex mutual recursion
2557@dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
2558rule does not appear directly on its right hand side, but does appear
2559in rules for other nonterminals which do appear on its right hand
13863333 2560side.
bfa74976
RS
2561
2562For example:
2563
2564@example
2565@group
2566expr: primary
2567 | primary '+' primary
2568 ;
2569@end group
2570
2571@group
2572primary: constant
2573 | '(' expr ')'
2574 ;
2575@end group
2576@end example
2577
2578@noindent
2579defines two mutually-recursive nonterminals, since each refers to the
2580other.
2581
342b8b6e 2582@node Semantics
bfa74976
RS
2583@section Defining Language Semantics
2584@cindex defining language semantics
13863333 2585@cindex language semantics, defining
bfa74976
RS
2586
2587The grammar rules for a language determine only the syntax. The semantics
2588are determined by the semantic values associated with various tokens and
2589groupings, and by the actions taken when various groupings are recognized.
2590
2591For example, the calculator calculates properly because the value
2592associated with each expression is the proper number; it adds properly
2593because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
2594the numbers associated with @var{x} and @var{y}.
2595
2596@menu
2597* Value Type:: Specifying one data type for all semantic values.
2598* Multiple Types:: Specifying several alternative data types.
2599* Actions:: An action is the semantic definition of a grammar rule.
2600* Action Types:: Specifying data types for actions to operate on.
2601* Mid-Rule Actions:: Most actions go at the end of a rule.
2602 This says when, why and how to use the exceptional
2603 action in the middle of a rule.
2604@end menu
2605
342b8b6e 2606@node Value Type
bfa74976
RS
2607@subsection Data Types of Semantic Values
2608@cindex semantic value type
2609@cindex value type, semantic
2610@cindex data types of semantic values
2611@cindex default data type
2612
2613In a simple program it may be sufficient to use the same data type for
2614the semantic values of all language constructs. This was true in the
1964ad8c
AD
2615RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish
2616Notation Calculator}).
bfa74976
RS
2617
2618Bison's default is to use type @code{int} for all semantic values. To
2619specify some other type, define @code{YYSTYPE} as a macro, like this:
2620
2621@example
2622#define YYSTYPE double
2623@end example
2624
2625@noindent
342b8b6e 2626This macro definition must go in the prologue of the grammar file
75f5aaea 2627(@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
bfa74976 2628
342b8b6e 2629@node Multiple Types
bfa74976
RS
2630@subsection More Than One Value Type
2631
2632In most programs, you will need different data types for different kinds
2633of tokens and groupings. For example, a numeric constant may need type
2634@code{int} or @code{long}, while a string constant needs type @code{char *},
2635and an identifier might need a pointer to an entry in the symbol table.
2636
2637To use more than one data type for semantic values in one parser, Bison
2638requires you to do two things:
2639
2640@itemize @bullet
2641@item
2642Specify the entire collection of possible data types, with the
704a47c4
AD
2643@code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of
2644Value Types}).
bfa74976
RS
2645
2646@item
14ded682
AD
2647Choose one of those types for each symbol (terminal or nonterminal) for
2648which semantic values are used. This is done for tokens with the
2649@code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names})
2650and for groupings with the @code{%type} Bison declaration (@pxref{Type
2651Decl, ,Nonterminal Symbols}).
bfa74976
RS
2652@end itemize
2653
342b8b6e 2654@node Actions
bfa74976
RS
2655@subsection Actions
2656@cindex action
2657@vindex $$
2658@vindex $@var{n}
2659
2660An action accompanies a syntactic rule and contains C code to be executed
2661each time an instance of that rule is recognized. The task of most actions
2662is to compute a semantic value for the grouping built by the rule from the
2663semantic values associated with tokens or smaller groupings.
2664
2665An action consists of C statements surrounded by braces, much like a
704a47c4
AD
2666compound statement in C. It can be placed at any position in the rule;
2667it is executed at that position. Most rules have just one action at the
2668end of the rule, following all the components. Actions in the middle of
2669a rule are tricky and used only for special purposes (@pxref{Mid-Rule
2670Actions, ,Actions in Mid-Rule}).
bfa74976
RS
2671
2672The C code in an action can refer to the semantic values of the components
2673matched by the rule with the construct @code{$@var{n}}, which stands for
2674the value of the @var{n}th component. The semantic value for the grouping
2675being constructed is @code{$$}. (Bison translates both of these constructs
2676into array element references when it copies the actions into the parser
2677file.)
2678
2679Here is a typical example:
2680
2681@example
2682@group
2683exp: @dots{}
2684 | exp '+' exp
2685 @{ $$ = $1 + $3; @}
2686@end group
2687@end example
2688
2689@noindent
2690This rule constructs an @code{exp} from two smaller @code{exp} groupings
2691connected by a plus-sign token. In the action, @code{$1} and @code{$3}
2692refer to the semantic values of the two component @code{exp} groupings,
2693which are the first and third symbols on the right hand side of the rule.
2694The sum is stored into @code{$$} so that it becomes the semantic value of
2695the addition-expression just recognized by the rule. If there were a
2696useful semantic value associated with the @samp{+} token, it could be
e0c471a9 2697referred to as @code{$2}.
bfa74976 2698
3ded9a63
AD
2699Note that the vertical-bar character @samp{|} is really a rule
2700separator, and actions are attached to a single rule. This is a
2701difference with tools like Flex, for which @samp{|} stands for either
2702``or'', or ``the same action as that of the next rule''. In the
2703following example, the action is triggered only when @samp{b} is found:
2704
2705@example
2706@group
2707a-or-b: 'a'|'b' @{ a_or_b_found = 1; @};
2708@end group
2709@end example
2710
bfa74976
RS
2711@cindex default action
2712If you don't specify an action for a rule, Bison supplies a default:
2713@w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule becomes
2714the value of the whole rule. Of course, the default rule is valid only
2715if the two data types match. There is no meaningful default action for
2716an empty rule; every empty rule must have an explicit action unless the
2717rule's value does not matter.
2718
2719@code{$@var{n}} with @var{n} zero or negative is allowed for reference
2720to tokens and groupings on the stack @emph{before} those that match the
2721current rule. This is a very risky practice, and to use it reliably
2722you must be certain of the context in which the rule is applied. Here
2723is a case in which you can use this reliably:
2724
2725@example
2726@group
2727foo: expr bar '+' expr @{ @dots{} @}
2728 | expr bar '-' expr @{ @dots{} @}
2729 ;
2730@end group
2731
2732@group
2733bar: /* empty */
2734 @{ previous_expr = $0; @}
2735 ;
2736@end group
2737@end example
2738
2739As long as @code{bar} is used only in the fashion shown here, @code{$0}
2740always refers to the @code{expr} which precedes @code{bar} in the
2741definition of @code{foo}.
2742
342b8b6e 2743@node Action Types
bfa74976
RS
2744@subsection Data Types of Values in Actions
2745@cindex action data types
2746@cindex data types in actions
2747
2748If you have chosen a single data type for semantic values, the @code{$$}
2749and @code{$@var{n}} constructs always have that data type.
2750
2751If you have used @code{%union} to specify a variety of data types, then you
2752must declare a choice among these types for each terminal or nonterminal
2753symbol that can have a semantic value. Then each time you use @code{$$} or
2754@code{$@var{n}}, its data type is determined by which symbol it refers to
e0c471a9 2755in the rule. In this example,
bfa74976
RS
2756
2757@example
2758@group
2759exp: @dots{}
2760 | exp '+' exp
2761 @{ $$ = $1 + $3; @}
2762@end group
2763@end example
2764
2765@noindent
2766@code{$1} and @code{$3} refer to instances of @code{exp}, so they all
2767have the data type declared for the nonterminal symbol @code{exp}. If
2768@code{$2} were used, it would have the data type declared for the
e0c471a9 2769terminal symbol @code{'+'}, whatever that might be.
bfa74976
RS
2770
2771Alternatively, you can specify the data type when you refer to the value,
2772by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
2773reference. For example, if you have defined types as shown here:
2774
2775@example
2776@group
2777%union @{
2778 int itype;
2779 double dtype;
2780@}
2781@end group
2782@end example
2783
2784@noindent
2785then you can write @code{$<itype>1} to refer to the first subunit of the
2786rule as an integer, or @code{$<dtype>1} to refer to it as a double.
2787
342b8b6e 2788@node Mid-Rule Actions
bfa74976
RS
2789@subsection Actions in Mid-Rule
2790@cindex actions in mid-rule
2791@cindex mid-rule actions
2792
2793Occasionally it is useful to put an action in the middle of a rule.
2794These actions are written just like usual end-of-rule actions, but they
2795are executed before the parser even recognizes the following components.
2796
2797A mid-rule action may refer to the components preceding it using
2798@code{$@var{n}}, but it may not refer to subsequent components because
2799it is run before they are parsed.
2800
2801The mid-rule action itself counts as one of the components of the rule.
2802This makes a difference when there is another action later in the same rule
2803(and usually there is another at the end): you have to count the actions
2804along with the symbols when working out which number @var{n} to use in
2805@code{$@var{n}}.
2806
2807The mid-rule action can also have a semantic value. The action can set
2808its value with an assignment to @code{$$}, and actions later in the rule
2809can refer to the value using @code{$@var{n}}. Since there is no symbol
2810to name the action, there is no way to declare a data type for the value
fdc6758b
MA
2811in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to
2812specify a data type each time you refer to this value.
bfa74976
RS
2813
2814There is no way to set the value of the entire rule with a mid-rule
2815action, because assignments to @code{$$} do not have that effect. The
2816only way to set the value for the entire rule is with an ordinary action
2817at the end of the rule.
2818
2819Here is an example from a hypothetical compiler, handling a @code{let}
2820statement that looks like @samp{let (@var{variable}) @var{statement}} and
2821serves to create a variable named @var{variable} temporarily for the
2822duration of @var{statement}. To parse this construct, we must put
2823@var{variable} into the symbol table while @var{statement} is parsed, then
2824remove it afterward. Here is how it is done:
2825
2826@example
2827@group
2828stmt: LET '(' var ')'
2829 @{ $<context>$ = push_context ();
2830 declare_variable ($3); @}
2831 stmt @{ $$ = $6;
2832 pop_context ($<context>5); @}
2833@end group
2834@end example
2835
2836@noindent
2837As soon as @samp{let (@var{variable})} has been recognized, the first
2838action is run. It saves a copy of the current semantic context (the
2839list of accessible variables) as its semantic value, using alternative
2840@code{context} in the data-type union. Then it calls
2841@code{declare_variable} to add the new variable to that list. Once the
2842first action is finished, the embedded statement @code{stmt} can be
2843parsed. Note that the mid-rule action is component number 5, so the
2844@samp{stmt} is component number 6.
2845
2846After the embedded statement is parsed, its semantic value becomes the
2847value of the entire @code{let}-statement. Then the semantic value from the
2848earlier action is used to restore the prior list of variables. This
2849removes the temporary @code{let}-variable from the list so that it won't
2850appear to exist while the rest of the program is parsed.
2851
2852Taking action before a rule is completely recognized often leads to
2853conflicts since the parser must commit to a parse in order to execute the
2854action. For example, the following two rules, without mid-rule actions,
2855can coexist in a working parser because the parser can shift the open-brace
2856token and look at what follows before deciding whether there is a
2857declaration or not:
2858
2859@example
2860@group
2861compound: '@{' declarations statements '@}'
2862 | '@{' statements '@}'
2863 ;
2864@end group
2865@end example
2866
2867@noindent
2868But when we add a mid-rule action as follows, the rules become nonfunctional:
2869
2870@example
2871@group
2872compound: @{ prepare_for_local_variables (); @}
2873 '@{' declarations statements '@}'
2874@end group
2875@group
2876 | '@{' statements '@}'
2877 ;
2878@end group
2879@end example
2880
2881@noindent
2882Now the parser is forced to decide whether to run the mid-rule action
2883when it has read no farther than the open-brace. In other words, it
2884must commit to using one rule or the other, without sufficient
2885information to do it correctly. (The open-brace token is what is called
2886the @dfn{look-ahead} token at this time, since the parser is still
2887deciding what to do about it. @xref{Look-Ahead, ,Look-Ahead Tokens}.)
2888
2889You might think that you could correct the problem by putting identical
2890actions into the two rules, like this:
2891
2892@example
2893@group
2894compound: @{ prepare_for_local_variables (); @}
2895 '@{' declarations statements '@}'
2896 | @{ prepare_for_local_variables (); @}
2897 '@{' statements '@}'
2898 ;
2899@end group
2900@end example
2901
2902@noindent
2903But this does not help, because Bison does not realize that the two actions
2904are identical. (Bison never tries to understand the C code in an action.)
2905
2906If the grammar is such that a declaration can be distinguished from a
2907statement by the first token (which is true in C), then one solution which
2908does work is to put the action after the open-brace, like this:
2909
2910@example
2911@group
2912compound: '@{' @{ prepare_for_local_variables (); @}
2913 declarations statements '@}'
2914 | '@{' statements '@}'
2915 ;
2916@end group
2917@end example
2918
2919@noindent
2920Now the first token of the following declaration or statement,
2921which would in any case tell Bison which rule to use, can still do so.
2922
2923Another solution is to bury the action inside a nonterminal symbol which
2924serves as a subroutine:
2925
2926@example
2927@group
2928subroutine: /* empty */
2929 @{ prepare_for_local_variables (); @}
2930 ;
2931
2932@end group
2933
2934@group
2935compound: subroutine
2936 '@{' declarations statements '@}'
2937 | subroutine
2938 '@{' statements '@}'
2939 ;
2940@end group
2941@end example
2942
2943@noindent
2944Now Bison can execute the action in the rule for @code{subroutine} without
2945deciding which rule for @code{compound} it will eventually use. Note that
2946the action is now at the end of its rule. Any mid-rule action can be
2947converted to an end-of-rule action in this way, and this is what Bison
2948actually does to implement mid-rule actions.
2949
342b8b6e 2950@node Locations
847bf1f5
AD
2951@section Tracking Locations
2952@cindex location
2953@cindex textual position
2954@cindex position, textual
2955
2956Though grammar rules and semantic actions are enough to write a fully
2957functional parser, it can be useful to process some additionnal informations,
3e259915
MA
2958especially symbol locations.
2959
2960@c (terminal or not) ?
847bf1f5 2961
704a47c4
AD
2962The way locations are handled is defined by providing a data type, and
2963actions to take when rules are matched.
847bf1f5
AD
2964
2965@menu
2966* Location Type:: Specifying a data type for locations.
2967* Actions and Locations:: Using locations in actions.
2968* Location Default Action:: Defining a general way to compute locations.
2969@end menu
2970
342b8b6e 2971@node Location Type
847bf1f5
AD
2972@subsection Data Type of Locations
2973@cindex data type of locations
2974@cindex default location type
2975
2976Defining a data type for locations is much simpler than for semantic values,
2977since all tokens and groupings always use the same type.
2978
2979The type of locations is specified by defining a macro called @code{YYLTYPE}.
2980When @code{YYLTYPE} is not defined, Bison uses a default structure type with
2981four members:
2982
2983@example
2984struct
2985@{
2986 int first_line;
2987 int first_column;
2988 int last_line;
2989 int last_column;
2990@}
2991@end example
2992
342b8b6e 2993@node Actions and Locations
847bf1f5
AD
2994@subsection Actions and Locations
2995@cindex location actions
2996@cindex actions, location
2997@vindex @@$
2998@vindex @@@var{n}
2999
3000Actions are not only useful for defining language semantics, but also for
3001describing the behavior of the output parser with locations.
3002
3003The most obvious way for building locations of syntactic groupings is very
3004similar to the way semantic values are computed. In a given rule, several
3005constructs can be used to access the locations of the elements being matched.
3006The location of the @var{n}th component of the right hand side is
3007@code{@@@var{n}}, while the location of the left hand side grouping is
3008@code{@@$}.
3009
3e259915 3010Here is a basic example using the default data type for locations:
847bf1f5
AD
3011
3012@example
3013@group
3014exp: @dots{}
3e259915 3015 | exp '/' exp
847bf1f5 3016 @{
3e259915
MA
3017 @@$.first_column = @@1.first_column;
3018 @@$.first_line = @@1.first_line;
847bf1f5
AD
3019 @@$.last_column = @@3.last_column;
3020 @@$.last_line = @@3.last_line;
3e259915
MA
3021 if ($3)
3022 $$ = $1 / $3;
3023 else
3024 @{
3025 $$ = 1;
3026 printf("Division by zero, l%d,c%d-l%d,c%d",
3027 @@3.first_line, @@3.first_column,
3028 @@3.last_line, @@3.last_column);
3029 @}
847bf1f5
AD
3030 @}
3031@end group
3032@end example
3033
3e259915
MA
3034As for semantic values, there is a default action for locations that is
3035run each time a rule is matched. It sets the beginning of @code{@@$} to the
3036beginning of the first symbol, and the end of @code{@@$} to the end of the
79282c6c 3037last symbol.
3e259915
MA
3038
3039With this default action, the location tracking can be fully automatic. The
3040example above simply rewrites this way:
3041
3042@example
3043@group
3044exp: @dots{}
3045 | exp '/' exp
3046 @{
3047 if ($3)
3048 $$ = $1 / $3;
3049 else
3050 @{
3051 $$ = 1;
3052 printf("Division by zero, l%d,c%d-l%d,c%d",
3053 @@3.first_line, @@3.first_column,
3054 @@3.last_line, @@3.last_column);
3055 @}
3056 @}
3057@end group
3058@end example
847bf1f5 3059
342b8b6e 3060@node Location Default Action
847bf1f5
AD
3061@subsection Default Action for Locations
3062@vindex YYLLOC_DEFAULT
3063
704a47c4
AD
3064Actually, actions are not the best place to compute locations. Since
3065locations are much more general than semantic values, there is room in
3066the output parser to redefine the default action to take for each
3067rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
3068matched, before the associated action is run.
847bf1f5 3069
3e259915 3070Most of the time, this macro is general enough to suppress location
79282c6c 3071dedicated code from semantic actions.
847bf1f5 3072
79282c6c
AD
3073The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
3074the location of the grouping (the result of the computation). The second one
3075is an array holding locations of all right hand side elements of the rule
3e259915 3076being matched. The last one is the size of the right hand side rule.
847bf1f5 3077
676385e2 3078By default, it is defined this way for simple LALR(1) parsers:
847bf1f5
AD
3079
3080@example
3081@group
b2d52318
AD
3082#define YYLLOC_DEFAULT(Current, Rhs, N) \
3083 Current.first_line = Rhs[1].first_line; \
3084 Current.first_column = Rhs[1].first_column; \
3085 Current.last_line = Rhs[N].last_line; \
3086 Current.last_column = Rhs[N].last_column;
847bf1f5
AD
3087@end group
3088@end example
3089
676385e2
PH
3090@noindent
3091and like this for GLR parsers:
3092
3093@example
3094@group
3095#define YYLLOC_DEFAULT(Current, Rhs, N) \
3096 Current.first_line = YYRHSLOC(Rhs,1).first_line; \
3097 Current.first_column = YYRHSLOC(Rhs,1).first_column; \
3098 Current.last_line = YYRHSLOC(Rhs,N).last_line; \
3099 Current.last_column = YYRHSLOC(Rhs,N).last_column;
3100@end group
3101@end example
3102
3e259915 3103When defining @code{YYLLOC_DEFAULT}, you should consider that:
847bf1f5 3104
3e259915 3105@itemize @bullet
79282c6c 3106@item
3e259915
MA
3107All arguments are free of side-effects. However, only the first one (the
3108result) should be modified by @code{YYLLOC_DEFAULT}.
847bf1f5 3109
3e259915 3110@item
b2d52318
AD
3111For consistency with semantic actions, valid indexes for the location
3112array range from 1 to @var{n}.
3e259915 3113@end itemize
847bf1f5 3114
342b8b6e 3115@node Declarations
bfa74976
RS
3116@section Bison Declarations
3117@cindex declarations, Bison
3118@cindex Bison declarations
3119
3120The @dfn{Bison declarations} section of a Bison grammar defines the symbols
3121used in formulating the grammar and the data types of semantic values.
3122@xref{Symbols}.
3123
3124All token type names (but not single-character literal tokens such as
3125@code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
3126declared if you need to specify which data type to use for the semantic
3127value (@pxref{Multiple Types, ,More Than One Value Type}).
3128
3129The first rule in the file also specifies the start symbol, by default.
3130If you want some other symbol to be the start symbol, you must declare
704a47c4
AD
3131it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free
3132Grammars}).
bfa74976
RS
3133
3134@menu
3135* Token Decl:: Declaring terminal symbols.
3136* Precedence Decl:: Declaring terminals with precedence and associativity.
3137* Union Decl:: Declaring the set of all semantic value types.
3138* Type Decl:: Declaring the choice of type for a nonterminal symbol.
3139* Expect Decl:: Suppressing warnings about shift/reduce conflicts.
3140* Start Decl:: Specifying the start symbol.
3141* Pure Decl:: Requesting a reentrant parser.
3142* Decl Summary:: Table of all Bison declarations.
3143@end menu
3144
342b8b6e 3145@node Token Decl
bfa74976
RS
3146@subsection Token Type Names
3147@cindex declaring token type names
3148@cindex token type names, declaring
931c7513 3149@cindex declaring literal string tokens
bfa74976
RS
3150@findex %token
3151
3152The basic way to declare a token type name (terminal symbol) is as follows:
3153
3154@example
3155%token @var{name}
3156@end example
3157
3158Bison will convert this into a @code{#define} directive in
3159the parser, so that the function @code{yylex} (if it is in this file)
3160can use the name @var{name} to stand for this token type's code.
3161
14ded682
AD
3162Alternatively, you can use @code{%left}, @code{%right}, or
3163@code{%nonassoc} instead of @code{%token}, if you wish to specify
3164associativity and precedence. @xref{Precedence Decl, ,Operator
3165Precedence}.
bfa74976
RS
3166
3167You can explicitly specify the numeric code for a token type by appending
3168an integer value in the field immediately following the token name:
3169
3170@example
3171%token NUM 300
3172@end example
3173
3174@noindent
3175It is generally best, however, to let Bison choose the numeric codes for
3176all token types. Bison will automatically select codes that don't conflict
e966383b 3177with each other or with normal characters.
bfa74976
RS
3178
3179In the event that the stack type is a union, you must augment the
3180@code{%token} or other token declaration to include the data type
704a47c4
AD
3181alternative delimited by angle-brackets (@pxref{Multiple Types, ,More
3182Than One Value Type}).
bfa74976
RS
3183
3184For example:
3185
3186@example
3187@group
3188%union @{ /* define stack type */
3189 double val;
3190 symrec *tptr;
3191@}
3192%token <val> NUM /* define token NUM and its type */
3193@end group
3194@end example
3195
931c7513
RS
3196You can associate a literal string token with a token type name by
3197writing the literal string at the end of a @code{%token}
3198declaration which declares the name. For example:
3199
3200@example
3201%token arrow "=>"
3202@end example
3203
3204@noindent
3205For example, a grammar for the C language might specify these names with
3206equivalent literal string tokens:
3207
3208@example
3209%token <operator> OR "||"
3210%token <operator> LE 134 "<="
3211%left OR "<="
3212@end example
3213
3214@noindent
3215Once you equate the literal string and the token name, you can use them
3216interchangeably in further declarations or the grammar rules. The
3217@code{yylex} function can use the token name or the literal string to
3218obtain the token type code number (@pxref{Calling Convention}).
3219
342b8b6e 3220@node Precedence Decl
bfa74976
RS
3221@subsection Operator Precedence
3222@cindex precedence declarations
3223@cindex declaring operator precedence
3224@cindex operator precedence, declaring
3225
3226Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
3227declare a token and specify its precedence and associativity, all at
3228once. These are called @dfn{precedence declarations}.
704a47c4
AD
3229@xref{Precedence, ,Operator Precedence}, for general information on
3230operator precedence.
bfa74976
RS
3231
3232The syntax of a precedence declaration is the same as that of
3233@code{%token}: either
3234
3235@example
3236%left @var{symbols}@dots{}
3237@end example
3238
3239@noindent
3240or
3241
3242@example
3243%left <@var{type}> @var{symbols}@dots{}
3244@end example
3245
3246And indeed any of these declarations serves the purposes of @code{%token}.
3247But in addition, they specify the associativity and relative precedence for
3248all the @var{symbols}:
3249
3250@itemize @bullet
3251@item
3252The associativity of an operator @var{op} determines how repeated uses
3253of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
3254@var{z}} is parsed by grouping @var{x} with @var{y} first or by
3255grouping @var{y} with @var{z} first. @code{%left} specifies
3256left-associativity (grouping @var{x} with @var{y} first) and
3257@code{%right} specifies right-associativity (grouping @var{y} with
3258@var{z} first). @code{%nonassoc} specifies no associativity, which
3259means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
3260considered a syntax error.
3261
3262@item
3263The precedence of an operator determines how it nests with other operators.
3264All the tokens declared in a single precedence declaration have equal
3265precedence and nest together according to their associativity.
3266When two tokens declared in different precedence declarations associate,
3267the one declared later has the higher precedence and is grouped first.
3268@end itemize
3269
342b8b6e 3270@node Union Decl
bfa74976
RS
3271@subsection The Collection of Value Types
3272@cindex declaring value types
3273@cindex value types, declaring
3274@findex %union
3275
3276The @code{%union} declaration specifies the entire collection of possible
3277data types for semantic values. The keyword @code{%union} is followed by a
3278pair of braces containing the same thing that goes inside a @code{union} in
13863333 3279C.
bfa74976
RS
3280
3281For example:
3282
3283@example
3284@group
3285%union @{
3286 double val;
3287 symrec *tptr;
3288@}
3289@end group
3290@end example
3291
3292@noindent
3293This says that the two alternative types are @code{double} and @code{symrec
3294*}. They are given names @code{val} and @code{tptr}; these names are used
3295in the @code{%token} and @code{%type} declarations to pick one of the types
3296for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
3297
3298Note that, unlike making a @code{union} declaration in C, you do not write
3299a semicolon after the closing brace.
3300
342b8b6e 3301@node Type Decl
bfa74976
RS
3302@subsection Nonterminal Symbols
3303@cindex declaring value types, nonterminals
3304@cindex value types, nonterminals, declaring
3305@findex %type
3306
3307@noindent
3308When you use @code{%union} to specify multiple value types, you must
3309declare the value type of each nonterminal symbol for which values are
3310used. This is done with a @code{%type} declaration, like this:
3311
3312@example
3313%type <@var{type}> @var{nonterminal}@dots{}
3314@end example
3315
3316@noindent
704a47c4
AD
3317Here @var{nonterminal} is the name of a nonterminal symbol, and
3318@var{type} is the name given in the @code{%union} to the alternative
3319that you want (@pxref{Union Decl, ,The Collection of Value Types}). You
3320can give any number of nonterminal symbols in the same @code{%type}
3321declaration, if they have the same value type. Use spaces to separate
3322the symbol names.
bfa74976 3323
931c7513
RS
3324You can also declare the value type of a terminal symbol. To do this,
3325use the same @code{<@var{type}>} construction in a declaration for the
3326terminal symbol. All kinds of token declarations allow
3327@code{<@var{type}>}.
3328
342b8b6e 3329@node Expect Decl
bfa74976
RS
3330@subsection Suppressing Conflict Warnings
3331@cindex suppressing conflict warnings
3332@cindex preventing warnings about conflicts
3333@cindex warnings, preventing
3334@cindex conflicts, suppressing warnings of
3335@findex %expect
3336
3337Bison normally warns if there are any conflicts in the grammar
7da99ede
AD
3338(@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars
3339have harmless shift/reduce conflicts which are resolved in a predictable
3340way and would be difficult to eliminate. It is desirable to suppress
3341the warning about these conflicts unless the number of conflicts
3342changes. You can do this with the @code{%expect} declaration.
bfa74976
RS
3343
3344The declaration looks like this:
3345
3346@example
3347%expect @var{n}
3348@end example
3349
7da99ede
AD
3350Here @var{n} is a decimal integer. The declaration says there should be
3351no warning if there are @var{n} shift/reduce conflicts and no
3352reduce/reduce conflicts. An error, instead of the usual warning, is
3353given if there are either more or fewer conflicts, or if there are any
3354reduce/reduce conflicts.
bfa74976
RS
3355
3356In general, using @code{%expect} involves these steps:
3357
3358@itemize @bullet
3359@item
3360Compile your grammar without @code{%expect}. Use the @samp{-v} option
3361to get a verbose list of where the conflicts occur. Bison will also
3362print the number of conflicts.
3363
3364@item
3365Check each of the conflicts to make sure that Bison's default
3366resolution is what you really want. If not, rewrite the grammar and
3367go back to the beginning.
3368
3369@item
3370Add an @code{%expect} declaration, copying the number @var{n} from the
3371number which Bison printed.
3372@end itemize
3373
3374Now Bison will stop annoying you about the conflicts you have checked, but
3375it will warn you again if changes in the grammar result in additional
3376conflicts.
3377
342b8b6e 3378@node Start Decl
bfa74976
RS
3379@subsection The Start-Symbol
3380@cindex declaring the start symbol
3381@cindex start symbol, declaring
3382@cindex default start symbol
3383@findex %start
3384
3385Bison assumes by default that the start symbol for the grammar is the first
3386nonterminal specified in the grammar specification section. The programmer
3387may override this restriction with the @code{%start} declaration as follows:
3388
3389@example
3390%start @var{symbol}
3391@end example
3392
342b8b6e 3393@node Pure Decl
bfa74976
RS
3394@subsection A Pure (Reentrant) Parser
3395@cindex reentrant parser
3396@cindex pure parser
8c9a50be 3397@findex %pure-parser
bfa74976
RS
3398
3399A @dfn{reentrant} program is one which does not alter in the course of
3400execution; in other words, it consists entirely of @dfn{pure} (read-only)
3401code. Reentrancy is important whenever asynchronous execution is possible;
14ded682
AD
3402for example, a non-reentrant program may not be safe to call from a signal
3403handler. In systems with multiple threads of control, a non-reentrant
bfa74976
RS
3404program must be called only within interlocks.
3405
70811b85
RS
3406Normally, Bison generates a parser which is not reentrant. This is
3407suitable for most uses, and it permits compatibility with YACC. (The
3408standard YACC interfaces are inherently nonreentrant, because they use
3409statically allocated variables for communication with @code{yylex},
3410including @code{yylval} and @code{yylloc}.)
bfa74976 3411
70811b85 3412Alternatively, you can generate a pure, reentrant parser. The Bison
8c9a50be 3413declaration @code{%pure-parser} says that you want the parser to be
70811b85 3414reentrant. It looks like this:
bfa74976
RS
3415
3416@example
8c9a50be 3417%pure-parser
bfa74976
RS
3418@end example
3419
70811b85
RS
3420The result is that the communication variables @code{yylval} and
3421@code{yylloc} become local variables in @code{yyparse}, and a different
3422calling convention is used for the lexical analyzer function
3423@code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure
3424Parsers}, for the details of this. The variable @code{yynerrs} also
3425becomes local in @code{yyparse} (@pxref{Error Reporting, ,The Error
3426Reporting Function @code{yyerror}}). The convention for calling
3427@code{yyparse} itself is unchanged.
3428
3429Whether the parser is pure has nothing to do with the grammar rules.
3430You can generate either a pure parser or a nonreentrant parser from any
3431valid grammar.
bfa74976 3432
342b8b6e 3433@node Decl Summary
bfa74976
RS
3434@subsection Bison Declaration Summary
3435@cindex Bison declaration summary
3436@cindex declaration summary
3437@cindex summary, Bison declaration
3438
d8988b2f 3439Here is a summary of the declarations used to define a grammar:
bfa74976
RS
3440
3441@table @code
3442@item %union
3443Declare the collection of data types that semantic values may have
3444(@pxref{Union Decl, ,The Collection of Value Types}).
3445
3446@item %token
3447Declare a terminal symbol (token type name) with no precedence
3448or associativity specified (@pxref{Token Decl, ,Token Type Names}).
3449
3450@item %right
3451Declare a terminal symbol (token type name) that is right-associative
3452(@pxref{Precedence Decl, ,Operator Precedence}).
3453
3454@item %left
3455Declare a terminal symbol (token type name) that is left-associative
3456(@pxref{Precedence Decl, ,Operator Precedence}).
3457
3458@item %nonassoc
3459Declare a terminal symbol (token type name) that is nonassociative
3460(using it in a way that would be associative is a syntax error)
3461(@pxref{Precedence Decl, ,Operator Precedence}).
3462
3463@item %type
3464Declare the type of semantic values for a nonterminal symbol
3465(@pxref{Type Decl, ,Nonterminal Symbols}).
3466
3467@item %start
89cab50d
AD
3468Specify the grammar's start symbol (@pxref{Start Decl, ,The
3469Start-Symbol}).
bfa74976
RS
3470
3471@item %expect
3472Declare the expected number of shift-reduce conflicts
3473(@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
d8988b2f 3474@end table
bfa74976 3475
d8988b2f
AD
3476@sp 1
3477@noindent
3478In order to change the behavior of @command{bison}, use the following
3479directives:
3480
3481@table @code
3482@item %debug
4947ebdb
PE
3483In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
3484already defined, so that the debugging facilities are compiled.
ec3bc396 3485@xref{Tracing, ,Tracing Your Parser}.
d8988b2f
AD
3486
3487@item %defines
3488Write an extra output file containing macro definitions for the token
3489type names defined in the grammar and the semantic value type
3490@code{YYSTYPE}, as well as a few @code{extern} variable declarations.
3491
3492If the parser output file is named @file{@var{name}.c} then this file
e0c471a9 3493is named @file{@var{name}.h}.
d8988b2f
AD
3494
3495This output file is essential if you wish to put the definition of
3496@code{yylex} in a separate source file, because @code{yylex} needs to
3497be able to refer to token type codes and the variable
e0c471a9 3498@code{yylval}. @xref{Token Values, ,Semantic Values of Tokens}.
d8988b2f
AD
3499
3500@item %file-prefix="@var{prefix}"
3501Specify a prefix to use for all Bison output file names. The names are
3502chosen as if the input file were named @file{@var{prefix}.y}.
3503
8c9a50be 3504@c @item %header-extension
d8988b2f
AD
3505@c Specify the extension of the parser header file generated when
3506@c @code{%define} or @samp{-d} are used.
3507@c
3508@c For example, a grammar file named @file{foo.ypp} and containing a
8c9a50be 3509@c @code{%header-extension .hh} directive will produce a header file
d8988b2f 3510@c named @file{foo.tab.hh}
6deb4447 3511
89cab50d
AD
3512@item %locations
3513Generate the code processing the locations (@pxref{Action Features,
3514,Special Features for Use in Actions}). This mode is enabled as soon as
3515the grammar uses the special @samp{@@@var{n}} tokens, but if your
3516grammar does not use it, using @samp{%locations} allows for more
3517accurate parse error messages.
3518
d8988b2f
AD
3519@item %name-prefix="@var{prefix}"
3520Rename the external symbols used in the parser so that they start with
3521@var{prefix} instead of @samp{yy}. The precise list of symbols renamed
3522is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs},
b5b61c61
AD
3523@code{yylval}, @code{yychar}, @code{yydebug}, and possible
3524@code{yylloc}. For example, if you use @samp{%name-prefix="c_"}, the
3525names become @code{c_parse}, @code{c_lex}, and so on. @xref{Multiple
3526Parsers, ,Multiple Parsers in the Same Program}.
931c7513 3527
d8988b2f 3528@item %no-parser
6deb4447
AD
3529Do not include any C code in the parser file; generate tables only. The
3530parser file contains just @code{#define} directives and static variable
3531declarations.
3532
3533This option also tells Bison to write the C code for the grammar actions
3534into a file named @file{@var{filename}.act}, in the form of a
3535brace-surrounded body fit for a @code{switch} statement.
3536
d8988b2f 3537@item %no-lines
931c7513
RS
3538Don't generate any @code{#line} preprocessor commands in the parser
3539file. Ordinarily Bison writes these commands in the parser file so that
3540the C compiler and debuggers will associate errors and object code with
3541your source file (the grammar file). This directive causes them to
3542associate errors with the parser file, treating it an independent source
3543file in its own right.
3544
d8988b2f
AD
3545@item %output="@var{filename}"
3546Specify the @var{filename} for the parser file.
6deb4447 3547
d8988b2f
AD
3548@item %pure-parser
3549Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure
3550(Reentrant) Parser}).
6deb4447 3551
8c9a50be 3552@c @item %source-extension
f9a8293a
AD
3553@c Specify the extension of the parser output file.
3554@c
3555@c For example, a grammar file named @file{foo.yy} and containing a
8c9a50be 3556@c @code{%source-extension .cpp} directive will produce a parser file
f9a8293a 3557@c named @file{foo.tab.cpp}
6deb4447 3558
8c9a50be 3559@item %token-table
931c7513
RS
3560Generate an array of token names in the parser file. The name of the
3561array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
3650b4b8 3562token whose internal Bison token code number is @var{i}. The first
88bce5a2
AD
3563three elements of @code{yytname} are always @code{"$end"},
3564@code{"error"}, and @code{"$undefined"}; after these come the symbols
3565defined in the grammar file.
931c7513
RS
3566
3567For single-character literal tokens and literal string tokens, the name
3568in the table includes the single-quote or double-quote characters: for
3569example, @code{"'+'"} is a single-character literal and @code{"\"<=\""}
3570is a literal string token. All the characters of the literal string
3571token appear verbatim in the string found in the table; even
3572double-quote characters are not escaped. For example, if the token
3573consists of three characters @samp{*"*}, its string in @code{yytname}
3574contains @samp{"*"*"}. (In C, that would be written as
3575@code{"\"*\"*\""}).
3576
8c9a50be 3577When you specify @code{%token-table}, Bison also generates macro
931c7513
RS
3578definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and
3579@code{YYNRULES}, and @code{YYNSTATES}:
3580
3581@table @code
3582@item YYNTOKENS
3583The highest token number, plus one.
3584@item YYNNTS
9ecbd125 3585The number of nonterminal symbols.
931c7513
RS
3586@item YYNRULES
3587The number of grammar rules,
3588@item YYNSTATES
3589The number of parser states (@pxref{Parser States}).
3590@end table
d8988b2f
AD
3591
3592@item %verbose
3593Write an extra output file containing verbose descriptions of the
3594parser states and what is done for each type of look-ahead token in
ec3bc396
AD
3595that state. @xref{Understanding, , Understanding Your Parser}, for more
3596information.
d8988b2f 3597
d8988b2f 3598
d8988b2f
AD
3599
3600@item %yacc
d8988b2f
AD
3601Pretend the option @option{--yacc} was given, i.e., imitate Yacc,
3602including its naming conventions. @xref{Bison Options}, for more.
bfa74976
RS
3603@end table
3604
d8988b2f
AD
3605
3606
3607
342b8b6e 3608@node Multiple Parsers
bfa74976
RS
3609@section Multiple Parsers in the Same Program
3610
3611Most programs that use Bison parse only one language and therefore contain
3612only one Bison parser. But what if you want to parse more than one
3613language with the same program? Then you need to avoid a name conflict
3614between different definitions of @code{yyparse}, @code{yylval}, and so on.
3615
3616The easy way to do this is to use the option @samp{-p @var{prefix}}
704a47c4
AD
3617(@pxref{Invocation, ,Invoking Bison}). This renames the interface
3618functions and variables of the Bison parser to start with @var{prefix}
3619instead of @samp{yy}. You can use this to give each parser distinct
3620names that do not conflict.
bfa74976
RS
3621
3622The precise list of symbols renamed is @code{yyparse}, @code{yylex},
c656404a
RS
3623@code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yychar} and
3624@code{yydebug}. For example, if you use @samp{-p c}, the names become
3625@code{cparse}, @code{clex}, and so on.
bfa74976
RS
3626
3627@strong{All the other variables and macros associated with Bison are not
3628renamed.} These others are not global; there is no conflict if the same
3629name is used in different parsers. For example, @code{YYSTYPE} is not
3630renamed, but defining this in different ways in different parsers causes
3631no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
3632
3633The @samp{-p} option works by adding macro definitions to the beginning
3634of the parser source file, defining @code{yyparse} as
3635@code{@var{prefix}parse}, and so on. This effectively substitutes one
3636name for the other in the entire parser file.
3637
342b8b6e 3638@node Interface
bfa74976
RS
3639@chapter Parser C-Language Interface
3640@cindex C-language interface
3641@cindex interface
3642
3643The Bison parser is actually a C function named @code{yyparse}. Here we
3644describe the interface conventions of @code{yyparse} and the other
3645functions that it needs to use.
3646
3647Keep in mind that the parser uses many C identifiers starting with
3648@samp{yy} and @samp{YY} for internal purposes. If you use such an
75f5aaea
MA
3649identifier (aside from those in this manual) in an action or in epilogue
3650in the grammar file, you are likely to run into trouble.
bfa74976
RS
3651
3652@menu
3653* Parser Function:: How to call @code{yyparse} and what it returns.
13863333 3654* Lexical:: You must supply a function @code{yylex}
bfa74976
RS
3655 which reads tokens.
3656* Error Reporting:: You must supply a function @code{yyerror}.
3657* Action Features:: Special features for use in actions.
3658@end menu
3659
342b8b6e 3660@node Parser Function
bfa74976
RS
3661@section The Parser Function @code{yyparse}
3662@findex yyparse
3663
3664You call the function @code{yyparse} to cause parsing to occur. This
3665function reads tokens, executes actions, and ultimately returns when it
3666encounters end-of-input or an unrecoverable syntax error. You can also
14ded682
AD
3667write an action which directs @code{yyparse} to return immediately
3668without reading further.
bfa74976
RS
3669
3670The value returned by @code{yyparse} is 0 if parsing was successful (return
3671is due to end-of-input).
3672
3673The value is 1 if parsing failed (return is due to a syntax error).
3674
3675In an action, you can cause immediate return from @code{yyparse} by using
3676these macros:
3677
3678@table @code
3679@item YYACCEPT
3680@findex YYACCEPT
3681Return immediately with value 0 (to report success).
3682
3683@item YYABORT
3684@findex YYABORT
3685Return immediately with value 1 (to report failure).
3686@end table
3687
342b8b6e 3688@node Lexical
bfa74976
RS
3689@section The Lexical Analyzer Function @code{yylex}
3690@findex yylex
3691@cindex lexical analyzer
3692
3693The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
3694the input stream and returns them to the parser. Bison does not create
3695this function automatically; you must write it so that @code{yyparse} can
3696call it. The function is sometimes referred to as a lexical scanner.
3697
3698In simple programs, @code{yylex} is often defined at the end of the Bison
3699grammar file. If @code{yylex} is defined in a separate source file, you
3700need to arrange for the token-type macro definitions to be available there.
3701To do this, use the @samp{-d} option when you run Bison, so that it will
3702write these macro definitions into a separate header file
3703@file{@var{name}.tab.h} which you can include in the other source files
e0c471a9 3704that need it. @xref{Invocation, ,Invoking Bison}.
bfa74976
RS
3705
3706@menu
3707* Calling Convention:: How @code{yyparse} calls @code{yylex}.
3708* Token Values:: How @code{yylex} must return the semantic value
3709 of the token it has read.
3710* Token Positions:: How @code{yylex} must return the text position
3711 (line number, etc.) of the token, if the
3712 actions want that.
3713* Pure Calling:: How the calling convention differs
3714 in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
3715@end menu
3716
342b8b6e 3717@node Calling Convention
bfa74976
RS
3718@subsection Calling Convention for @code{yylex}
3719
3720The value that @code{yylex} returns must be the numeric code for the type
3721of token it has just found, or 0 for end-of-input.
3722
3723When a token is referred to in the grammar rules by a name, that name
3724in the parser file becomes a C macro whose definition is the proper
3725numeric code for that token type. So @code{yylex} can use the name
3726to indicate that type. @xref{Symbols}.
3727
3728When a token is referred to in the grammar rules by a character literal,
3729the numeric code for that character is also the code for the token type.
3730So @code{yylex} can simply return that character code. The null character
3731must not be used this way, because its code is zero and that is what
3732signifies end-of-input.
3733
3734Here is an example showing these things:
3735
3736@example
13863333
AD
3737int
3738yylex (void)
bfa74976
RS
3739@{
3740 @dots{}
3741 if (c == EOF) /* Detect end of file. */
3742 return 0;
3743 @dots{}
3744 if (c == '+' || c == '-')
3745 return c; /* Assume token type for `+' is '+'. */
3746 @dots{}
3747 return INT; /* Return the type of the token. */
3748 @dots{}
3749@}
3750@end example
3751
3752@noindent
3753This interface has been designed so that the output from the @code{lex}
3754utility can be used without change as the definition of @code{yylex}.
3755
931c7513
RS
3756If the grammar uses literal string tokens, there are two ways that
3757@code{yylex} can determine the token type codes for them:
3758
3759@itemize @bullet
3760@item
3761If the grammar defines symbolic token names as aliases for the
3762literal string tokens, @code{yylex} can use these symbolic names like
3763all others. In this case, the use of the literal string tokens in
3764the grammar file has no effect on @code{yylex}.
3765
3766@item
9ecbd125 3767@code{yylex} can find the multicharacter token in the @code{yytname}
931c7513 3768table. The index of the token in the table is the token type's code.
9ecbd125 3769The name of a multicharacter token is recorded in @code{yytname} with a
931c7513
RS
3770double-quote, the token's characters, and another double-quote. The
3771token's characters are not escaped in any way; they appear verbatim in
3772the contents of the string in the table.
3773
3774Here's code for looking up a token in @code{yytname}, assuming that the
3775characters of the token are stored in @code{token_buffer}.
3776
3777@smallexample
3778for (i = 0; i < YYNTOKENS; i++)
3779 @{
3780 if (yytname[i] != 0
3781 && yytname[i][0] == '"'
6f515a27
JT
3782 && strncmp (yytname[i] + 1, token_buffer,
3783 strlen (token_buffer))
931c7513
RS
3784 && yytname[i][strlen (token_buffer) + 1] == '"'
3785 && yytname[i][strlen (token_buffer) + 2] == 0)
3786 break;
3787 @}
3788@end smallexample
3789
3790The @code{yytname} table is generated only if you use the
8c9a50be 3791@code{%token-table} declaration. @xref{Decl Summary}.
931c7513
RS
3792@end itemize
3793
342b8b6e 3794@node Token Values
bfa74976
RS
3795@subsection Semantic Values of Tokens
3796
3797@vindex yylval
14ded682 3798In an ordinary (non-reentrant) parser, the semantic value of the token must
bfa74976
RS
3799be stored into the global variable @code{yylval}. When you are using
3800just one data type for semantic values, @code{yylval} has that type.
3801Thus, if the type is @code{int} (the default), you might write this in
3802@code{yylex}:
3803
3804@example
3805@group
3806 @dots{}
3807 yylval = value; /* Put value onto Bison stack. */
3808 return INT; /* Return the type of the token. */
3809 @dots{}
3810@end group
3811@end example
3812
3813When you are using multiple data types, @code{yylval}'s type is a union
704a47c4
AD
3814made from the @code{%union} declaration (@pxref{Union Decl, ,The
3815Collection of Value Types}). So when you store a token's value, you
3816must use the proper member of the union. If the @code{%union}
3817declaration looks like this:
bfa74976
RS
3818
3819@example
3820@group
3821%union @{
3822 int intval;
3823 double val;
3824 symrec *tptr;
3825@}
3826@end group
3827@end example
3828
3829@noindent
3830then the code in @code{yylex} might look like this:
3831
3832@example
3833@group
3834 @dots{}
3835 yylval.intval = value; /* Put value onto Bison stack. */
3836 return INT; /* Return the type of the token. */
3837 @dots{}
3838@end group
3839@end example
3840
342b8b6e 3841@node Token Positions
bfa74976
RS
3842@subsection Textual Positions of Tokens
3843
3844@vindex yylloc
847bf1f5
AD
3845If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
3846Tracking Locations}) in actions to keep track of the
89cab50d
AD
3847textual locations of tokens and groupings, then you must provide this
3848information in @code{yylex}. The function @code{yyparse} expects to
3849find the textual location of a token just parsed in the global variable
3850@code{yylloc}. So @code{yylex} must store the proper data in that
847bf1f5
AD
3851variable.
3852
3853By default, the value of @code{yylloc} is a structure and you need only
89cab50d
AD
3854initialize the members that are going to be used by the actions. The
3855four members are called @code{first_line}, @code{first_column},
3856@code{last_line} and @code{last_column}. Note that the use of this
3857feature makes the parser noticeably slower.
bfa74976
RS
3858
3859@tindex YYLTYPE
3860The data type of @code{yylloc} has the name @code{YYLTYPE}.
3861
342b8b6e 3862@node Pure Calling
c656404a 3863@subsection Calling Conventions for Pure Parsers
bfa74976 3864
8c9a50be 3865When you use the Bison declaration @code{%pure-parser} to request a
e425e872
RS
3866pure, reentrant parser, the global communication variables @code{yylval}
3867and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant)
3868Parser}.) In such parsers the two global variables are replaced by
3869pointers passed as arguments to @code{yylex}. You must declare them as
3870shown here, and pass the information back by storing it through those
3871pointers.
bfa74976
RS
3872
3873@example
13863333
AD
3874int
3875yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
bfa74976
RS
3876@{
3877 @dots{}
3878 *lvalp = value; /* Put value onto Bison stack. */
3879 return INT; /* Return the type of the token. */
3880 @dots{}
3881@}
3882@end example
3883
3884If the grammar file does not use the @samp{@@} constructs to refer to
3885textual positions, then the type @code{YYLTYPE} will not be defined. In
3886this case, omit the second argument; @code{yylex} will be called with
3887only one argument.
3888
c656404a 3889@vindex YYPARSE_PARAM
931c7513
RS
3890If you use a reentrant parser, you can optionally pass additional
3891parameter information to it in a reentrant way. To do so, define the
3892macro @code{YYPARSE_PARAM} as a variable name. This modifies the
3893@code{yyparse} function to accept one argument, of type @code{void *},
3894with that name.
e425e872
RS
3895
3896When you call @code{yyparse}, pass the address of an object, casting the
3897address to @code{void *}. The grammar actions can refer to the contents
3898of the object by casting the pointer value back to its proper type and
3899then dereferencing it. Here's an example. Write this in the parser:
3900
3901@example
3902%@{
3903struct parser_control
3904@{
3905 int nastiness;
3906 int randomness;
3907@};
3908
3909#define YYPARSE_PARAM parm
3910%@}
3911@end example
3912
3913@noindent
3914Then call the parser like this:
3915
3916@example
3917struct parser_control
3918@{
3919 int nastiness;
3920 int randomness;
3921@};
3922
3923@dots{}
3924
3925@{
3926 struct parser_control foo;
3927 @dots{} /* @r{Store proper data in @code{foo}.} */
3928 value = yyparse ((void *) &foo);
3929 @dots{}
3930@}
3931@end example
3932
3933@noindent
3934In the grammar actions, use expressions like this to refer to the data:
3935
3936@example
3937((struct parser_control *) parm)->randomness
3938@end example
3939
c656404a
RS
3940@vindex YYLEX_PARAM
3941If you wish to pass the additional parameter data to @code{yylex},
3942define the macro @code{YYLEX_PARAM} just like @code{YYPARSE_PARAM}, as
3943shown here:
3944
3945@example
3946%@{
3947struct parser_control
3948@{
3949 int nastiness;
3950 int randomness;
3951@};
3952
3953#define YYPARSE_PARAM parm
3954#define YYLEX_PARAM parm
3955%@}
3956@end example
3957
3958You should then define @code{yylex} to accept one additional
3959argument---the value of @code{parm}. (This makes either two or three
3960arguments in total, depending on whether an argument of type
3961@code{YYLTYPE} is passed.) You can declare the argument as a pointer to
3962the proper object type, or you can declare it as @code{void *} and
3963access the contents as shown above.
3964
8c9a50be 3965You can use @samp{%pure-parser} to request a reentrant parser without
931c7513
RS
3966also using @code{YYPARSE_PARAM}. Then you should call @code{yyparse}
3967with no arguments, as usual.
3968
342b8b6e 3969@node Error Reporting
bfa74976
RS
3970@section The Error Reporting Function @code{yyerror}
3971@cindex error reporting function
3972@findex yyerror
3973@cindex parse error
3974@cindex syntax error
3975
3976The Bison parser detects a @dfn{parse error} or @dfn{syntax error}
9ecbd125 3977whenever it reads a token which cannot satisfy any syntax rule. An
bfa74976 3978action in the grammar can also explicitly proclaim an error, using the
ceed8467
AD
3979macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
3980in Actions}).
bfa74976
RS
3981
3982The Bison parser expects to report the error by calling an error
3983reporting function named @code{yyerror}, which you must supply. It is
3984called by @code{yyparse} whenever a syntax error is found, and it
3985receives one argument. For a parse error, the string is normally
3986@w{@code{"parse error"}}.
3987
3988@findex YYERROR_VERBOSE
3989If you define the macro @code{YYERROR_VERBOSE} in the Bison declarations
ceed8467
AD
3990section (@pxref{Bison Declarations, ,The Bison Declarations Section}),
3991then Bison provides a more verbose and specific error message string
3992instead of just plain @w{@code{"parse error"}}. It doesn't matter what
3993definition you use for @code{YYERROR_VERBOSE}, just whether you define
3994it.
bfa74976
RS
3995
3996The parser can detect one other kind of error: stack overflow. This
3997happens when the input contains constructions that are very deeply
3998nested. It isn't likely you will encounter this, since the Bison
3999parser extends its stack automatically up to a very large limit. But
4000if overflow happens, @code{yyparse} calls @code{yyerror} in the usual
4001fashion, except that the argument string is @w{@code{"parser stack
4002overflow"}}.
4003
4004The following definition suffices in simple programs:
4005
4006@example
4007@group
13863333
AD
4008void
4009yyerror (char *s)
bfa74976
RS
4010@{
4011@end group
4012@group
4013 fprintf (stderr, "%s\n", s);
4014@}
4015@end group
4016@end example
4017
4018After @code{yyerror} returns to @code{yyparse}, the latter will attempt
4019error recovery if you have written suitable error recovery grammar rules
4020(@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
4021immediately return 1.
4022
4023@vindex yynerrs
4024The variable @code{yynerrs} contains the number of syntax errors
4025encountered so far. Normally this variable is global; but if you
704a47c4
AD
4026request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser})
4027then it is a local variable which only the actions can access.
bfa74976 4028
342b8b6e 4029@node Action Features
bfa74976
RS
4030@section Special Features for Use in Actions
4031@cindex summary, action features
4032@cindex action features summary
4033
4034Here is a table of Bison constructs, variables and macros that
4035are useful in actions.
4036
4037@table @samp
4038@item $$
4039Acts like a variable that contains the semantic value for the
4040grouping made by the current rule. @xref{Actions}.
4041
4042@item $@var{n}
4043Acts like a variable that contains the semantic value for the
4044@var{n}th component of the current rule. @xref{Actions}.
4045
4046@item $<@var{typealt}>$
4047Like @code{$$} but specifies alternative @var{typealt} in the union
704a47c4
AD
4048specified by the @code{%union} declaration. @xref{Action Types, ,Data
4049Types of Values in Actions}.
bfa74976
RS
4050
4051@item $<@var{typealt}>@var{n}
4052Like @code{$@var{n}} but specifies alternative @var{typealt} in the
13863333 4053union specified by the @code{%union} declaration.
e0c471a9 4054@xref{Action Types, ,Data Types of Values in Actions}.
bfa74976
RS
4055
4056@item YYABORT;
4057Return immediately from @code{yyparse}, indicating failure.
4058@xref{Parser Function, ,The Parser Function @code{yyparse}}.
4059
4060@item YYACCEPT;
4061Return immediately from @code{yyparse}, indicating success.
4062@xref{Parser Function, ,The Parser Function @code{yyparse}}.
4063
4064@item YYBACKUP (@var{token}, @var{value});
4065@findex YYBACKUP
4066Unshift a token. This macro is allowed only for rules that reduce
4067a single value, and only when there is no look-ahead token.
676385e2 4068It is also disallowed in GLR parsers.
bfa74976
RS
4069It installs a look-ahead token with token type @var{token} and
4070semantic value @var{value}; then it discards the value that was
4071going to be reduced by this rule.
4072
4073If the macro is used when it is not valid, such as when there is
4074a look-ahead token already, then it reports a syntax error with
4075a message @samp{cannot back up} and performs ordinary error
4076recovery.
4077
4078In either case, the rest of the action is not executed.
4079
4080@item YYEMPTY
4081@vindex YYEMPTY
4082Value stored in @code{yychar} when there is no look-ahead token.
4083
4084@item YYERROR;
4085@findex YYERROR
4086Cause an immediate syntax error. This statement initiates error
4087recovery just as if the parser itself had detected an error; however, it
4088does not call @code{yyerror}, and does not print any message. If you
4089want to print an error message, call @code{yyerror} explicitly before
4090the @samp{YYERROR;} statement. @xref{Error Recovery}.
4091
4092@item YYRECOVERING
4093This macro stands for an expression that has the value 1 when the parser
4094is recovering from a syntax error, and 0 the rest of the time.
4095@xref{Error Recovery}.
4096
4097@item yychar
4098Variable containing the current look-ahead token. (In a pure parser,
4099this is actually a local variable within @code{yyparse}.) When there is
4100no look-ahead token, the value @code{YYEMPTY} is stored in the variable.
4101@xref{Look-Ahead, ,Look-Ahead Tokens}.
4102
4103@item yyclearin;
4104Discard the current look-ahead token. This is useful primarily in
4105error rules. @xref{Error Recovery}.
4106
4107@item yyerrok;
4108Resume generating error messages immediately for subsequent syntax
13863333 4109errors. This is useful primarily in error rules.
bfa74976
RS
4110@xref{Error Recovery}.
4111
847bf1f5
AD
4112@item @@$
4113@findex @@$
4114Acts like a structure variable containing information on the textual position
4115of the grouping made by the current rule. @xref{Locations, ,
4116Tracking Locations}.
bfa74976 4117
847bf1f5
AD
4118@c Check if those paragraphs are still useful or not.
4119
4120@c @example
4121@c struct @{
4122@c int first_line, last_line;
4123@c int first_column, last_column;
4124@c @};
4125@c @end example
4126
4127@c Thus, to get the starting line number of the third component, you would
4128@c use @samp{@@3.first_line}.
bfa74976 4129
847bf1f5
AD
4130@c In order for the members of this structure to contain valid information,
4131@c you must make @code{yylex} supply this information about each token.
4132@c If you need only certain members, then @code{yylex} need only fill in
4133@c those members.
bfa74976 4134
847bf1f5
AD
4135@c The use of this feature makes the parser noticeably slower.
4136
4137@item @@@var{n}
4138@findex @@@var{n}
4139Acts like a structure variable containing information on the textual position
4140of the @var{n}th component of the current rule. @xref{Locations, ,
4141Tracking Locations}.
bfa74976 4142
bfa74976
RS
4143@end table
4144
342b8b6e 4145@node Algorithm
13863333
AD
4146@chapter The Bison Parser Algorithm
4147@cindex Bison parser algorithm
bfa74976
RS
4148@cindex algorithm of parser
4149@cindex shifting
4150@cindex reduction
4151@cindex parser stack
4152@cindex stack, parser
4153
4154As Bison reads tokens, it pushes them onto a stack along with their
4155semantic values. The stack is called the @dfn{parser stack}. Pushing a
4156token is traditionally called @dfn{shifting}.
4157
4158For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
4159@samp{3} to come. The stack will have four elements, one for each token
4160that was shifted.
4161
4162But the stack does not always have an element for each token read. When
4163the last @var{n} tokens and groupings shifted match the components of a
4164grammar rule, they can be combined according to that rule. This is called
4165@dfn{reduction}. Those tokens and groupings are replaced on the stack by a
4166single grouping whose symbol is the result (left hand side) of that rule.
4167Running the rule's action is part of the process of reduction, because this
4168is what computes the semantic value of the resulting grouping.
4169
4170For example, if the infix calculator's parser stack contains this:
4171
4172@example
41731 + 5 * 3
4174@end example
4175
4176@noindent
4177and the next input token is a newline character, then the last three
4178elements can be reduced to 15 via the rule:
4179
4180@example
4181expr: expr '*' expr;
4182@end example
4183
4184@noindent
4185Then the stack contains just these three elements:
4186
4187@example
41881 + 15
4189@end example
4190
4191@noindent
4192At this point, another reduction can be made, resulting in the single value
419316. Then the newline token can be shifted.
4194
4195The parser tries, by shifts and reductions, to reduce the entire input down
4196to a single grouping whose symbol is the grammar's start-symbol
4197(@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
4198
4199This kind of parser is known in the literature as a bottom-up parser.
4200
4201@menu
4202* Look-Ahead:: Parser looks one token ahead when deciding what to do.
4203* Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
4204* Precedence:: Operator precedence works by resolving conflicts.
4205* Contextual Precedence:: When an operator's precedence depends on context.
4206* Parser States:: The parser is a finite-state-machine with stack.
4207* Reduce/Reduce:: When two rules are applicable in the same situation.
4208* Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
676385e2 4209* Generalized LR Parsing:: Parsing arbitrary context-free grammars.
bfa74976
RS
4210* Stack Overflow:: What happens when stack gets full. How to avoid it.
4211@end menu
4212
342b8b6e 4213@node Look-Ahead
bfa74976
RS
4214@section Look-Ahead Tokens
4215@cindex look-ahead token
4216
4217The Bison parser does @emph{not} always reduce immediately as soon as the
4218last @var{n} tokens and groupings match a rule. This is because such a
4219simple strategy is inadequate to handle most languages. Instead, when a
4220reduction is possible, the parser sometimes ``looks ahead'' at the next
4221token in order to decide what to do.
4222
4223When a token is read, it is not immediately shifted; first it becomes the
4224@dfn{look-ahead token}, which is not on the stack. Now the parser can
4225perform one or more reductions of tokens and groupings on the stack, while
4226the look-ahead token remains off to the side. When no more reductions
4227should take place, the look-ahead token is shifted onto the stack. This
4228does not mean that all possible reductions have been done; depending on the
4229token type of the look-ahead token, some rules may choose to delay their
4230application.
4231
4232Here is a simple case where look-ahead is needed. These three rules define
4233expressions which contain binary addition operators and postfix unary
4234factorial operators (@samp{!}), and allow parentheses for grouping.
4235
4236@example
4237@group
4238expr: term '+' expr
4239 | term
4240 ;
4241@end group
4242
4243@group
4244term: '(' expr ')'
4245 | term '!'
4246 | NUMBER
4247 ;
4248@end group
4249@end example
4250
4251Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
4252should be done? If the following token is @samp{)}, then the first three
4253tokens must be reduced to form an @code{expr}. This is the only valid
4254course, because shifting the @samp{)} would produce a sequence of symbols
4255@w{@code{term ')'}}, and no rule allows this.
4256
4257If the following token is @samp{!}, then it must be shifted immediately so
4258that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
4259parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
4260@code{expr}. It would then be impossible to shift the @samp{!} because
4261doing so would produce on the stack the sequence of symbols @code{expr
4262'!'}. No rule allows that sequence.
4263
4264@vindex yychar
4265The current look-ahead token is stored in the variable @code{yychar}.
4266@xref{Action Features, ,Special Features for Use in Actions}.
4267
342b8b6e 4268@node Shift/Reduce
bfa74976
RS
4269@section Shift/Reduce Conflicts
4270@cindex conflicts
4271@cindex shift/reduce conflicts
4272@cindex dangling @code{else}
4273@cindex @code{else}, dangling
4274
4275Suppose we are parsing a language which has if-then and if-then-else
4276statements, with a pair of rules like this:
4277
4278@example
4279@group
4280if_stmt:
4281 IF expr THEN stmt
4282 | IF expr THEN stmt ELSE stmt
4283 ;
4284@end group
4285@end example
4286
4287@noindent
4288Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
4289terminal symbols for specific keyword tokens.
4290
4291When the @code{ELSE} token is read and becomes the look-ahead token, the
4292contents of the stack (assuming the input is valid) are just right for
4293reduction by the first rule. But it is also legitimate to shift the
4294@code{ELSE}, because that would lead to eventual reduction by the second
4295rule.
4296
4297This situation, where either a shift or a reduction would be valid, is
4298called a @dfn{shift/reduce conflict}. Bison is designed to resolve
4299these conflicts by choosing to shift, unless otherwise directed by
4300operator precedence declarations. To see the reason for this, let's
4301contrast it with the other alternative.
4302
4303Since the parser prefers to shift the @code{ELSE}, the result is to attach
4304the else-clause to the innermost if-statement, making these two inputs
4305equivalent:
4306
4307@example
4308if x then if y then win (); else lose;
4309
4310if x then do; if y then win (); else lose; end;
4311@end example
4312
4313But if the parser chose to reduce when possible rather than shift, the
4314result would be to attach the else-clause to the outermost if-statement,
4315making these two inputs equivalent:
4316
4317@example
4318if x then if y then win (); else lose;
4319
4320if x then do; if y then win (); end; else lose;
4321@end example
4322
4323The conflict exists because the grammar as written is ambiguous: either
4324parsing of the simple nested if-statement is legitimate. The established
4325convention is that these ambiguities are resolved by attaching the
4326else-clause to the innermost if-statement; this is what Bison accomplishes
4327by choosing to shift rather than reduce. (It would ideally be cleaner to
4328write an unambiguous grammar, but that is very hard to do in this case.)
4329This particular ambiguity was first encountered in the specifications of
4330Algol 60 and is called the ``dangling @code{else}'' ambiguity.
4331
4332To avoid warnings from Bison about predictable, legitimate shift/reduce
4333conflicts, use the @code{%expect @var{n}} declaration. There will be no
4334warning as long as the number of shift/reduce conflicts is exactly @var{n}.
4335@xref{Expect Decl, ,Suppressing Conflict Warnings}.
4336
4337The definition of @code{if_stmt} above is solely to blame for the
4338conflict, but the conflict does not actually appear without additional
4339rules. Here is a complete Bison input file that actually manifests the
4340conflict:
4341
4342@example
4343@group
4344%token IF THEN ELSE variable
4345%%
4346@end group
4347@group
4348stmt: expr
4349 | if_stmt
4350 ;
4351@end group
4352
4353@group
4354if_stmt:
4355 IF expr THEN stmt
4356 | IF expr THEN stmt ELSE stmt
4357 ;
4358@end group
4359
4360expr: variable
4361 ;
4362@end example
4363
342b8b6e 4364@node Precedence
bfa74976
RS
4365@section Operator Precedence
4366@cindex operator precedence
4367@cindex precedence of operators
4368
4369Another situation where shift/reduce conflicts appear is in arithmetic
4370expressions. Here shifting is not always the preferred resolution; the
4371Bison declarations for operator precedence allow you to specify when to
4372shift and when to reduce.
4373
4374@menu
4375* Why Precedence:: An example showing why precedence is needed.
4376* Using Precedence:: How to specify precedence in Bison grammars.
4377* Precedence Examples:: How these features are used in the previous example.
4378* How Precedence:: How they work.
4379@end menu
4380
342b8b6e 4381@node Why Precedence
bfa74976
RS
4382@subsection When Precedence is Needed
4383
4384Consider the following ambiguous grammar fragment (ambiguous because the
4385input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
4386
4387@example
4388@group
4389expr: expr '-' expr
4390 | expr '*' expr
4391 | expr '<' expr
4392 | '(' expr ')'
4393 @dots{}
4394 ;
4395@end group
4396@end example
4397
4398@noindent
4399Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
14ded682
AD
4400should it reduce them via the rule for the subtraction operator? It
4401depends on the next token. Of course, if the next token is @samp{)}, we
4402must reduce; shifting is invalid because no single rule can reduce the
4403token sequence @w{@samp{- 2 )}} or anything starting with that. But if
4404the next token is @samp{*} or @samp{<}, we have a choice: either
4405shifting or reduction would allow the parse to complete, but with
4406different results.
4407
4408To decide which one Bison should do, we must consider the results. If
4409the next operator token @var{op} is shifted, then it must be reduced
4410first in order to permit another opportunity to reduce the difference.
4411The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other
4412hand, if the subtraction is reduced before shifting @var{op}, the result
4413is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or
4414reduce should depend on the relative precedence of the operators
4415@samp{-} and @var{op}: @samp{*} should be shifted first, but not
4416@samp{<}.
bfa74976
RS
4417
4418@cindex associativity
4419What about input such as @w{@samp{1 - 2 - 5}}; should this be
14ded682
AD
4420@w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most
4421operators we prefer the former, which is called @dfn{left association}.
4422The latter alternative, @dfn{right association}, is desirable for
4423assignment operators. The choice of left or right association is a
4424matter of whether the parser chooses to shift or reduce when the stack
4425contains @w{@samp{1 - 2}} and the look-ahead token is @samp{-}: shifting
4426makes right-associativity.
bfa74976 4427
342b8b6e 4428@node Using Precedence
bfa74976
RS
4429@subsection Specifying Operator Precedence
4430@findex %left
4431@findex %right
4432@findex %nonassoc
4433
4434Bison allows you to specify these choices with the operator precedence
4435declarations @code{%left} and @code{%right}. Each such declaration
4436contains a list of tokens, which are operators whose precedence and
4437associativity is being declared. The @code{%left} declaration makes all
4438those operators left-associative and the @code{%right} declaration makes
4439them right-associative. A third alternative is @code{%nonassoc}, which
4440declares that it is a syntax error to find the same operator twice ``in a
4441row''.
4442
4443The relative precedence of different operators is controlled by the
4444order in which they are declared. The first @code{%left} or
4445@code{%right} declaration in the file declares the operators whose
4446precedence is lowest, the next such declaration declares the operators
4447whose precedence is a little higher, and so on.
4448
342b8b6e 4449@node Precedence Examples
bfa74976
RS
4450@subsection Precedence Examples
4451
4452In our example, we would want the following declarations:
4453
4454@example
4455%left '<'
4456%left '-'
4457%left '*'
4458@end example
4459
4460In a more complete example, which supports other operators as well, we
4461would declare them in groups of equal precedence. For example, @code{'+'} is
4462declared with @code{'-'}:
4463
4464@example
4465%left '<' '>' '=' NE LE GE
4466%left '+' '-'
4467%left '*' '/'
4468@end example
4469
4470@noindent
4471(Here @code{NE} and so on stand for the operators for ``not equal''
4472and so on. We assume that these tokens are more than one character long
4473and therefore are represented by names, not character literals.)
4474
342b8b6e 4475@node How Precedence
bfa74976
RS
4476@subsection How Precedence Works
4477
4478The first effect of the precedence declarations is to assign precedence
4479levels to the terminal symbols declared. The second effect is to assign
704a47c4
AD
4480precedence levels to certain rules: each rule gets its precedence from
4481the last terminal symbol mentioned in the components. (You can also
4482specify explicitly the precedence of a rule. @xref{Contextual
4483Precedence, ,Context-Dependent Precedence}.)
4484
4485Finally, the resolution of conflicts works by comparing the precedence
4486of the rule being considered with that of the look-ahead token. If the
4487token's precedence is higher, the choice is to shift. If the rule's
4488precedence is higher, the choice is to reduce. If they have equal
4489precedence, the choice is made based on the associativity of that
4490precedence level. The verbose output file made by @samp{-v}
4491(@pxref{Invocation, ,Invoking Bison}) says how each conflict was
4492resolved.
bfa74976
RS
4493
4494Not all rules and not all tokens have precedence. If either the rule or
4495the look-ahead token has no precedence, then the default is to shift.
4496
342b8b6e 4497@node Contextual Precedence
bfa74976
RS
4498@section Context-Dependent Precedence
4499@cindex context-dependent precedence
4500@cindex unary operator precedence
4501@cindex precedence, context-dependent
4502@cindex precedence, unary operator
4503@findex %prec
4504
4505Often the precedence of an operator depends on the context. This sounds
4506outlandish at first, but it is really very common. For example, a minus
4507sign typically has a very high precedence as a unary operator, and a
4508somewhat lower precedence (lower than multiplication) as a binary operator.
4509
4510The Bison precedence declarations, @code{%left}, @code{%right} and
4511@code{%nonassoc}, can only be used once for a given token; so a token has
4512only one precedence declared in this way. For context-dependent
4513precedence, you need to use an additional mechanism: the @code{%prec}
e0c471a9 4514modifier for rules.
bfa74976
RS
4515
4516The @code{%prec} modifier declares the precedence of a particular rule by
4517specifying a terminal symbol whose precedence should be used for that rule.
4518It's not necessary for that symbol to appear otherwise in the rule. The
4519modifier's syntax is:
4520
4521@example
4522%prec @var{terminal-symbol}
4523@end example
4524
4525@noindent
4526and it is written after the components of the rule. Its effect is to
4527assign the rule the precedence of @var{terminal-symbol}, overriding
4528the precedence that would be deduced for it in the ordinary way. The
4529altered rule precedence then affects how conflicts involving that rule
4530are resolved (@pxref{Precedence, ,Operator Precedence}).
4531
4532Here is how @code{%prec} solves the problem of unary minus. First, declare
4533a precedence for a fictitious terminal symbol named @code{UMINUS}. There
4534are no tokens of this type, but the symbol serves to stand for its
4535precedence:
4536
4537@example
4538@dots{}
4539%left '+' '-'
4540%left '*'
4541%left UMINUS
4542@end example
4543
4544Now the precedence of @code{UMINUS} can be used in specific rules:
4545
4546@example
4547@group
4548exp: @dots{}
4549 | exp '-' exp
4550 @dots{}
4551 | '-' exp %prec UMINUS
4552@end group
4553@end example
4554
342b8b6e 4555@node Parser States
bfa74976
RS
4556@section Parser States
4557@cindex finite-state machine
4558@cindex parser state
4559@cindex state (of parser)
4560
4561The function @code{yyparse} is implemented using a finite-state machine.
4562The values pushed on the parser stack are not simply token type codes; they
4563represent the entire sequence of terminal and nonterminal symbols at or
4564near the top of the stack. The current state collects all the information
4565about previous input which is relevant to deciding what to do next.
4566
4567Each time a look-ahead token is read, the current parser state together
4568with the type of look-ahead token are looked up in a table. This table
4569entry can say, ``Shift the look-ahead token.'' In this case, it also
4570specifies the new parser state, which is pushed onto the top of the
4571parser stack. Or it can say, ``Reduce using rule number @var{n}.''
4572This means that a certain number of tokens or groupings are taken off
4573the top of the stack, and replaced by one grouping. In other words,
4574that number of states are popped from the stack, and one new state is
4575pushed.
4576
4577There is one other alternative: the table can say that the look-ahead token
4578is erroneous in the current state. This causes error processing to begin
4579(@pxref{Error Recovery}).
4580
342b8b6e 4581@node Reduce/Reduce
bfa74976
RS
4582@section Reduce/Reduce Conflicts
4583@cindex reduce/reduce conflict
4584@cindex conflicts, reduce/reduce
4585
4586A reduce/reduce conflict occurs if there are two or more rules that apply
4587to the same sequence of input. This usually indicates a serious error
4588in the grammar.
4589
4590For example, here is an erroneous attempt to define a sequence
4591of zero or more @code{word} groupings.
4592
4593@example
4594sequence: /* empty */
4595 @{ printf ("empty sequence\n"); @}
4596 | maybeword
4597 | sequence word
4598 @{ printf ("added word %s\n", $2); @}
4599 ;
4600
4601maybeword: /* empty */
4602 @{ printf ("empty maybeword\n"); @}
4603 | word
4604 @{ printf ("single word %s\n", $1); @}
4605 ;
4606@end example
4607
4608@noindent
4609The error is an ambiguity: there is more than one way to parse a single
4610@code{word} into a @code{sequence}. It could be reduced to a
4611@code{maybeword} and then into a @code{sequence} via the second rule.
4612Alternatively, nothing-at-all could be reduced into a @code{sequence}
4613via the first rule, and this could be combined with the @code{word}
4614using the third rule for @code{sequence}.
4615
4616There is also more than one way to reduce nothing-at-all into a
4617@code{sequence}. This can be done directly via the first rule,
4618or indirectly via @code{maybeword} and then the second rule.
4619
4620You might think that this is a distinction without a difference, because it
4621does not change whether any particular input is valid or not. But it does
4622affect which actions are run. One parsing order runs the second rule's
4623action; the other runs the first rule's action and the third rule's action.
4624In this example, the output of the program changes.
4625
4626Bison resolves a reduce/reduce conflict by choosing to use the rule that
4627appears first in the grammar, but it is very risky to rely on this. Every
4628reduce/reduce conflict must be studied and usually eliminated. Here is the
4629proper way to define @code{sequence}:
4630
4631@example
4632sequence: /* empty */
4633 @{ printf ("empty sequence\n"); @}
4634 | sequence word
4635 @{ printf ("added word %s\n", $2); @}
4636 ;
4637@end example
4638
4639Here is another common error that yields a reduce/reduce conflict:
4640
4641@example
4642sequence: /* empty */
4643 | sequence words
4644 | sequence redirects
4645 ;
4646
4647words: /* empty */
4648 | words word
4649 ;
4650
4651redirects:/* empty */
4652 | redirects redirect
4653 ;
4654@end example
4655
4656@noindent
4657The intention here is to define a sequence which can contain either
4658@code{word} or @code{redirect} groupings. The individual definitions of
4659@code{sequence}, @code{words} and @code{redirects} are error-free, but the
4660three together make a subtle ambiguity: even an empty input can be parsed
4661in infinitely many ways!
4662
4663Consider: nothing-at-all could be a @code{words}. Or it could be two
4664@code{words} in a row, or three, or any number. It could equally well be a
4665@code{redirects}, or two, or any number. Or it could be a @code{words}
4666followed by three @code{redirects} and another @code{words}. And so on.
4667
4668Here are two ways to correct these rules. First, to make it a single level
4669of sequence:
4670
4671@example
4672sequence: /* empty */
4673 | sequence word
4674 | sequence redirect
4675 ;
4676@end example
4677
4678Second, to prevent either a @code{words} or a @code{redirects}
4679from being empty:
4680
4681@example
4682sequence: /* empty */
4683 | sequence words
4684 | sequence redirects
4685 ;
4686
4687words: word
4688 | words word
4689 ;
4690
4691redirects:redirect
4692 | redirects redirect
4693 ;
4694@end example
4695
342b8b6e 4696@node Mystery Conflicts
bfa74976
RS
4697@section Mysterious Reduce/Reduce Conflicts
4698
4699Sometimes reduce/reduce conflicts can occur that don't look warranted.
4700Here is an example:
4701
4702@example
4703@group
4704%token ID
4705
4706%%
4707def: param_spec return_spec ','
4708 ;
4709param_spec:
4710 type
4711 | name_list ':' type
4712 ;
4713@end group
4714@group
4715return_spec:
4716 type
4717 | name ':' type
4718 ;
4719@end group
4720@group
4721type: ID
4722 ;
4723@end group
4724@group
4725name: ID
4726 ;
4727name_list:
4728 name
4729 | name ',' name_list
4730 ;
4731@end group
4732@end example
4733
4734It would seem that this grammar can be parsed with only a single token
13863333 4735of look-ahead: when a @code{param_spec} is being read, an @code{ID} is
bfa74976
RS
4736a @code{name} if a comma or colon follows, or a @code{type} if another
4737@code{ID} follows. In other words, this grammar is LR(1).
4738
4739@cindex LR(1)
4740@cindex LALR(1)
4741However, Bison, like most parser generators, cannot actually handle all
4742LR(1) grammars. In this grammar, two contexts, that after an @code{ID}
4743at the beginning of a @code{param_spec} and likewise at the beginning of
4744a @code{return_spec}, are similar enough that Bison assumes they are the
4745same. They appear similar because the same set of rules would be
4746active---the rule for reducing to a @code{name} and that for reducing to
4747a @code{type}. Bison is unable to determine at that stage of processing
4748that the rules would require different look-ahead tokens in the two
4749contexts, so it makes a single parser state for them both. Combining
4750the two contexts causes a conflict later. In parser terminology, this
4751occurrence means that the grammar is not LALR(1).
4752
4753In general, it is better to fix deficiencies than to document them. But
4754this particular deficiency is intrinsically hard to fix; parser
4755generators that can handle LR(1) grammars are hard to write and tend to
4756produce parsers that are very large. In practice, Bison is more useful
4757as it is now.
4758
4759When the problem arises, you can often fix it by identifying the two
a220f555
MA
4760parser states that are being confused, and adding something to make them
4761look distinct. In the above example, adding one rule to
bfa74976
RS
4762@code{return_spec} as follows makes the problem go away:
4763
4764@example
4765@group
4766%token BOGUS
4767@dots{}
4768%%
4769@dots{}
4770return_spec:
4771 type
4772 | name ':' type
4773 /* This rule is never used. */
4774 | ID BOGUS
4775 ;
4776@end group
4777@end example
4778
4779This corrects the problem because it introduces the possibility of an
4780additional active rule in the context after the @code{ID} at the beginning of
4781@code{return_spec}. This rule is not active in the corresponding context
4782in a @code{param_spec}, so the two contexts receive distinct parser states.
4783As long as the token @code{BOGUS} is never generated by @code{yylex},
4784the added rule cannot alter the way actual input is parsed.
4785
4786In this particular example, there is another way to solve the problem:
4787rewrite the rule for @code{return_spec} to use @code{ID} directly
4788instead of via @code{name}. This also causes the two confusing
4789contexts to have different sets of active rules, because the one for
4790@code{return_spec} activates the altered rule for @code{return_spec}
4791rather than the one for @code{name}.
4792
4793@example
4794param_spec:
4795 type
4796 | name_list ':' type
4797 ;
4798return_spec:
4799 type
4800 | ID ':' type
4801 ;
4802@end example
4803
fae437e8 4804@node Generalized LR Parsing
676385e2
PH
4805@section Generalized LR (GLR) Parsing
4806@cindex GLR parsing
4807@cindex generalized LR (GLR) parsing
4808@cindex ambiguous grammars
4809@cindex non-deterministic parsing
4810
fae437e8
AD
4811Bison produces @emph{deterministic} parsers that choose uniquely
4812when to reduce and which reduction to apply
676385e2
PH
4813based on a summary of the preceding input and on one extra token of lookahead.
4814As a result, normal Bison handles a proper subset of the family of
4815context-free languages.
fae437e8 4816Ambiguous grammars, since they have strings with more than one possible
676385e2
PH
4817sequence of reductions cannot have deterministic parsers in this sense.
4818The same is true of languages that require more than one symbol of
4819lookahead, since the parser lacks the information necessary to make a
4820decision at the point it must be made in a shift-reduce parser.
fae437e8 4821Finally, as previously mentioned (@pxref{Mystery Conflicts}),
676385e2
PH
4822there are languages where Bison's particular choice of how to
4823summarize the input seen so far loses necessary information.
4824
4825When you use the @samp{%glr-parser} declaration in your grammar file,
4826Bison generates a parser that uses a different algorithm, called
4827Generalized LR (or GLR). A Bison GLR parser uses the same basic
4828algorithm for parsing as an ordinary Bison parser, but behaves
4829differently in cases where there is a shift-reduce conflict that has not
fae437e8 4830been resolved by precedence rules (@pxref{Precedence}) or a
676385e2 4831reduce-reduce conflict. When a GLR parser encounters such a situation, it
fae437e8 4832effectively @emph{splits} into a several parsers, one for each possible
676385e2
PH
4833shift or reduction. These parsers then proceed as usual, consuming
4834tokens in lock-step. Some of the stacks may encounter other conflicts
fae437e8
AD
4835and split further, with the result that instead of a sequence of states,
4836a Bison GLR parsing stack is what is in effect a tree of states.
676385e2
PH
4837
4838In effect, each stack represents a guess as to what the proper parse
4839is. Additional input may indicate that a guess was wrong, in which case
4840the appropriate stack silently disappears. Otherwise, the semantics
fae437e8 4841actions generated in each stack are saved, rather than being executed
676385e2 4842immediately. When a stack disappears, its saved semantic actions never
fae437e8 4843get executed. When a reduction causes two stacks to become equivalent,
676385e2
PH
4844their sets of semantic actions are both saved with the state that
4845results from the reduction. We say that two stacks are equivalent
fae437e8 4846when they both represent the same sequence of states,
676385e2
PH
4847and each pair of corresponding states represents a
4848grammar symbol that produces the same segment of the input token
4849stream.
4850
4851Whenever the parser makes a transition from having multiple
4852states to having one, it reverts to the normal LALR(1) parsing
4853algorithm, after resolving and executing the saved-up actions.
4854At this transition, some of the states on the stack will have semantic
4855values that are sets (actually multisets) of possible actions. The
4856parser tries to pick one of the actions by first finding one whose rule
4857has the highest dynamic precedence, as set by the @samp{%dprec}
fae437e8 4858declaration. Otherwise, if the alternative actions are not ordered by
676385e2 4859precedence, but there the same merging function is declared for both
fae437e8 4860rules by the @samp{%merge} declaration,
676385e2
PH
4861Bison resolves and evaluates both and then calls the merge function on
4862the result. Otherwise, it reports an ambiguity.
4863
4864It is possible to use a data structure for the GLR parsing tree that
4865permits the processing of any LALR(1) grammar in linear time (in the
4866size of the input), any unambiguous (not necessarily LALR(1)) grammar in
fae437e8 4867quadratic worst-case time, and any general (possibly ambiguous)
676385e2
PH
4868context-free grammar in cubic worst-case time. However, Bison currently
4869uses a simpler data structure that requires time proportional to the
4870length of the input times the maximum number of stacks required for any
4871prefix of the input. Thus, really ambiguous or non-deterministic
4872grammars can require exponential time and space to process. Such badly
4873behaving examples, however, are not generally of practical interest.
4874Usually, non-determinism in a grammar is local---the parser is ``in
4875doubt'' only for a few tokens at a time. Therefore, the current data
4876structure should generally be adequate. On LALR(1) portions of a
4877grammar, in particular, it is only slightly slower than with the default
4878Bison parser.
4879
342b8b6e 4880@node Stack Overflow
bfa74976
RS
4881@section Stack Overflow, and How to Avoid It
4882@cindex stack overflow
4883@cindex parser stack overflow
4884@cindex overflow of parser stack
4885
4886The Bison parser stack can overflow if too many tokens are shifted and
4887not reduced. When this happens, the parser function @code{yyparse}
4888returns a nonzero value, pausing only to call @code{yyerror} to report
4889the overflow.
4890
4891@vindex YYMAXDEPTH
4892By defining the macro @code{YYMAXDEPTH}, you can control how deep the
4893parser stack can become before a stack overflow occurs. Define the
4894macro with a value that is an integer. This value is the maximum number
4895of tokens that can be shifted (and not reduced) before overflow.
4896It must be a constant expression whose value is known at compile time.
4897
4898The stack space allowed is not necessarily allocated. If you specify a
4899large value for @code{YYMAXDEPTH}, the parser actually allocates a small
4900stack at first, and then makes it bigger by stages as needed. This
4901increasing allocation happens automatically and silently. Therefore,
4902you do not need to make @code{YYMAXDEPTH} painfully small merely to save
4903space for ordinary inputs that do not need much stack.
4904
4905@cindex default stack limit
4906The default value of @code{YYMAXDEPTH}, if you do not define it, is
490710000.
4908
4909@vindex YYINITDEPTH
4910You can control how much stack is allocated initially by defining the
4911macro @code{YYINITDEPTH}. This value too must be a compile-time
4912constant integer. The default is 200.
4913
342b8b6e 4914@node Error Recovery
bfa74976
RS
4915@chapter Error Recovery
4916@cindex error recovery
4917@cindex recovery from errors
4918
4919It is not usually acceptable to have a program terminate on a parse
4920error. For example, a compiler should recover sufficiently to parse the
4921rest of the input file and check it for errors; a calculator should accept
4922another expression.
4923
4924In a simple interactive command parser where each input is one line, it may
4925be sufficient to allow @code{yyparse} to return 1 on error and have the
4926caller ignore the rest of the input line when that happens (and then call
4927@code{yyparse} again). But this is inadequate for a compiler, because it
4928forgets all the syntactic context leading up to the error. A syntax error
4929deep within a function in the compiler input should not cause the compiler
4930to treat the following line like the beginning of a source file.
4931
4932@findex error
4933You can define how to recover from a syntax error by writing rules to
4934recognize the special token @code{error}. This is a terminal symbol that
4935is always defined (you need not declare it) and reserved for error
4936handling. The Bison parser generates an @code{error} token whenever a
4937syntax error happens; if you have provided a rule to recognize this token
13863333 4938in the current context, the parse can continue.
bfa74976
RS
4939
4940For example:
4941
4942@example
4943stmnts: /* empty string */
4944 | stmnts '\n'
4945 | stmnts exp '\n'
4946 | stmnts error '\n'
4947@end example
4948
4949The fourth rule in this example says that an error followed by a newline
4950makes a valid addition to any @code{stmnts}.
4951
4952What happens if a syntax error occurs in the middle of an @code{exp}? The
4953error recovery rule, interpreted strictly, applies to the precise sequence
4954of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
4955the middle of an @code{exp}, there will probably be some additional tokens
4956and subexpressions on the stack after the last @code{stmnts}, and there
4957will be tokens to read before the next newline. So the rule is not
4958applicable in the ordinary way.
4959
4960But Bison can force the situation to fit the rule, by discarding part of
4961the semantic context and part of the input. First it discards states and
4962objects from the stack until it gets back to a state in which the
4963@code{error} token is acceptable. (This means that the subexpressions
4964already parsed are discarded, back to the last complete @code{stmnts}.) At
4965this point the @code{error} token can be shifted. Then, if the old
4966look-ahead token is not acceptable to be shifted next, the parser reads
4967tokens and discards them until it finds a token which is acceptable. In
4968this example, Bison reads and discards input until the next newline
4969so that the fourth rule can apply.
4970
4971The choice of error rules in the grammar is a choice of strategies for
4972error recovery. A simple and useful strategy is simply to skip the rest of
4973the current input line or current statement if an error is detected:
4974
4975@example
4976stmnt: error ';' /* on error, skip until ';' is read */
4977@end example
4978
4979It is also useful to recover to the matching close-delimiter of an
4980opening-delimiter that has already been parsed. Otherwise the
4981close-delimiter will probably appear to be unmatched, and generate another,
4982spurious error message:
4983
4984@example
4985primary: '(' expr ')'
4986 | '(' error ')'
4987 @dots{}
4988 ;
4989@end example
4990
4991Error recovery strategies are necessarily guesses. When they guess wrong,
4992one syntax error often leads to another. In the above example, the error
4993recovery rule guesses that an error is due to bad input within one
4994@code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
4995middle of a valid @code{stmnt}. After the error recovery rule recovers
4996from the first error, another syntax error will be found straightaway,
4997since the text following the spurious semicolon is also an invalid
4998@code{stmnt}.
4999
5000To prevent an outpouring of error messages, the parser will output no error
5001message for another syntax error that happens shortly after the first; only
5002after three consecutive input tokens have been successfully shifted will
5003error messages resume.
5004
5005Note that rules which accept the @code{error} token may have actions, just
5006as any other rules can.
5007
5008@findex yyerrok
5009You can make error messages resume immediately by using the macro
5010@code{yyerrok} in an action. If you do this in the error rule's action, no
5011error messages will be suppressed. This macro requires no arguments;
5012@samp{yyerrok;} is a valid C statement.
5013
5014@findex yyclearin
5015The previous look-ahead token is reanalyzed immediately after an error. If
5016this is unacceptable, then the macro @code{yyclearin} may be used to clear
5017this token. Write the statement @samp{yyclearin;} in the error rule's
5018action.
5019
5020For example, suppose that on a parse error, an error handling routine is
5021called that advances the input stream to some point where parsing should
5022once again commence. The next symbol returned by the lexical scanner is
5023probably correct. The previous look-ahead token ought to be discarded
5024with @samp{yyclearin;}.
5025
5026@vindex YYRECOVERING
5027The macro @code{YYRECOVERING} stands for an expression that has the
5028value 1 when the parser is recovering from a syntax error, and 0 the
5029rest of the time. A value of 1 indicates that error messages are
5030currently suppressed for new syntax errors.
5031
342b8b6e 5032@node Context Dependency
bfa74976
RS
5033@chapter Handling Context Dependencies
5034
5035The Bison paradigm is to parse tokens first, then group them into larger
5036syntactic units. In many languages, the meaning of a token is affected by
5037its context. Although this violates the Bison paradigm, certain techniques
5038(known as @dfn{kludges}) may enable you to write Bison parsers for such
5039languages.
5040
5041@menu
5042* Semantic Tokens:: Token parsing can depend on the semantic context.
5043* Lexical Tie-ins:: Token parsing can depend on the syntactic context.
5044* Tie-in Recovery:: Lexical tie-ins have implications for how
5045 error recovery rules must be written.
5046@end menu
5047
5048(Actually, ``kludge'' means any technique that gets its job done but is
5049neither clean nor robust.)
5050
342b8b6e 5051@node Semantic Tokens
bfa74976
RS
5052@section Semantic Info in Token Types
5053
5054The C language has a context dependency: the way an identifier is used
5055depends on what its current meaning is. For example, consider this:
5056
5057@example
5058foo (x);
5059@end example
5060
5061This looks like a function call statement, but if @code{foo} is a typedef
5062name, then this is actually a declaration of @code{x}. How can a Bison
5063parser for C decide how to parse this input?
5064
5065The method used in GNU C is to have two different token types,
5066@code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
5067identifier, it looks up the current declaration of the identifier in order
5068to decide which token type to return: @code{TYPENAME} if the identifier is
5069declared as a typedef, @code{IDENTIFIER} otherwise.
5070
5071The grammar rules can then express the context dependency by the choice of
5072token type to recognize. @code{IDENTIFIER} is accepted as an expression,
5073but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
5074@code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
5075is @emph{not} significant, such as in declarations that can shadow a
5076typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
5077accepted---there is one rule for each of the two token types.
5078
5079This technique is simple to use if the decision of which kinds of
5080identifiers to allow is made at a place close to where the identifier is
5081parsed. But in C this is not always so: C allows a declaration to
5082redeclare a typedef name provided an explicit type has been specified
5083earlier:
5084
5085@example
5086typedef int foo, bar, lose;
5087static foo (bar); /* @r{redeclare @code{bar} as static variable} */
5088static int foo (lose); /* @r{redeclare @code{foo} as function} */
5089@end example
5090
5091Unfortunately, the name being declared is separated from the declaration
5092construct itself by a complicated syntactic structure---the ``declarator''.
5093
9ecbd125 5094As a result, part of the Bison parser for C needs to be duplicated, with
14ded682
AD
5095all the nonterminal names changed: once for parsing a declaration in
5096which a typedef name can be redefined, and once for parsing a
5097declaration in which that can't be done. Here is a part of the
5098duplication, with actions omitted for brevity:
bfa74976
RS
5099
5100@example
5101initdcl:
5102 declarator maybeasm '='
5103 init
5104 | declarator maybeasm
5105 ;
5106
5107notype_initdcl:
5108 notype_declarator maybeasm '='
5109 init
5110 | notype_declarator maybeasm
5111 ;
5112@end example
5113
5114@noindent
5115Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
5116cannot. The distinction between @code{declarator} and
5117@code{notype_declarator} is the same sort of thing.
5118
5119There is some similarity between this technique and a lexical tie-in
5120(described next), in that information which alters the lexical analysis is
5121changed during parsing by other parts of the program. The difference is
5122here the information is global, and is used for other purposes in the
5123program. A true lexical tie-in has a special-purpose flag controlled by
5124the syntactic context.
5125
342b8b6e 5126@node Lexical Tie-ins
bfa74976
RS
5127@section Lexical Tie-ins
5128@cindex lexical tie-in
5129
5130One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
5131which is set by Bison actions, whose purpose is to alter the way tokens are
5132parsed.
5133
5134For example, suppose we have a language vaguely like C, but with a special
5135construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
5136an expression in parentheses in which all integers are hexadecimal. In
5137particular, the token @samp{a1b} must be treated as an integer rather than
5138as an identifier if it appears in that context. Here is how you can do it:
5139
5140@example
5141@group
5142%@{
5143int hexflag;
5144%@}
5145%%
5146@dots{}
5147@end group
5148@group
5149expr: IDENTIFIER
5150 | constant
5151 | HEX '('
5152 @{ hexflag = 1; @}
5153 expr ')'
5154 @{ hexflag = 0;
5155 $$ = $4; @}
5156 | expr '+' expr
5157 @{ $$ = make_sum ($1, $3); @}
5158 @dots{}
5159 ;
5160@end group
5161
5162@group
5163constant:
5164 INTEGER
5165 | STRING
5166 ;
5167@end group
5168@end example
5169
5170@noindent
5171Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
5172it is nonzero, all integers are parsed in hexadecimal, and tokens starting
5173with letters are parsed as integers if possible.
5174
342b8b6e
AD
5175The declaration of @code{hexflag} shown in the prologue of the parser file
5176is needed to make it accessible to the actions (@pxref{Prologue, ,The Prologue}).
75f5aaea 5177You must also write the code in @code{yylex} to obey the flag.
bfa74976 5178
342b8b6e 5179@node Tie-in Recovery
bfa74976
RS
5180@section Lexical Tie-ins and Error Recovery
5181
5182Lexical tie-ins make strict demands on any error recovery rules you have.
5183@xref{Error Recovery}.
5184
5185The reason for this is that the purpose of an error recovery rule is to
5186abort the parsing of one construct and resume in some larger construct.
5187For example, in C-like languages, a typical error recovery rule is to skip
5188tokens until the next semicolon, and then start a new statement, like this:
5189
5190@example
5191stmt: expr ';'
5192 | IF '(' expr ')' stmt @{ @dots{} @}
5193 @dots{}
5194 error ';'
5195 @{ hexflag = 0; @}
5196 ;
5197@end example
5198
5199If there is a syntax error in the middle of a @samp{hex (@var{expr})}
5200construct, this error rule will apply, and then the action for the
5201completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
5202remain set for the entire rest of the input, or until the next @code{hex}
5203keyword, causing identifiers to be misinterpreted as integers.
5204
5205To avoid this problem the error recovery rule itself clears @code{hexflag}.
5206
5207There may also be an error recovery rule that works within expressions.
5208For example, there could be a rule which applies within parentheses
5209and skips to the close-parenthesis:
5210
5211@example
5212@group
5213expr: @dots{}
5214 | '(' expr ')'
5215 @{ $$ = $2; @}
5216 | '(' error ')'
5217 @dots{}
5218@end group
5219@end example
5220
5221If this rule acts within the @code{hex} construct, it is not going to abort
5222that construct (since it applies to an inner level of parentheses within
5223the construct). Therefore, it should not clear the flag: the rest of
5224the @code{hex} construct should be parsed with the flag still in effect.
5225
5226What if there is an error recovery rule which might abort out of the
5227@code{hex} construct or might not, depending on circumstances? There is no
5228way you can write the action to determine whether a @code{hex} construct is
5229being aborted or not. So if you are using a lexical tie-in, you had better
5230make sure your error recovery rules are not of this kind. Each rule must
5231be such that you can be sure that it always will, or always won't, have to
5232clear the flag.
5233
ec3bc396
AD
5234@c ================================================== Debugging Your Parser
5235
342b8b6e 5236@node Debugging
bfa74976 5237@chapter Debugging Your Parser
ec3bc396
AD
5238
5239Developing a parser can be a challenge, especially if you don't
5240understand the algorithm (@pxref{Algorithm, ,The Bison Parser
5241Algorithm}). Even so, sometimes a detailed description of the automaton
5242can help (@pxref{Understanding, , Understanding Your Parser}), or
5243tracing the execution of the parser can give some insight on why it
5244behaves improperly (@pxref{Tracing, , Tracing Your Parser}).
5245
5246@menu
5247* Understanding:: Understanding the structure of your parser.
5248* Tracing:: Tracing the execution of your parser.
5249@end menu
5250
5251@node Understanding
5252@section Understanding Your Parser
5253
5254As documented elsewhere (@pxref{Algorithm, ,The Bison Parser Algorithm})
5255Bison parsers are @dfn{shift/reduce automata}. In some cases (much more
5256frequent than one would hope), looking at this automaton is required to
5257tune or simply fix a parser. Bison provides two different
5258representation of it, either textually or graphically (as a @sc{vcg}
5259file).
5260
5261The textual file is generated when the options @option{--report} or
5262@option{--verbose} are specified, see @xref{Invocation, , Invoking
5263Bison}. Its name is made by removing @samp{.tab.c} or @samp{.c} from
5264the parser output file name, and adding @samp{.output} instead.
5265Therefore, if the input file is @file{foo.y}, then the parser file is
5266called @file{foo.tab.c} by default. As a consequence, the verbose
5267output file is called @file{foo.output}.
5268
5269The following grammar file, @file{calc.y}, will be used in the sequel:
5270
5271@example
5272%token NUM STR
5273%left '+' '-'
5274%left '*'
5275%%
5276exp: exp '+' exp
5277 | exp '-' exp
5278 | exp '*' exp
5279 | exp '/' exp
5280 | NUM
5281 ;
5282useless: STR;
5283%%
5284@end example
5285
88bce5a2
AD
5286@command{bison} reports:
5287
5288@example
5289calc.y: warning: 1 useless nonterminal and 1 useless rule
5290calc.y:11.1-7: warning: useless nonterminal: useless
5291calc.y:11.8-12: warning: useless rule: useless: STR
5292calc.y contains 7 shift/reduce conflicts.
5293@end example
5294
5295When given @option{--report=state}, in addition to @file{calc.tab.c}, it
5296creates a file @file{calc.output} with contents detailed below. The
5297order of the output and the exact presentation might vary, but the
5298interpretation is the same.
ec3bc396
AD
5299
5300The first section includes details on conflicts that were solved thanks
5301to precedence and/or associativity:
5302
5303@example
5304Conflict in state 8 between rule 2 and token '+' resolved as reduce.
5305Conflict in state 8 between rule 2 and token '-' resolved as reduce.
5306Conflict in state 8 between rule 2 and token '*' resolved as shift.
5307@exdent @dots{}
5308@end example
5309
5310@noindent
5311The next section lists states that still have conflicts.
5312
5313@example
5314State 8 contains 1 shift/reduce conflict.
5315State 9 contains 1 shift/reduce conflict.
5316State 10 contains 1 shift/reduce conflict.
5317State 11 contains 4 shift/reduce conflicts.
5318@end example
5319
5320@noindent
5321@cindex token, useless
5322@cindex useless token
5323@cindex nonterminal, useless
5324@cindex useless nonterminal
5325@cindex rule, useless
5326@cindex useless rule
5327The next section reports useless tokens, nonterminal and rules. Useless
5328nonterminals and rules are removed in order to produce a smaller parser,
5329but useless tokens are preserved, since they might be used by the
5330scanner (note the difference between ``useless'' and ``not used''
5331below):
5332
5333@example
5334Useless nonterminals:
5335 useless
5336
5337Terminals which are not used:
5338 STR
5339
5340Useless rules:
5341#6 useless: STR;
5342@end example
5343
5344@noindent
5345The next section reproduces the exact grammar that Bison used:
5346
5347@example
5348Grammar
5349
5350 Number, Line, Rule
88bce5a2 5351 0 5 $accept -> exp $end
ec3bc396
AD
5352 1 5 exp -> exp '+' exp
5353 2 6 exp -> exp '-' exp
5354 3 7 exp -> exp '*' exp
5355 4 8 exp -> exp '/' exp
5356 5 9 exp -> NUM
5357@end example
5358
5359@noindent
5360and reports the uses of the symbols:
5361
5362@example
5363Terminals, with rules where they appear
5364
88bce5a2 5365$end (0) 0
ec3bc396
AD
5366'*' (42) 3
5367'+' (43) 1
5368'-' (45) 2
5369'/' (47) 4
5370error (256)
5371NUM (258) 5
5372
5373Nonterminals, with rules where they appear
5374
88bce5a2 5375$accept (8)
ec3bc396
AD
5376 on left: 0
5377exp (9)
5378 on left: 1 2 3 4 5, on right: 0 1 2 3 4
5379@end example
5380
5381@noindent
5382@cindex item
5383@cindex pointed rule
5384@cindex rule, pointed
5385Bison then proceeds onto the automaton itself, describing each state
5386with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
5387item is a production rule together with a point (marked by @samp{.})
5388that the input cursor.
5389
5390@example
5391state 0
5392
88bce5a2 5393 $accept -> . exp $ (rule 0)
ec3bc396
AD
5394
5395 NUM shift, and go to state 1
5396
5397 exp go to state 2
5398@end example
5399
5400This reads as follows: ``state 0 corresponds to being at the very
5401beginning of the parsing, in the initial rule, right before the start
5402symbol (here, @code{exp}). When the parser returns to this state right
5403after having reduced a rule that produced an @code{exp}, the control
5404flow jumps to state 2. If there is no such transition on a nonterminal
5405symbol, and the lookahead is a @code{NUM}, then this token is shifted on
5406the parse stack, and the control flow jumps to state 1. Any other
5407lookahead triggers a parse error.''
5408
5409@cindex core, item set
5410@cindex item set core
5411@cindex kernel, item set
5412@cindex item set core
5413Even though the only active rule in state 0 seems to be rule 0, the
5414report lists @code{NUM} as a lookahead symbol because @code{NUM} can be
5415at the beginning of any rule deriving an @code{exp}. By default Bison
5416reports the so-called @dfn{core} or @dfn{kernel} of the item set, but if
5417you want to see more detail you can invoke @command{bison} with
5418@option{--report=itemset} to list all the items, include those that can
5419be derived:
5420
5421@example
5422state 0
5423
88bce5a2 5424 $accept -> . exp $ (rule 0)
ec3bc396
AD
5425 exp -> . exp '+' exp (rule 1)
5426 exp -> . exp '-' exp (rule 2)
5427 exp -> . exp '*' exp (rule 3)
5428 exp -> . exp '/' exp (rule 4)
5429 exp -> . NUM (rule 5)
5430
5431 NUM shift, and go to state 1
5432
5433 exp go to state 2
5434@end example
5435
5436@noindent
5437In the state 1...
5438
5439@example
5440state 1
5441
5442 exp -> NUM . (rule 5)
5443
5444 $default reduce using rule 5 (exp)
5445@end example
5446
5447@noindent
5448the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead
5449(@samp{$default}), the parser will reduce it. If it was coming from
5450state 0, then, after this reduction it will return to state 0, and will
5451jump to state 2 (@samp{exp: go to state 2}).
5452
5453@example
5454state 2
5455
88bce5a2 5456 $accept -> exp . $ (rule 0)
ec3bc396
AD
5457 exp -> exp . '+' exp (rule 1)
5458 exp -> exp . '-' exp (rule 2)
5459 exp -> exp . '*' exp (rule 3)
5460 exp -> exp . '/' exp (rule 4)
5461
5462 $ shift, and go to state 3
5463 '+' shift, and go to state 4
5464 '-' shift, and go to state 5
5465 '*' shift, and go to state 6
5466 '/' shift, and go to state 7
5467@end example
5468
5469@noindent
5470In state 2, the automaton can only shift a symbol. For instance,
5471because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
5472@samp{+}, it will be shifted on the parse stack, and the automaton
5473control will jump to state 4, corresponding to the item @samp{exp -> exp
5474'+' . exp}. Since there is no default action, any other token than
5475those listed above will trigger a parse error.
5476
5477The state 3 is named the @dfn{final state}, or the @dfn{accepting
5478state}:
5479
5480@example
5481state 3
5482
88bce5a2 5483 $accept -> exp $ . (rule 0)
ec3bc396
AD
5484
5485 $default accept
5486@end example
5487
5488@noindent
5489the initial rule is completed (the start symbol and the end
5490of input were read), the parsing exits successfully.
5491
5492The interpretation of states 4 to 7 is straightforward, and is left to
5493the reader.
5494
5495@example
5496state 4
5497
5498 exp -> exp '+' . exp (rule 1)
5499
5500 NUM shift, and go to state 1
5501
5502 exp go to state 8
5503
5504state 5
5505
5506 exp -> exp '-' . exp (rule 2)
5507
5508 NUM shift, and go to state 1
5509
5510 exp go to state 9
5511
5512state 6
5513
5514 exp -> exp '*' . exp (rule 3)
5515
5516 NUM shift, and go to state 1
5517
5518 exp go to state 10
5519
5520state 7
5521
5522 exp -> exp '/' . exp (rule 4)
5523
5524 NUM shift, and go to state 1
5525
5526 exp go to state 11
5527@end example
5528
5529As was announced in beginning of the report, @samp{State 8 contains 1
5530shift/reduce conflict}:
5531
5532@example
5533state 8
5534
5535 exp -> exp . '+' exp (rule 1)
5536 exp -> exp '+' exp . (rule 1)
5537 exp -> exp . '-' exp (rule 2)
5538 exp -> exp . '*' exp (rule 3)
5539 exp -> exp . '/' exp (rule 4)
5540
5541 '*' shift, and go to state 6
5542 '/' shift, and go to state 7
5543
5544 '/' [reduce using rule 1 (exp)]
5545 $default reduce using rule 1 (exp)
5546@end example
5547
5548Indeed, there are two actions associated to the lookahead @samp{/}:
5549either shifting (and going to state 7), or reducing rule 1. The
5550conflict means that either the grammar is ambiguous, or the parser lacks
5551information to make the right decision. Indeed the grammar is
5552ambiguous, as, since we did not specify the precedence of @samp{/}, the
5553sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM /
5554NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM + NUM) /
5555NUM}, which corresponds to reducing rule 1.
5556
5557Because in LALR(1) parsing a single decision can be made, Bison
5558arbitrarily chose to disable the reduction, see @ref{Shift/Reduce, ,
5559Shift/Reduce Conflicts}. Discarded actions are reported in between
5560square brackets.
5561
5562Note that all the previous states had a single possible action: either
5563shifting the next token and going to the corresponding state, or
5564reducing a single rule. In the other cases, i.e., when shifting
5565@emph{and} reducing is possible or when @emph{several} reductions are
5566possible, the lookahead is required to select the action. State 8 is
5567one such state: if the lookahead is @samp{*} or @samp{/} then the action
5568is shifting, otherwise the action is reducing rule 1. In other words,
5569the first two items, corresponding to rule 1, are not eligible when the
5570lookahead is @samp{*}, since we specified that @samp{*} has higher
5571precedence that @samp{+}. More generally, some items are eligible only
5572with some set of possible lookaheads. When run with
5573@option{--report=lookahead}, Bison specifies these lookaheads:
5574
5575@example
5576state 8
5577
5578 exp -> exp . '+' exp [$, '+', '-', '/'] (rule 1)
5579 exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1)
5580 exp -> exp . '-' exp (rule 2)
5581 exp -> exp . '*' exp (rule 3)
5582 exp -> exp . '/' exp (rule 4)
5583
5584 '*' shift, and go to state 6
5585 '/' shift, and go to state 7
5586
5587 '/' [reduce using rule 1 (exp)]
5588 $default reduce using rule 1 (exp)
5589@end example
5590
5591The remaining states are similar:
5592
5593@example
5594state 9
5595
5596 exp -> exp . '+' exp (rule 1)
5597 exp -> exp . '-' exp (rule 2)
5598 exp -> exp '-' exp . (rule 2)
5599 exp -> exp . '*' exp (rule 3)
5600 exp -> exp . '/' exp (rule 4)
5601
5602 '*' shift, and go to state 6
5603 '/' shift, and go to state 7
5604
5605 '/' [reduce using rule 2 (exp)]
5606 $default reduce using rule 2 (exp)
5607
5608state 10
5609
5610 exp -> exp . '+' exp (rule 1)
5611 exp -> exp . '-' exp (rule 2)
5612 exp -> exp . '*' exp (rule 3)
5613 exp -> exp '*' exp . (rule 3)
5614 exp -> exp . '/' exp (rule 4)
5615
5616 '/' shift, and go to state 7
5617
5618 '/' [reduce using rule 3 (exp)]
5619 $default reduce using rule 3 (exp)
5620
5621state 11
5622
5623 exp -> exp . '+' exp (rule 1)
5624 exp -> exp . '-' exp (rule 2)
5625 exp -> exp . '*' exp (rule 3)
5626 exp -> exp . '/' exp (rule 4)
5627 exp -> exp '/' exp . (rule 4)
5628
5629 '+' shift, and go to state 4
5630 '-' shift, and go to state 5
5631 '*' shift, and go to state 6
5632 '/' shift, and go to state 7
5633
5634 '+' [reduce using rule 4 (exp)]
5635 '-' [reduce using rule 4 (exp)]
5636 '*' [reduce using rule 4 (exp)]
5637 '/' [reduce using rule 4 (exp)]
5638 $default reduce using rule 4 (exp)
5639@end example
5640
5641@noindent
5642Observe that state 11 contains conflicts due to the lack of precedence
5643of @samp{/} wrt @samp{+}, @samp{-}, and @samp{*}, but also because the
5644associativity of @samp{/} is not specified.
5645
5646
5647@node Tracing
5648@section Tracing Your Parser
bfa74976
RS
5649@findex yydebug
5650@cindex debugging
5651@cindex tracing the parser
5652
5653If a Bison grammar compiles properly but doesn't do what you want when it
5654runs, the @code{yydebug} parser-trace feature can help you figure out why.
5655
3ded9a63
AD
5656There are several means to enable compilation of trace facilities:
5657
5658@table @asis
5659@item the macro @code{YYDEBUG}
5660@findex YYDEBUG
5661Define the macro @code{YYDEBUG} to a nonzero value when you compile the
5662parser. This is compliant with POSIX Yacc. You could use
5663@samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
5664YYDEBUG 1} in the prologue of the grammar file (@pxref{Prologue, , The
5665Prologue}).
5666
5667@item the option @option{-t}, @option{--debug}
5668Use the @samp{-t} option when you run Bison (@pxref{Invocation,
5669,Invoking Bison}). This is POSIX compliant too.
5670
5671@item the directive @samp{%debug}
5672@findex %debug
5673Add the @code{%debug} directive (@pxref{Decl Summary, ,Bison
5674Declaration Summary}). This is a Bison extension, which will prove
5675useful when Bison will output parsers for languages that don't use a
5676preprocessor. Useless POSIX and Yacc portability matter to you, this is
5677the preferred solution.
5678@end table
5679
5680We suggest that you always enable the debug option so that debugging is
5681always possible.
bfa74976 5682
02a81e05 5683The trace facility outputs messages with macro calls of the form
e2742e46 5684@code{YYFPRINTF (stderr, @var{format}, @var{args})} where
02a81e05 5685@var{format} and @var{args} are the usual @code{printf} format and
4947ebdb
PE
5686arguments. If you define @code{YYDEBUG} to a nonzero value but do not
5687define @code{YYFPRINTF}, @code{<stdio.h>} is automatically included
e4e1a4dc 5688and @code{YYPRINTF} is defined to @code{fprintf}.
bfa74976
RS
5689
5690Once you have compiled the program with trace facilities, the way to
5691request a trace is to store a nonzero value in the variable @code{yydebug}.
5692You can do this by making the C code do it (in @code{main}, perhaps), or
5693you can alter the value with a C debugger.
5694
5695Each step taken by the parser when @code{yydebug} is nonzero produces a
5696line or two of trace information, written on @code{stderr}. The trace
5697messages tell you these things:
5698
5699@itemize @bullet
5700@item
5701Each time the parser calls @code{yylex}, what kind of token was read.
5702
5703@item
5704Each time a token is shifted, the depth and complete contents of the
5705state stack (@pxref{Parser States}).
5706
5707@item
5708Each time a rule is reduced, which rule it is, and the complete contents
5709of the state stack afterward.
5710@end itemize
5711
5712To make sense of this information, it helps to refer to the listing file
704a47c4
AD
5713produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking
5714Bison}). This file shows the meaning of each state in terms of
5715positions in various rules, and also what each state will do with each
5716possible input token. As you read the successive trace messages, you
5717can see that the parser is functioning according to its specification in
5718the listing file. Eventually you will arrive at the place where
5719something undesirable happens, and you will see which parts of the
5720grammar are to blame.
bfa74976
RS
5721
5722The parser file is a C program and you can use C debuggers on it, but it's
5723not easy to interpret what it is doing. The parser function is a
5724finite-state machine interpreter, and aside from the actions it executes
5725the same code over and over. Only the values of variables show where in
5726the grammar it is working.
5727
5728@findex YYPRINT
5729The debugging information normally gives the token type of each token
5730read, but not its semantic value. You can optionally define a macro
5731named @code{YYPRINT} to provide a way to print the value. If you define
5732@code{YYPRINT}, it should take three arguments. The parser will pass a
5733standard I/O stream, the numeric code for the token type, and the token
5734value (from @code{yylval}).
5735
5736Here is an example of @code{YYPRINT} suitable for the multi-function
5737calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
5738
5739@smallexample
5740#define YYPRINT(file, type, value) yyprint (file, type, value)
5741
5742static void
13863333 5743yyprint (FILE *file, int type, YYSTYPE value)
bfa74976
RS
5744@{
5745 if (type == VAR)
5746 fprintf (file, " %s", value.tptr->name);
5747 else if (type == NUM)
5748 fprintf (file, " %d", value.val);
5749@}
5750@end smallexample
5751
ec3bc396
AD
5752@c ================================================= Invoking Bison
5753
342b8b6e 5754@node Invocation
bfa74976
RS
5755@chapter Invoking Bison
5756@cindex invoking Bison
5757@cindex Bison invocation
5758@cindex options for invoking Bison
5759
5760The usual way to invoke Bison is as follows:
5761
5762@example
5763bison @var{infile}
5764@end example
5765
5766Here @var{infile} is the grammar file name, which usually ends in
5767@samp{.y}. The parser file's name is made by replacing the @samp{.y}
5768with @samp{.tab.c}. Thus, the @samp{bison foo.y} filename yields
5769@file{foo.tab.c}, and the @samp{bison hack/foo.y} filename yields
02a81e05 5770@file{hack/foo.tab.c}. It's is also possible, in case you are writing
79282c6c 5771C++ code instead of C in your grammar file, to name it @file{foo.ypp}
234a3be3
AD
5772or @file{foo.y++}. Then, the output files will take an extention like
5773the given one as input (repectively @file{foo.tab.cpp} and @file{foo.tab.c++}).
5774This feature takes effect with all options that manipulate filenames like
5775@samp{-o} or @samp{-d}.
5776
5777For example :
5778
5779@example
5780bison -d @var{infile.yxx}
5781@end example
84163231 5782@noindent
234a3be3
AD
5783will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}. and
5784
5785@example
5786bison -d @var{infile.y} -o @var{output.c++}
5787@end example
84163231 5788@noindent
234a3be3
AD
5789will produce @file{output.c++} and @file{outfile.h++}.
5790
bfa74976
RS
5791
5792@menu
13863333 5793* Bison Options:: All the options described in detail,
bfa74976
RS
5794 in alphabetical order by short options.
5795* Option Cross Key:: Alphabetical list of long options.
5796* VMS Invocation:: Bison command syntax on VMS.
5797@end menu
5798
342b8b6e 5799@node Bison Options
bfa74976
RS
5800@section Bison Options
5801
5802Bison supports both traditional single-letter options and mnemonic long
5803option names. Long option names are indicated with @samp{--} instead of
5804@samp{-}. Abbreviations for option names are allowed as long as they
5805are unique. When a long option takes an argument, like
5806@samp{--file-prefix}, connect the option name and the argument with
5807@samp{=}.
5808
5809Here is a list of options that can be used with Bison, alphabetized by
5810short option. It is followed by a cross key alphabetized by long
5811option.
5812
89cab50d
AD
5813@c Please, keep this ordered as in `bison --help'.
5814@noindent
5815Operations modes:
5816@table @option
5817@item -h
5818@itemx --help
5819Print a summary of the command-line options to Bison and exit.
bfa74976 5820
89cab50d
AD
5821@item -V
5822@itemx --version
5823Print the version number of Bison and exit.
bfa74976 5824
89cab50d
AD
5825@need 1750
5826@item -y
5827@itemx --yacc
89cab50d
AD
5828Equivalent to @samp{-o y.tab.c}; the parser output file is called
5829@file{y.tab.c}, and the other outputs are called @file{y.output} and
5830@file{y.tab.h}. The purpose of this option is to imitate Yacc's output
5831file name conventions. Thus, the following shell script can substitute
e0c471a9 5832for Yacc:
bfa74976 5833
89cab50d
AD
5834@example
5835bison -y $*
5836@end example
5837@end table
5838
5839@noindent
5840Tuning the parser:
5841
5842@table @option
cd5bd6ac
AD
5843@item -S @var{file}
5844@itemx --skeleton=@var{file}
5845Specify the skeleton to use. You probably don't need this option unless
5846you are developing Bison.
5847
89cab50d
AD
5848@item -t
5849@itemx --debug
4947ebdb
PE
5850In the parser file, define the macro @code{YYDEBUG} to 1 if it is not
5851already defined, so that the debugging facilities are compiled.
ec3bc396 5852@xref{Tracing, ,Tracing Your Parser}.
89cab50d
AD
5853
5854@item --locations
d8988b2f 5855Pretend that @code{%locations} was specified. @xref{Decl Summary}.
89cab50d
AD
5856
5857@item -p @var{prefix}
5858@itemx --name-prefix=@var{prefix}
d8988b2f
AD
5859Pretend that @code{%name-prefix="@var{prefix}"} was specified.
5860@xref{Decl Summary}.
bfa74976
RS
5861
5862@item -l
5863@itemx --no-lines
5864Don't put any @code{#line} preprocessor commands in the parser file.
5865Ordinarily Bison puts them in the parser file so that the C compiler
5866and debuggers will associate errors with your source file, the
5867grammar file. This option causes them to associate errors with the
95e742f7 5868parser file, treating it as an independent source file in its own right.
bfa74976 5869
931c7513
RS
5870@item -n
5871@itemx --no-parser
d8988b2f 5872Pretend that @code{%no-parser} was specified. @xref{Decl Summary}.
931c7513 5873
89cab50d
AD
5874@item -k
5875@itemx --token-table
d8988b2f 5876Pretend that @code{%token-table} was specified. @xref{Decl Summary}.
89cab50d 5877@end table
bfa74976 5878
89cab50d
AD
5879@noindent
5880Adjust the output:
bfa74976 5881
89cab50d
AD
5882@table @option
5883@item -d
d8988b2f
AD
5884@itemx --defines
5885Pretend that @code{%defines} was specified, i.e., write an extra output
6deb4447
AD
5886file containing macro definitions for the token type names defined in
5887the grammar and the semantic value type @code{YYSTYPE}, as well as a few
5888@code{extern} variable declarations. @xref{Decl Summary}.
931c7513 5889
342b8b6e 5890@item --defines=@var{defines-file}
d8988b2f 5891Same as above, but save in the file @var{defines-file}.
342b8b6e 5892
89cab50d
AD
5893@item -b @var{file-prefix}
5894@itemx --file-prefix=@var{prefix}
d8988b2f
AD
5895Pretend that @code{%verbose} was specified, i.e, specify prefix to use
5896for all Bison output file names. @xref{Decl Summary}.
bfa74976 5897
ec3bc396
AD
5898@item -r @var{things}
5899@itemx --report=@var{things}
5900Write an extra output file containing verbose description of the comma
5901separated list of @var{things} among:
5902
5903@table @code
5904@item state
5905Description of the grammar, conflicts (resolved and unresolved), and
5906LALR automaton.
5907
5908@item lookahead
5909Implies @code{state} and augments the description of the automaton with
5910each rule's lookahead set.
5911
5912@item itemset
5913Implies @code{state} and augments the description of the automaton with
5914the full set of items for each state, instead of its core only.
5915@end table
5916
5917For instance, on the following grammar
5918
bfa74976
RS
5919@item -v
5920@itemx --verbose
6deb4447
AD
5921Pretend that @code{%verbose} was specified, i.e, write an extra output
5922file containing verbose descriptions of the grammar and
d8988b2f 5923parser. @xref{Decl Summary}.
bfa74976 5924
d8988b2f
AD
5925@item -o @var{filename}
5926@itemx --output=@var{filename}
5927Specify the @var{filename} for the parser file.
bfa74976 5928
d8988b2f
AD
5929The other output files' names are constructed from @var{filename} as
5930described under the @samp{-v} and @samp{-d} options.
342b8b6e
AD
5931
5932@item -g
5933Output a VCG definition of the LALR(1) grammar automaton computed by
5934Bison. If the grammar file is @file{foo.y}, the VCG output file will
5935be @file{foo.vcg}.
5936
5937@item --graph=@var{graph-file}
5938The behaviour of @var{--graph} is the same than @samp{-g}. The only
5939difference is that it has an optionnal argument which is the name of
5940the output graph filename.
bfa74976
RS
5941@end table
5942
342b8b6e 5943@node Option Cross Key
bfa74976
RS
5944@section Option Cross Key
5945
5946Here is a list of options, alphabetized by long option, to help you find
5947the corresponding short option.
5948
5949@tex
5950\def\leaderfill{\leaders\hbox to 1em{\hss.\hss}\hfill}
5951
5952{\tt
5953\line{ --debug \leaderfill -t}
5954\line{ --defines \leaderfill -d}
5955\line{ --file-prefix \leaderfill -b}
342b8b6e 5956\line{ --graph \leaderfill -g}
ff51d159 5957\line{ --help \leaderfill -h}
bfa74976
RS
5958\line{ --name-prefix \leaderfill -p}
5959\line{ --no-lines \leaderfill -l}
931c7513 5960\line{ --no-parser \leaderfill -n}
d8988b2f 5961\line{ --output \leaderfill -o}
931c7513 5962\line{ --token-table \leaderfill -k}
bfa74976
RS
5963\line{ --verbose \leaderfill -v}
5964\line{ --version \leaderfill -V}
5965\line{ --yacc \leaderfill -y}
5966}
5967@end tex
5968
5969@ifinfo
5970@example
5971--debug -t
342b8b6e 5972--defines=@var{defines-file} -d
bfa74976 5973--file-prefix=@var{prefix} -b @var{file-prefix}
342b8b6e 5974--graph=@var{graph-file} -d
ff51d159 5975--help -h
931c7513 5976--name-prefix=@var{prefix} -p @var{name-prefix}
bfa74976 5977--no-lines -l
931c7513 5978--no-parser -n
d8988b2f 5979--output=@var{outfile} -o @var{outfile}
931c7513 5980--token-table -k
bfa74976
RS
5981--verbose -v
5982--version -V
8c9a50be 5983--yacc -y
bfa74976
RS
5984@end example
5985@end ifinfo
5986
342b8b6e 5987@node VMS Invocation
bfa74976
RS
5988@section Invoking Bison under VMS
5989@cindex invoking Bison under VMS
5990@cindex VMS
5991
5992The command line syntax for Bison on VMS is a variant of the usual
5993Bison command syntax---adapted to fit VMS conventions.
5994
5995To find the VMS equivalent for any Bison option, start with the long
5996option, and substitute a @samp{/} for the leading @samp{--}, and
5997substitute a @samp{_} for each @samp{-} in the name of the long option.
5998For example, the following invocation under VMS:
5999
6000@example
6001bison /debug/name_prefix=bar foo.y
6002@end example
6003
6004@noindent
6005is equivalent to the following command under POSIX.
6006
6007@example
6008bison --debug --name-prefix=bar foo.y
6009@end example
6010
6011The VMS file system does not permit filenames such as
6012@file{foo.tab.c}. In the above example, the output file
6013would instead be named @file{foo_tab.c}.
6014
342b8b6e 6015@node Table of Symbols
bfa74976
RS
6016@appendix Bison Symbols
6017@cindex Bison symbols, table of
6018@cindex symbols in Bison, table of
6019
6020@table @code
3ded9a63
AD
6021@item @@$
6022In an action, the location of the left-hand side of the rule.
88bce5a2 6023@xref{Locations, , Locations Overview}.
3ded9a63
AD
6024
6025@item @@@var{n}
6026In an action, the location of the @var{n}-th symbol of the right-hand
6027side of the rule. @xref{Locations, , Locations Overview}.
6028
6029@item $$
6030In an action, the semantic value of the left-hand side of the rule.
6031@xref{Actions}.
6032
6033@item $@var{n}
6034In an action, the semantic value of the @var{n}-th symbol of the
6035right-hand side of the rule. @xref{Actions}.
6036
88bce5a2
AD
6037@item $accept
6038The predefined nonterminal whose only rule is @samp{$accept: @var{start}
6039$end}, where @var{start} is the start symbol. @xref{Start Decl, , The
6040Start-Symbol}. It cannot be used in the grammar.
6041
6042@item $end
6043The predefined token marking the end of the token stream. It cannot be
6044used in the grammar.
6045
6046@item $undefined
6047The predefined token onto which all undefined values returned by
6048@code{yylex} are mapped. It cannot be used in the grammar, rather, use
6049@code{error}.
6050
bfa74976
RS
6051@item error
6052A token name reserved for error recovery. This token may be used in
6053grammar rules so as to allow the Bison parser to recognize an error in
6054the grammar without halting the process. In effect, a sentence
6055containing an error may be recognized as valid. On a parse error, the
6056token @code{error} becomes the current look-ahead token. Actions
6057corresponding to @code{error} are then executed, and the look-ahead
6058token is reset to the token that originally caused the violation.
6059@xref{Error Recovery}.
6060
6061@item YYABORT
6062Macro to pretend that an unrecoverable syntax error has occurred, by
6063making @code{yyparse} return 1 immediately. The error reporting
ceed8467
AD
6064function @code{yyerror} is not called. @xref{Parser Function, ,The
6065Parser Function @code{yyparse}}.
bfa74976
RS
6066
6067@item YYACCEPT
6068Macro to pretend that a complete utterance of the language has been
13863333 6069read, by making @code{yyparse} return 0 immediately.
bfa74976
RS
6070@xref{Parser Function, ,The Parser Function @code{yyparse}}.
6071
6072@item YYBACKUP
6073Macro to discard a value from the parser stack and fake a look-ahead
6074token. @xref{Action Features, ,Special Features for Use in Actions}.
6075
3ded9a63 6076@item YYDEBUG
ec3bc396
AD
6077Macro to define to equip the parser with tracing code. @xref{Tracing,
6078,Tracing Your Parser}.
3ded9a63 6079
bfa74976
RS
6080@item YYERROR
6081Macro to pretend that a syntax error has just been detected: call
6082@code{yyerror} and then perform normal error recovery if possible
6083(@pxref{Error Recovery}), or (if recovery is impossible) make
6084@code{yyparse} return 1. @xref{Error Recovery}.
6085
6086@item YYERROR_VERBOSE
6087Macro that you define with @code{#define} in the Bison declarations
6088section to request verbose, specific error message strings when
6089@code{yyerror} is called.
6090
6091@item YYINITDEPTH
6092Macro for specifying the initial size of the parser stack.
6093@xref{Stack Overflow}.
6094
c656404a
RS
6095@item YYLEX_PARAM
6096Macro for specifying an extra argument (or list of extra arguments) for
6097@code{yyparse} to pass to @code{yylex}. @xref{Pure Calling,, Calling
6098Conventions for Pure Parsers}.
6099
bfa74976
RS
6100@item YYLTYPE
6101Macro for the data type of @code{yylloc}; a structure with four
847bf1f5 6102members. @xref{Location Type, , Data Types of Locations}.
bfa74976 6103
931c7513
RS
6104@item yyltype
6105Default value for YYLTYPE.
6106
bfa74976
RS
6107@item YYMAXDEPTH
6108Macro for specifying the maximum size of the parser stack.
6109@xref{Stack Overflow}.
6110
c656404a
RS
6111@item YYPARSE_PARAM
6112Macro for specifying the name of a parameter that @code{yyparse} should
6113accept. @xref{Pure Calling,, Calling Conventions for Pure Parsers}.
6114
bfa74976
RS
6115@item YYRECOVERING
6116Macro whose value indicates whether the parser is recovering from a
6117syntax error. @xref{Action Features, ,Special Features for Use in Actions}.
6118
f9a8293a
AD
6119@item YYSTACK_USE_ALLOCA
6120Macro used to control the use of @code{alloca}. If defined to @samp{0},
6121the parser will not use @code{alloca} but @code{malloc} when trying to
6122grow its internal stacks. Do @emph{not} define @code{YYSTACK_USE_ALLOCA}
6123to anything else.
6124
bfa74976
RS
6125@item YYSTYPE
6126Macro for the data type of semantic values; @code{int} by default.
6127@xref{Value Type, ,Data Types of Semantic Values}.
6128
6129@item yychar
13863333
AD
6130External integer variable that contains the integer value of the current
6131look-ahead token. (In a pure parser, it is a local variable within
6132@code{yyparse}.) Error-recovery rule actions may examine this variable.
6133@xref{Action Features, ,Special Features for Use in Actions}.
bfa74976
RS
6134
6135@item yyclearin
6136Macro used in error-recovery rule actions. It clears the previous
6137look-ahead token. @xref{Error Recovery}.
6138
6139@item yydebug
6140External integer variable set to zero by default. If @code{yydebug}
6141is given a nonzero value, the parser will output information on input
ec3bc396 6142symbols and parser action. @xref{Tracing, ,Tracing Your Parser}.
bfa74976
RS
6143
6144@item yyerrok
6145Macro to cause parser to recover immediately to its normal mode
6146after a parse error. @xref{Error Recovery}.
6147
6148@item yyerror
6149User-supplied function to be called by @code{yyparse} on error. The
6150function receives one argument, a pointer to a character string
13863333
AD
6151containing an error message. @xref{Error Reporting, ,The Error
6152Reporting Function @code{yyerror}}.
bfa74976
RS
6153
6154@item yylex
704a47c4
AD
6155User-supplied lexical analyzer function, called with no arguments to get
6156the next token. @xref{Lexical, ,The Lexical Analyzer Function
6157@code{yylex}}.
bfa74976
RS
6158
6159@item yylval
6160External variable in which @code{yylex} should place the semantic
6161value associated with a token. (In a pure parser, it is a local
6162variable within @code{yyparse}, and its address is passed to
6163@code{yylex}.) @xref{Token Values, ,Semantic Values of Tokens}.
6164
6165@item yylloc
13863333
AD
6166External variable in which @code{yylex} should place the line and column
6167numbers associated with a token. (In a pure parser, it is a local
6168variable within @code{yyparse}, and its address is passed to
bfa74976 6169@code{yylex}.) You can ignore this variable if you don't use the
13863333
AD
6170@samp{@@} feature in the grammar actions. @xref{Token Positions,
6171,Textual Positions of Tokens}.
bfa74976
RS
6172
6173@item yynerrs
13863333
AD
6174Global variable which Bison increments each time there is a parse error.
6175(In a pure parser, it is a local variable within @code{yyparse}.)
6176@xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
bfa74976
RS
6177
6178@item yyparse
6179The parser function produced by Bison; call this function to start
6180parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
6181
6deb4447
AD
6182@item %debug
6183Equip the parser for debugging. @xref{Decl Summary}.
6184
6185@item %defines
6186Bison declaration to create a header file meant for the scanner.
6187@xref{Decl Summary}.
6188
fae437e8 6189@item %dprec
676385e2
PH
6190Bison declaration to assign a precedence to a rule that is used at parse
6191time to resolve reduce/reduce conflicts. @xref{GLR Parsers}.
6192
d8988b2f 6193@item %file-prefix="@var{prefix}"
676385e2 6194Bison declaration to set the prefix of the output files. @xref{Decl
d8988b2f
AD
6195Summary}.
6196
676385e2
PH
6197@item %glr-parser
6198Bison declaration to produce a GLR parser. @xref{GLR Parsers}.
6199
8c9a50be 6200@c @item %source-extension
f9a8293a
AD
6201@c Bison declaration to specify the generated parser output file extension.
6202@c @xref{Decl Summary}.
6203@c
8c9a50be 6204@c @item %header-extension
f9a8293a
AD
6205@c Bison declaration to specify the generated parser header file extension
6206@c if required. @xref{Decl Summary}.
6207
bfa74976
RS
6208@item %left
6209Bison declaration to assign left associativity to token(s).
6210@xref{Precedence Decl, ,Operator Precedence}.
6211
676385e2
PH
6212@item %merge
6213Bison declaration to assign a merging function to a rule. If there is a
fae437e8 6214reduce/reduce conflict with a rule having the same merging function, the
676385e2
PH
6215function is applied to the two semantic values to get a single result.
6216@xref{GLR Parsers}.
6217
d8988b2f
AD
6218@item %name-prefix="@var{prefix}"
6219Bison declaration to rename the external symbols. @xref{Decl Summary}.
6220
6221@item %no-lines
931c7513
RS
6222Bison declaration to avoid generating @code{#line} directives in the
6223parser file. @xref{Decl Summary}.
6224
bfa74976 6225@item %nonassoc
14ded682 6226Bison declaration to assign non-associativity to token(s).
bfa74976
RS
6227@xref{Precedence Decl, ,Operator Precedence}.
6228
d8988b2f
AD
6229@item %output="@var{filename}"
6230Bison declaration to set the name of the parser file. @xref{Decl
6231Summary}.
6232
bfa74976
RS
6233@item %prec
6234Bison declaration to assign a precedence to a specific rule.
6235@xref{Contextual Precedence, ,Context-Dependent Precedence}.
6236
d8988b2f 6237@item %pure-parser
bfa74976
RS
6238Bison declaration to request a pure (reentrant) parser.
6239@xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6240
6241@item %right
6242Bison declaration to assign right associativity to token(s).
6243@xref{Precedence Decl, ,Operator Precedence}.
6244
6245@item %start
704a47c4
AD
6246Bison declaration to specify the start symbol. @xref{Start Decl, ,The
6247Start-Symbol}.
bfa74976
RS
6248
6249@item %token
6250Bison declaration to declare token(s) without specifying precedence.
6251@xref{Token Decl, ,Token Type Names}.
6252
d8988b2f 6253@item %token-table
931c7513
RS
6254Bison declaration to include a token name table in the parser file.
6255@xref{Decl Summary}.
6256
bfa74976 6257@item %type
704a47c4
AD
6258Bison declaration to declare nonterminals. @xref{Type Decl,
6259,Nonterminal Symbols}.
bfa74976
RS
6260
6261@item %union
6262Bison declaration to specify several possible data types for semantic
6263values. @xref{Union Decl, ,The Collection of Value Types}.
6264@end table
6265
3ded9a63
AD
6266@sp 1
6267
bfa74976
RS
6268These are the punctuation and delimiters used in Bison input:
6269
6270@table @samp
6271@item %%
6272Delimiter used to separate the grammar rule section from the
75f5aaea 6273Bison declarations section or the epilogue.
bfa74976
RS
6274@xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
6275
6276@item %@{ %@}
89cab50d 6277All code listed between @samp{%@{} and @samp{%@}} is copied directly to
342b8b6e 6278the output file uninterpreted. Such code forms the prologue of the input
75f5aaea 6279file. @xref{Grammar Outline, ,Outline of a Bison
89cab50d 6280Grammar}.
bfa74976
RS
6281
6282@item /*@dots{}*/
6283Comment delimiters, as in C.
6284
6285@item :
89cab50d
AD
6286Separates a rule's result from its components. @xref{Rules, ,Syntax of
6287Grammar Rules}.
bfa74976
RS
6288
6289@item ;
6290Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
6291
6292@item |
6293Separates alternate rules for the same result nonterminal.
6294@xref{Rules, ,Syntax of Grammar Rules}.
6295@end table
6296
342b8b6e 6297@node Glossary
bfa74976
RS
6298@appendix Glossary
6299@cindex glossary
6300
6301@table @asis
6302@item Backus-Naur Form (BNF)
6303Formal method of specifying context-free grammars. BNF was first used
89cab50d
AD
6304in the @cite{ALGOL-60} report, 1963. @xref{Language and Grammar,
6305,Languages and Context-Free Grammars}.
bfa74976
RS
6306
6307@item Context-free grammars
6308Grammars specified as rules that can be applied regardless of context.
6309Thus, if there is a rule which says that an integer can be used as an
6310expression, integers are allowed @emph{anywhere} an expression is
89cab50d
AD
6311permitted. @xref{Language and Grammar, ,Languages and Context-Free
6312Grammars}.
bfa74976
RS
6313
6314@item Dynamic allocation
6315Allocation of memory that occurs during execution, rather than at
6316compile time or on entry to a function.
6317
6318@item Empty string
6319Analogous to the empty set in set theory, the empty string is a
6320character string of length zero.
6321
6322@item Finite-state stack machine
6323A ``machine'' that has discrete states in which it is said to exist at
6324each instant in time. As input to the machine is processed, the
6325machine moves from state to state as specified by the logic of the
6326machine. In the case of the parser, the input is the language being
6327parsed, and the states correspond to various stages in the grammar
6328rules. @xref{Algorithm, ,The Bison Parser Algorithm }.
6329
676385e2
PH
6330@item Generalized LR (GLR)
6331A parsing algorithm that can handle all context-free grammars, including those
fae437e8 6332that are not LALR(1). It resolves situations that Bison's usual LALR(1)
676385e2
PH
6333algorithm cannot by effectively splitting off multiple parsers, trying all
6334possible parsers, and discarding those that fail in the light of additional
6335right context. @xref{Generalized LR Parsing, ,Generalized LR Parsing}.
6336
bfa74976
RS
6337@item Grouping
6338A language construct that is (in general) grammatically divisible;
13863333 6339for example, `expression' or `declaration' in C.
bfa74976
RS
6340@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6341
6342@item Infix operator
6343An arithmetic operator that is placed between the operands on which it
6344performs some operation.
6345
6346@item Input stream
6347A continuous flow of data between devices or programs.
6348
6349@item Language construct
6350One of the typical usage schemas of the language. For example, one of
6351the constructs of the C language is the @code{if} statement.
6352@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
6353
6354@item Left associativity
6355Operators having left associativity are analyzed from left to right:
6356@samp{a+b+c} first computes @samp{a+b} and then combines with
6357@samp{c}. @xref{Precedence, ,Operator Precedence}.
6358
6359@item Left recursion
89cab50d
AD
6360A rule whose result symbol is also its first component symbol; for
6361example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive
6362Rules}.
bfa74976
RS
6363
6364@item Left-to-right parsing
6365Parsing a sentence of a language by analyzing it token by token from
6366left to right. @xref{Algorithm, ,The Bison Parser Algorithm }.
6367
6368@item Lexical analyzer (scanner)
6369A function that reads an input stream and returns tokens one by one.
6370@xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
6371
6372@item Lexical tie-in
6373A flag, set by actions in the grammar rules, which alters the way
6374tokens are parsed. @xref{Lexical Tie-ins}.
6375
931c7513 6376@item Literal string token
14ded682 6377A token which consists of two or more fixed characters. @xref{Symbols}.
931c7513 6378
bfa74976 6379@item Look-ahead token
89cab50d
AD
6380A token already read but not yet shifted. @xref{Look-Ahead, ,Look-Ahead
6381Tokens}.
bfa74976
RS
6382
6383@item LALR(1)
6384The class of context-free grammars that Bison (like most other parser
6385generators) can handle; a subset of LR(1). @xref{Mystery Conflicts, ,
6386Mysterious Reduce/Reduce Conflicts}.
6387
6388@item LR(1)
6389The class of context-free grammars in which at most one token of
6390look-ahead is needed to disambiguate the parsing of any piece of input.
6391
6392@item Nonterminal symbol
6393A grammar symbol standing for a grammatical construct that can
6394be expressed through rules in terms of smaller constructs; in other
6395words, a construct that is not a token. @xref{Symbols}.
6396
6397@item Parse error
6398An error encountered during parsing of an input stream due to invalid
6399syntax. @xref{Error Recovery}.
6400
6401@item Parser
6402A function that recognizes valid sentences of a language by analyzing
6403the syntax structure of a set of tokens passed to it from a lexical
6404analyzer.
6405
6406@item Postfix operator
6407An arithmetic operator that is placed after the operands upon which it
6408performs some operation.
6409
6410@item Reduction
6411Replacing a string of nonterminals and/or terminals with a single
89cab50d
AD
6412nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison
6413Parser Algorithm }.
bfa74976
RS
6414
6415@item Reentrant
6416A reentrant subprogram is a subprogram which can be in invoked any
6417number of times in parallel, without interference between the various
6418invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
6419
6420@item Reverse polish notation
6421A language in which all operators are postfix operators.
6422
6423@item Right recursion
89cab50d
AD
6424A rule whose result symbol is also its last component symbol; for
6425example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive
6426Rules}.
bfa74976
RS
6427
6428@item Semantics
6429In computer languages, the semantics are specified by the actions
6430taken for each instance of the language, i.e., the meaning of
6431each statement. @xref{Semantics, ,Defining Language Semantics}.
6432
6433@item Shift
6434A parser is said to shift when it makes the choice of analyzing
6435further input from the stream rather than reducing immediately some
6436already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm }.
6437
6438@item Single-character literal
6439A single character that is recognized and interpreted as is.
6440@xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
6441
6442@item Start symbol
6443The nonterminal symbol that stands for a complete valid utterance in
6444the language being parsed. The start symbol is usually listed as the
13863333 6445first nonterminal symbol in a language specification.
bfa74976
RS
6446@xref{Start Decl, ,The Start-Symbol}.
6447
6448@item Symbol table
6449A data structure where symbol names and associated data are stored
6450during parsing to allow for recognition and use of existing
6451information in repeated uses of a symbol. @xref{Multi-function Calc}.
6452
6453@item Token
6454A basic, grammatically indivisible unit of a language. The symbol
6455that describes a token in the grammar is a terminal symbol.
6456The input of the Bison parser is a stream of tokens which comes from
6457the lexical analyzer. @xref{Symbols}.
6458
6459@item Terminal symbol
89cab50d
AD
6460A grammar symbol that has no rules in the grammar and therefore is
6461grammatically indivisible. The piece of text it represents is a token.
6462@xref{Language and Grammar, ,Languages and Context-Free Grammars}.
bfa74976
RS
6463@end table
6464
342b8b6e 6465@node Copying This Manual
f2b5126e 6466@appendix Copying This Manual
f9a8293a 6467
f2b5126e
PB
6468@menu
6469* GNU Free Documentation License:: License for copying this manual.
6470@end menu
f9a8293a 6471
f2b5126e
PB
6472@include fdl.texi
6473
342b8b6e 6474@node Index
bfa74976
RS
6475@unnumbered Index
6476
6477@printindex cp
6478
bfa74976 6479@bye