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