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