1 This is bison.info, produced by makeinfo version 4.0b from
5 * bison: (bison). GNU Project parser generator (yacc replacement).
8 This file documents the Bison parser generator.
10 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 1999,
11 2000, 2001 Free Software Foundation, Inc.
13 Permission is granted to make and distribute verbatim copies of this
14 manual provided the copyright notice and this permission notice are
15 preserved on all copies.
17 Permission is granted to copy and distribute modified versions of
18 this manual under the conditions for verbatim copying, provided also
19 that the sections entitled "GNU General Public License" and "Conditions
20 for Using Bison" are included exactly as in the original, and provided
21 that the entire resulting derived work is distributed under the terms
22 of a permission notice identical to this one.
24 Permission is granted to copy and distribute translations of this
25 manual into another language, under the above conditions for modified
26 versions, except that the sections entitled "GNU General Public
27 License", "Conditions for Using Bison" and this permission notice may be
28 included in translations approved by the Free Software Foundation
29 instead of in the original English.
32 File: bison.info, Node: Top, Next: Introduction, Prev: (dir), Up: (dir)
34 This manual documents version 1.28c of Bison.
40 * Copying:: The GNU General Public License says
41 how you can copy and share Bison
44 * Concepts:: Basic concepts for understanding Bison.
45 * Examples:: Three simple explained examples of using Bison.
48 * Grammar File:: Writing Bison declarations and rules.
49 * Interface:: C-language interface to the parser function `yyparse'.
50 * Algorithm:: How the Bison parser works at run-time.
51 * Error Recovery:: Writing rules for error recovery.
52 * Context Dependency:: What to do if your language syntax is too
53 messy for Bison to handle straightforwardly.
54 * Debugging:: Debugging Bison parsers that parse wrong.
55 * Invocation:: How to run Bison (to produce the parser source file).
56 * Table of Symbols:: All the keywords of the Bison language are explained.
57 * Glossary:: Basic concepts are explained.
58 * Copying This Manual:: License for copying this manual.
59 * Index:: Cross-references to the text.
61 --- The Detailed Node Listing ---
65 * Language and Grammar:: Languages and context-free grammars,
66 as mathematical ideas.
67 * Grammar in Bison:: How we represent grammars for Bison's sake.
68 * Semantic Values:: Each token or syntactic grouping can have
69 a semantic value (the value of an integer,
70 the name of an identifier, etc.).
71 * Semantic Actions:: Each rule can have an action containing C code.
72 * Bison Parser:: What are Bison's input and output,
73 how is the output used?
74 * Stages:: Stages in writing and running Bison grammars.
75 * Grammar Layout:: Overall structure of a Bison grammar file.
79 * RPN Calc:: Reverse polish notation calculator;
80 a first example with no operator precedence.
81 * Infix Calc:: Infix (algebraic) notation calculator.
82 Operator precedence is introduced.
83 * Simple Error Recovery:: Continuing after syntax errors.
84 * Multi-function Calc:: Calculator with memory and trig functions.
85 It uses multiple data-types for semantic values.
86 * Exercises:: Ideas for improving the multi-function calculator.
88 Reverse Polish Notation Calculator
90 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
91 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
92 * Lexer: Rpcalc Lexer. The lexical analyzer.
93 * Main: Rpcalc Main. The controlling function.
94 * Error: Rpcalc Error. The error reporting function.
95 * Gen: Rpcalc Gen. Running Bison on the grammar file.
96 * Comp: Rpcalc Compile. Run the C compiler on the output code.
98 Grammar Rules for `rpcalc'
104 Multi-Function Calculator: `mfcalc'
106 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
107 * Rules: Mfcalc Rules. Grammar rules for the calculator.
108 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
112 * Grammar Outline:: Overall layout of the grammar file.
113 * Symbols:: Terminal and nonterminal symbols.
114 * Rules:: How to write grammar rules.
115 * Recursion:: Writing recursive rules.
116 * Semantics:: Semantic values and actions.
117 * Declarations:: All kinds of Bison declarations are described here.
118 * Multiple Parsers:: Putting more than one Bison parser in one program.
120 Outline of a Bison Grammar
122 * Prologue:: Syntax and usage of the prologue (declarations section).
123 * Bison Declarations:: Syntax and usage of the Bison declarations section.
124 * Grammar Rules:: Syntax and usage of the grammar rules section.
125 * Epilogue:: Syntax and usage of the epilogue (additional code section).
127 Defining Language Semantics
129 * Value Type:: Specifying one data type for all semantic values.
130 * Multiple Types:: Specifying several alternative data types.
131 * Actions:: An action is the semantic definition of a grammar rule.
132 * Action Types:: Specifying data types for actions to operate on.
133 * Mid-Rule Actions:: Most actions go at the end of a rule.
134 This says when, why and how to use the exceptional
135 action in the middle of a rule.
139 * Token Decl:: Declaring terminal symbols.
140 * Precedence Decl:: Declaring terminals with precedence and associativity.
141 * Union Decl:: Declaring the set of all semantic value types.
142 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
143 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
144 * Start Decl:: Specifying the start symbol.
145 * Pure Decl:: Requesting a reentrant parser.
146 * Decl Summary:: Table of all Bison declarations.
148 Parser C-Language Interface
150 * Parser Function:: How to call `yyparse' and what it returns.
151 * Lexical:: You must supply a function `yylex'
153 * Error Reporting:: You must supply a function `yyerror'.
154 * Action Features:: Special features for use in actions.
156 The Lexical Analyzer Function `yylex'
158 * Calling Convention:: How `yyparse' calls `yylex'.
159 * Token Values:: How `yylex' must return the semantic value
160 of the token it has read.
161 * Token Positions:: How `yylex' must return the text position
162 (line number, etc.) of the token, if the
164 * Pure Calling:: How the calling convention differs
165 in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
167 The Bison Parser Algorithm
169 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
170 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
171 * Precedence:: Operator precedence works by resolving conflicts.
172 * Contextual Precedence:: When an operator's precedence depends on context.
173 * Parser States:: The parser is a finite-state-machine with stack.
174 * Reduce/Reduce:: When two rules are applicable in the same situation.
175 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
176 * Stack Overflow:: What happens when stack gets full. How to avoid it.
180 * Why Precedence:: An example showing why precedence is needed.
181 * Using Precedence:: How to specify precedence in Bison grammars.
182 * Precedence Examples:: How these features are used in the previous example.
183 * How Precedence:: How they work.
185 Handling Context Dependencies
187 * Semantic Tokens:: Token parsing can depend on the semantic context.
188 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
189 * Tie-in Recovery:: Lexical tie-ins have implications for how
190 error recovery rules must be written.
194 * Bison Options:: All the options described in detail,
195 in alphabetical order by short options.
196 * Option Cross Key:: Alphabetical list of long options.
197 * VMS Invocation:: Bison command syntax on VMS.
201 * GNU Free Documentation License:: License for copying this manual.
204 File: bison.info, Node: Introduction, Next: Conditions, Prev: Top, Up: Top
209 "Bison" is a general-purpose parser generator that converts a
210 grammar description for an LALR(1) context-free grammar into a C
211 program to parse that grammar. Once you are proficient with Bison, you
212 may use it to develop a wide range of language parsers, from those used
213 in simple desk calculators to complex programming languages.
215 Bison is upward compatible with Yacc: all properly-written Yacc
216 grammars ought to work with Bison with no change. Anyone familiar with
217 Yacc should be able to use Bison with little trouble. You need to be
218 fluent in C programming in order to use Bison or to understand this
221 We begin with tutorial chapters that explain the basic concepts of
222 using Bison and show three explained examples, each building on the
223 last. If you don't know Bison or Yacc, start by reading these
224 chapters. Reference chapters follow which describe specific aspects of
227 Bison was written primarily by Robert Corbett; Richard Stallman made
228 it Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
229 multi-character string literals and other features.
231 This edition corresponds to version 1.28c of Bison.
234 File: bison.info, Node: Conditions, Next: Copying, Prev: Introduction, Up: Top
236 Conditions for Using Bison
237 **************************
239 As of Bison version 1.24, we have changed the distribution terms for
240 `yyparse' to permit using Bison's output in nonfree programs.
241 Formerly, Bison parsers could be used only in programs that were free
244 The other GNU programming tools, such as the GNU C compiler, have
245 never had such a requirement. They could always be used for nonfree
246 software. The reason Bison was different was not due to a special
247 policy decision; it resulted from applying the usual General Public
248 License to all of the Bison source code.
250 The output of the Bison utility--the Bison parser file--contains a
251 verbatim copy of a sizable piece of Bison, which is the code for the
252 `yyparse' function. (The actions from your grammar are inserted into
253 this function at one point, but the rest of the function is not
254 changed.) When we applied the GPL terms to the code for `yyparse', the
255 effect was to restrict the use of Bison output to free software.
257 We didn't change the terms because of sympathy for people who want to
258 make software proprietary. *Software should be free.* But we
259 concluded that limiting Bison's use to free software was doing little to
260 encourage people to make other software free. So we decided to make the
261 practical conditions for using Bison match the practical conditions for
262 using the other GNU tools.
265 File: bison.info, Node: Copying, Next: Concepts, Prev: Conditions, Up: Top
267 GNU GENERAL PUBLIC LICENSE
268 **************************
272 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
273 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
275 Everyone is permitted to copy and distribute verbatim copies
276 of this license document, but changing it is not allowed.
281 The licenses for most software are designed to take away your
282 freedom to share and change it. By contrast, the GNU General Public
283 License is intended to guarantee your freedom to share and change free
284 software--to make sure the software is free for all its users. This
285 General Public License applies to most of the Free Software
286 Foundation's software and to any other program whose authors commit to
287 using it. (Some other Free Software Foundation software is covered by
288 the GNU Library General Public License instead.) You can apply it to
291 When we speak of free software, we are referring to freedom, not
292 price. Our General Public Licenses are designed to make sure that you
293 have the freedom to distribute copies of free software (and charge for
294 this service if you wish), that you receive source code or can get it
295 if you want it, that you can change the software or use pieces of it in
296 new free programs; and that you know you can do these things.
298 To protect your rights, we need to make restrictions that forbid
299 anyone to deny you these rights or to ask you to surrender the rights.
300 These restrictions translate to certain responsibilities for you if you
301 distribute copies of the software, or if you modify it.
303 For example, if you distribute copies of such a program, whether
304 gratis or for a fee, you must give the recipients all the rights that
305 you have. You must make sure that they, too, receive or can get the
306 source code. And you must show them these terms so they know their
309 We protect your rights with two steps: (1) copyright the software,
310 and (2) offer you this license which gives you legal permission to copy,
311 distribute and/or modify the software.
313 Also, for each author's protection and ours, we want to make certain
314 that everyone understands that there is no warranty for this free
315 software. If the software is modified by someone else and passed on, we
316 want its recipients to know that what they have is not the original, so
317 that any problems introduced by others will not reflect on the original
318 authors' reputations.
320 Finally, any free program is threatened constantly by software
321 patents. We wish to avoid the danger that redistributors of a free
322 program will individually obtain patent licenses, in effect making the
323 program proprietary. To prevent this, we have made it clear that any
324 patent must be licensed for everyone's free use or not licensed at all.
326 The precise terms and conditions for copying, distribution and
329 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
330 0. This License applies to any program or other work which contains a
331 notice placed by the copyright holder saying it may be distributed
332 under the terms of this General Public License. The "Program",
333 below, refers to any such program or work, and a "work based on
334 the Program" means either the Program or any derivative work under
335 copyright law: that is to say, a work containing the Program or a
336 portion of it, either verbatim or with modifications and/or
337 translated into another language. (Hereinafter, translation is
338 included without limitation in the term "modification".) Each
339 licensee is addressed as "you".
341 Activities other than copying, distribution and modification are
342 not covered by this License; they are outside its scope. The act
343 of running the Program is not restricted, and the output from the
344 Program is covered only if its contents constitute a work based on
345 the Program (independent of having been made by running the
346 Program). Whether that is true depends on what the Program does.
348 1. You may copy and distribute verbatim copies of the Program's
349 source code as you receive it, in any medium, provided that you
350 conspicuously and appropriately publish on each copy an appropriate
351 copyright notice and disclaimer of warranty; keep intact all the
352 notices that refer to this License and to the absence of any
353 warranty; and give any other recipients of the Program a copy of
354 this License along with the Program.
356 You may charge a fee for the physical act of transferring a copy,
357 and you may at your option offer warranty protection in exchange
360 2. You may modify your copy or copies of the Program or any portion
361 of it, thus forming a work based on the Program, and copy and
362 distribute such modifications or work under the terms of Section 1
363 above, provided that you also meet all of these conditions:
365 a. You must cause the modified files to carry prominent notices
366 stating that you changed the files and the date of any change.
368 b. You must cause any work that you distribute or publish, that
369 in whole or in part contains or is derived from the Program
370 or any part thereof, to be licensed as a whole at no charge
371 to all third parties under the terms of this License.
373 c. If the modified program normally reads commands interactively
374 when run, you must cause it, when started running for such
375 interactive use in the most ordinary way, to print or display
376 an announcement including an appropriate copyright notice and
377 a notice that there is no warranty (or else, saying that you
378 provide a warranty) and that users may redistribute the
379 program under these conditions, and telling the user how to
380 view a copy of this License. (Exception: if the Program
381 itself is interactive but does not normally print such an
382 announcement, your work based on the Program is not required
383 to print an announcement.)
385 These requirements apply to the modified work as a whole. If
386 identifiable sections of that work are not derived from the
387 Program, and can be reasonably considered independent and separate
388 works in themselves, then this License, and its terms, do not
389 apply to those sections when you distribute them as separate
390 works. But when you distribute the same sections as part of a
391 whole which is a work based on the Program, the distribution of
392 the whole must be on the terms of this License, whose permissions
393 for other licensees extend to the entire whole, and thus to each
394 and every part regardless of who wrote it.
396 Thus, it is not the intent of this section to claim rights or
397 contest your rights to work written entirely by you; rather, the
398 intent is to exercise the right to control the distribution of
399 derivative or collective works based on the Program.
401 In addition, mere aggregation of another work not based on the
402 Program with the Program (or with a work based on the Program) on
403 a volume of a storage or distribution medium does not bring the
404 other work under the scope of this License.
406 3. You may copy and distribute the Program (or a work based on it,
407 under Section 2) in object code or executable form under the terms
408 of Sections 1 and 2 above provided that you also do one of the
411 a. Accompany it with the complete corresponding machine-readable
412 source code, which must be distributed under the terms of
413 Sections 1 and 2 above on a medium customarily used for
414 software interchange; or,
416 b. Accompany it with a written offer, valid for at least three
417 years, to give any third party, for a charge no more than your
418 cost of physically performing source distribution, a complete
419 machine-readable copy of the corresponding source code, to be
420 distributed under the terms of Sections 1 and 2 above on a
421 medium customarily used for software interchange; or,
423 c. Accompany it with the information you received as to the offer
424 to distribute corresponding source code. (This alternative is
425 allowed only for noncommercial distribution and only if you
426 received the program in object code or executable form with
427 such an offer, in accord with Subsection b above.)
429 The source code for a work means the preferred form of the work for
430 making modifications to it. For an executable work, complete
431 source code means all the source code for all modules it contains,
432 plus any associated interface definition files, plus the scripts
433 used to control compilation and installation of the executable.
434 However, as a special exception, the source code distributed need
435 not include anything that is normally distributed (in either
436 source or binary form) with the major components (compiler,
437 kernel, and so on) of the operating system on which the executable
438 runs, unless that component itself accompanies the executable.
440 If distribution of executable or object code is made by offering
441 access to copy from a designated place, then offering equivalent
442 access to copy the source code from the same place counts as
443 distribution of the source code, even though third parties are not
444 compelled to copy the source along with the object code.
446 4. You may not copy, modify, sublicense, or distribute the Program
447 except as expressly provided under this License. Any attempt
448 otherwise to copy, modify, sublicense or distribute the Program is
449 void, and will automatically terminate your rights under this
450 License. However, parties who have received copies, or rights,
451 from you under this License will not have their licenses
452 terminated so long as such parties remain in full compliance.
454 5. You are not required to accept this License, since you have not
455 signed it. However, nothing else grants you permission to modify
456 or distribute the Program or its derivative works. These actions
457 are prohibited by law if you do not accept this License.
458 Therefore, by modifying or distributing the Program (or any work
459 based on the Program), you indicate your acceptance of this
460 License to do so, and all its terms and conditions for copying,
461 distributing or modifying the Program or works based on it.
463 6. Each time you redistribute the Program (or any work based on the
464 Program), the recipient automatically receives a license from the
465 original licensor to copy, distribute or modify the Program
466 subject to these terms and conditions. You may not impose any
467 further restrictions on the recipients' exercise of the rights
468 granted herein. You are not responsible for enforcing compliance
469 by third parties to this License.
471 7. If, as a consequence of a court judgment or allegation of patent
472 infringement or for any other reason (not limited to patent
473 issues), conditions are imposed on you (whether by court order,
474 agreement or otherwise) that contradict the conditions of this
475 License, they do not excuse you from the conditions of this
476 License. If you cannot distribute so as to satisfy simultaneously
477 your obligations under this License and any other pertinent
478 obligations, then as a consequence you may not distribute the
479 Program at all. For example, if a patent license would not permit
480 royalty-free redistribution of the Program by all those who
481 receive copies directly or indirectly through you, then the only
482 way you could satisfy both it and this License would be to refrain
483 entirely from distribution of the Program.
485 If any portion of this section is held invalid or unenforceable
486 under any particular circumstance, the balance of the section is
487 intended to apply and the section as a whole is intended to apply
488 in other circumstances.
490 It is not the purpose of this section to induce you to infringe any
491 patents or other property right claims or to contest validity of
492 any such claims; this section has the sole purpose of protecting
493 the integrity of the free software distribution system, which is
494 implemented by public license practices. Many people have made
495 generous contributions to the wide range of software distributed
496 through that system in reliance on consistent application of that
497 system; it is up to the author/donor to decide if he or she is
498 willing to distribute software through any other system and a
499 licensee cannot impose that choice.
501 This section is intended to make thoroughly clear what is believed
502 to be a consequence of the rest of this License.
504 8. If the distribution and/or use of the Program is restricted in
505 certain countries either by patents or by copyrighted interfaces,
506 the original copyright holder who places the Program under this
507 License may add an explicit geographical distribution limitation
508 excluding those countries, so that distribution is permitted only
509 in or among countries not thus excluded. In such case, this
510 License incorporates the limitation as if written in the body of
513 9. The Free Software Foundation may publish revised and/or new
514 versions of the General Public License from time to time. Such
515 new versions will be similar in spirit to the present version, but
516 may differ in detail to address new problems or concerns.
518 Each version is given a distinguishing version number. If the
519 Program specifies a version number of this License which applies
520 to it and "any later version", you have the option of following
521 the terms and conditions either of that version or of any later
522 version published by the Free Software Foundation. If the Program
523 does not specify a version number of this License, you may choose
524 any version ever published by the Free Software Foundation.
526 10. If you wish to incorporate parts of the Program into other free
527 programs whose distribution conditions are different, write to the
528 author to ask for permission. For software which is copyrighted
529 by the Free Software Foundation, write to the Free Software
530 Foundation; we sometimes make exceptions for this. Our decision
531 will be guided by the two goals of preserving the free status of
532 all derivatives of our free software and of promoting the sharing
533 and reuse of software generally.
537 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
538 WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
539 LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
540 HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
541 WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
542 NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
543 FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
544 QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
545 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
546 SERVICING, REPAIR OR CORRECTION.
548 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
549 WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
550 MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
551 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
552 INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
553 INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
554 DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
555 OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
556 OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
557 ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
559 END OF TERMS AND CONDITIONS
561 Appendix: How to Apply These Terms to Your New Programs
562 =======================================================
564 If you develop a new program, and you want it to be of the greatest
565 possible use to the public, the best way to achieve this is to make it
566 free software which everyone can redistribute and change under these
569 To do so, attach the following notices to the program. It is safest
570 to attach them to the start of each source file to most effectively
571 convey the exclusion of warranty; and each file should have at least
572 the "copyright" line and a pointer to where the full notice is found.
574 ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
575 Copyright (C) YYYY NAME OF AUTHOR
577 This program is free software; you can redistribute it and/or modify
578 it under the terms of the GNU General Public License as published by
579 the Free Software Foundation; either version 2 of the License, or
580 (at your option) any later version.
582 This program is distributed in the hope that it will be useful,
583 but WITHOUT ANY WARRANTY; without even the implied warranty of
584 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
585 GNU General Public License for more details.
587 You should have received a copy of the GNU General Public License
588 along with this program; if not, write to the Free Software
589 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
591 Also add information on how to contact you by electronic and paper
594 If the program is interactive, make it output a short notice like
595 this when it starts in an interactive mode:
597 Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
598 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
599 This is free software, and you are welcome to redistribute it
600 under certain conditions; type `show c' for details.
602 The hypothetical commands `show w' and `show c' should show the
603 appropriate parts of the General Public License. Of course, the
604 commands you use may be called something other than `show w' and `show
605 c'; they could even be mouse-clicks or menu items--whatever suits your
608 You should also get your employer (if you work as a programmer) or
609 your school, if any, to sign a "copyright disclaimer" for the program,
610 if necessary. Here is a sample; alter the names:
612 Yoyodyne, Inc., hereby disclaims all copyright interest in the program
613 `Gnomovision' (which makes passes at compilers) written by James Hacker.
615 SIGNATURE OF TY COON, 1 April 1989
616 Ty Coon, President of Vice
618 This General Public License does not permit incorporating your
619 program into proprietary programs. If your program is a subroutine
620 library, you may consider it more useful to permit linking proprietary
621 applications with the library. If this is what you want to do, use the
622 GNU Library General Public License instead of this License.
625 File: bison.info, Node: Concepts, Next: Examples, Prev: Copying, Up: Top
627 The Concepts of Bison
628 *********************
630 This chapter introduces many of the basic concepts without which the
631 details of Bison will not make sense. If you do not already know how to
632 use Bison or Yacc, we suggest you start by reading this chapter
637 * Language and Grammar:: Languages and context-free grammars,
638 as mathematical ideas.
639 * Grammar in Bison:: How we represent grammars for Bison's sake.
640 * Semantic Values:: Each token or syntactic grouping can have
641 a semantic value (the value of an integer,
642 the name of an identifier, etc.).
643 * Semantic Actions:: Each rule can have an action containing C code.
644 * Locations Overview:: Tracking Locations.
645 * Bison Parser:: What are Bison's input and output,
646 how is the output used?
647 * Stages:: Stages in writing and running Bison grammars.
648 * Grammar Layout:: Overall structure of a Bison grammar file.
651 File: bison.info, Node: Language and Grammar, Next: Grammar in Bison, Up: Concepts
653 Languages and Context-Free Grammars
654 ===================================
656 In order for Bison to parse a language, it must be described by a
657 "context-free grammar". This means that you specify one or more
658 "syntactic groupings" and give rules for constructing them from their
659 parts. For example, in the C language, one kind of grouping is called
660 an `expression'. One rule for making an expression might be, "An
661 expression can be made of a minus sign and another expression".
662 Another would be, "An expression can be an integer". As you can see,
663 rules are often recursive, but there must be at least one rule which
664 leads out of the recursion.
666 The most common formal system for presenting such rules for humans
667 to read is "Backus-Naur Form" or "BNF", which was developed in order to
668 specify the language Algol 60. Any grammar expressed in BNF is a
669 context-free grammar. The input to Bison is essentially
670 machine-readable BNF.
672 Not all context-free languages can be handled by Bison, only those
673 that are LALR(1). In brief, this means that it must be possible to
674 tell how to parse any portion of an input string with just a single
675 token of look-ahead. Strictly speaking, that is a description of an
676 LR(1) grammar, and LALR(1) involves additional restrictions that are
677 hard to explain simply; but it is rare in actual practice to find an
678 LR(1) grammar that fails to be LALR(1). *Note Mysterious Reduce/Reduce
679 Conflicts: Mystery Conflicts, for more information on this.
681 In the formal grammatical rules for a language, each kind of
682 syntactic unit or grouping is named by a "symbol". Those which are
683 built by grouping smaller constructs according to grammatical rules are
684 called "nonterminal symbols"; those which can't be subdivided are called
685 "terminal symbols" or "token types". We call a piece of input
686 corresponding to a single terminal symbol a "token", and a piece
687 corresponding to a single nonterminal symbol a "grouping".
689 We can use the C language as an example of what symbols, terminal and
690 nonterminal, mean. The tokens of C are identifiers, constants (numeric
691 and string), and the various keywords, arithmetic operators and
692 punctuation marks. So the terminal symbols of a grammar for C include
693 `identifier', `number', `string', plus one symbol for each keyword,
694 operator or punctuation mark: `if', `return', `const', `static', `int',
695 `char', `plus-sign', `open-brace', `close-brace', `comma' and many
696 more. (These tokens can be subdivided into characters, but that is a
697 matter of lexicography, not grammar.)
699 Here is a simple C function subdivided into tokens:
701 int /* keyword `int' */
702 square (x) /* identifier, open-paren, */
703 /* identifier, close-paren */
704 int x; /* keyword `int', identifier, semicolon */
706 return x * x; /* keyword `return', identifier, */
707 /* asterisk, identifier, semicolon */
710 The syntactic groupings of C include the expression, the statement,
711 the declaration, and the function definition. These are represented in
712 the grammar of C by nonterminal symbols `expression', `statement',
713 `declaration' and `function definition'. The full grammar uses dozens
714 of additional language constructs, each with its own nonterminal
715 symbol, in order to express the meanings of these four. The example
716 above is a function definition; it contains one declaration, and one
717 statement. In the statement, each `x' is an expression and so is `x *
720 Each nonterminal symbol must have grammatical rules showing how it
721 is made out of simpler constructs. For example, one kind of C
722 statement is the `return' statement; this would be described with a
723 grammar rule which reads informally as follows:
725 A `statement' can be made of a `return' keyword, an `expression'
728 There would be many other rules for `statement', one for each kind of
731 One nonterminal symbol must be distinguished as the special one which
732 defines a complete utterance in the language. It is called the "start
733 symbol". In a compiler, this means a complete input program. In the C
734 language, the nonterminal symbol `sequence of definitions and
735 declarations' plays this role.
737 For example, `1 + 2' is a valid C expression--a valid part of a C
738 program--but it is not valid as an _entire_ C program. In the
739 context-free grammar of C, this follows from the fact that `expression'
740 is not the start symbol.
742 The Bison parser reads a sequence of tokens as its input, and groups
743 the tokens using the grammar rules. If the input is valid, the end
744 result is that the entire token sequence reduces to a single grouping
745 whose symbol is the grammar's start symbol. If we use a grammar for C,
746 the entire input must be a `sequence of definitions and declarations'.
747 If not, the parser reports a syntax error.
750 File: bison.info, Node: Grammar in Bison, Next: Semantic Values, Prev: Language and Grammar, Up: Concepts
752 From Formal Rules to Bison Input
753 ================================
755 A formal grammar is a mathematical construct. To define the language
756 for Bison, you must write a file expressing the grammar in Bison syntax:
757 a "Bison grammar" file. *Note Bison Grammar Files: Grammar File.
759 A nonterminal symbol in the formal grammar is represented in Bison
760 input as an identifier, like an identifier in C. By convention, it
761 should be in lower case, such as `expr', `stmt' or `declaration'.
763 The Bison representation for a terminal symbol is also called a
764 "token type". Token types as well can be represented as C-like
765 identifiers. By convention, these identifiers should be upper case to
766 distinguish them from nonterminals: for example, `INTEGER',
767 `IDENTIFIER', `IF' or `RETURN'. A terminal symbol that stands for a
768 particular keyword in the language should be named after that keyword
769 converted to upper case. The terminal symbol `error' is reserved for
770 error recovery. *Note Symbols::.
772 A terminal symbol can also be represented as a character literal,
773 just like a C character constant. You should do this whenever a token
774 is just a single character (parenthesis, plus-sign, etc.): use that
775 same character in a literal as the terminal symbol for that token.
777 A third way to represent a terminal symbol is with a C string
778 constant containing several characters. *Note Symbols::, for more
781 The grammar rules also have an expression in Bison syntax. For
782 example, here is the Bison rule for a C `return' statement. The
783 semicolon in quotes is a literal character token, representing part of
784 the C syntax for the statement; the naked semicolon, and the colon, are
785 Bison punctuation used in every rule.
787 stmt: RETURN expr ';'
790 *Note Syntax of Grammar Rules: Rules.
793 File: bison.info, Node: Semantic Values, Next: Semantic Actions, Prev: Grammar in Bison, Up: Concepts
798 A formal grammar selects tokens only by their classifications: for
799 example, if a rule mentions the terminal symbol `integer constant', it
800 means that _any_ integer constant is grammatically valid in that
801 position. The precise value of the constant is irrelevant to how to
802 parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
805 But the precise value is very important for what the input means
806 once it is parsed. A compiler is useless if it fails to distinguish
807 between 4, 1 and 3989 as constants in the program! Therefore, each
808 token in a Bison grammar has both a token type and a "semantic value".
809 *Note Defining Language Semantics: Semantics, for details.
811 The token type is a terminal symbol defined in the grammar, such as
812 `INTEGER', `IDENTIFIER' or `',''. It tells everything you need to know
813 to decide where the token may validly appear and how to group it with
814 other tokens. The grammar rules know nothing about tokens except their
817 The semantic value has all the rest of the information about the
818 meaning of the token, such as the value of an integer, or the name of an
819 identifier. (A token such as `','' which is just punctuation doesn't
820 need to have any semantic value.)
822 For example, an input token might be classified as token type
823 `INTEGER' and have the semantic value 4. Another input token might
824 have the same token type `INTEGER' but value 3989. When a grammar rule
825 says that `INTEGER' is allowed, either of these tokens is acceptable
826 because each is an `INTEGER'. When the parser accepts the token, it
827 keeps track of the token's semantic value.
829 Each grouping can also have a semantic value as well as its
830 nonterminal symbol. For example, in a calculator, an expression
831 typically has a semantic value that is a number. In a compiler for a
832 programming language, an expression typically has a semantic value that
833 is a tree structure describing the meaning of the expression.
836 File: bison.info, Node: Semantic Actions, Next: Locations Overview, Prev: Semantic Values, Up: Concepts
841 In order to be useful, a program must do more than parse input; it
842 must also produce some output based on the input. In a Bison grammar,
843 a grammar rule can have an "action" made up of C statements. Each time
844 the parser recognizes a match for that rule, the action is executed.
847 Most of the time, the purpose of an action is to compute the
848 semantic value of the whole construct from the semantic values of its
849 parts. For example, suppose we have a rule which says an expression
850 can be the sum of two expressions. When the parser recognizes such a
851 sum, each of the subexpressions has a semantic value which describes
852 how it was built up. The action for this rule should create a similar
853 sort of value for the newly recognized larger expression.
855 For example, here is a rule that says an expression can be the sum of
858 expr: expr '+' expr { $$ = $1 + $3; }
861 The action says how to produce the semantic value of the sum expression
862 from the values of the two subexpressions.
865 File: bison.info, Node: Locations Overview, Next: Bison Parser, Prev: Semantic Actions, Up: Concepts
870 Many applications, like interpreters or compilers, have to produce
871 verbose and useful error messages. To achieve this, one must be able to
872 keep track of the "textual position", or "location", of each syntactic
873 construct. Bison provides a mechanism for handling these locations.
875 Each token has a semantic value. In a similar fashion, each token
876 has an associated location, but the type of locations is the same for
877 all tokens and groupings. Moreover, the output parser is equipped with
878 a default data structure for storing locations (*note Locations::, for
881 Like semantic values, locations can be reached in actions using a
882 dedicated set of constructs. In the example above, the location of the
883 whole grouping is `@$', while the locations of the subexpressions are
886 When a rule is matched, a default action is used to compute the
887 semantic value of its left hand side (*note Actions::). In the same
888 way, another default action is used for locations. However, the action
889 for locations is general enough for most cases, meaning there is
890 usually no need to describe for each rule how `@$' should be formed.
891 When building a new location for a given grouping, the default behavior
892 of the output parser is to take the beginning of the first symbol, and
893 the end of the last symbol.
896 File: bison.info, Node: Bison Parser, Next: Stages, Prev: Locations Overview, Up: Concepts
898 Bison Output: the Parser File
899 =============================
901 When you run Bison, you give it a Bison grammar file as input. The
902 output is a C source file that parses the language described by the
903 grammar. This file is called a "Bison parser". Keep in mind that the
904 Bison utility and the Bison parser are two distinct programs: the Bison
905 utility is a program whose output is the Bison parser that becomes part
908 The job of the Bison parser is to group tokens into groupings
909 according to the grammar rules--for example, to build identifiers and
910 operators into expressions. As it does this, it runs the actions for
911 the grammar rules it uses.
913 The tokens come from a function called the "lexical analyzer" that
914 you must supply in some fashion (such as by writing it in C). The
915 Bison parser calls the lexical analyzer each time it wants a new token.
916 It doesn't know what is "inside" the tokens (though their semantic
917 values may reflect this). Typically the lexical analyzer makes the
918 tokens by parsing characters of text, but Bison does not depend on
919 this. *Note The Lexical Analyzer Function `yylex': Lexical.
921 The Bison parser file is C code which defines a function named
922 `yyparse' which implements that grammar. This function does not make a
923 complete C program: you must supply some additional functions. One is
924 the lexical analyzer. Another is an error-reporting function which the
925 parser calls to report an error. In addition, a complete C program must
926 start with a function called `main'; you have to provide this, and
927 arrange for it to call `yyparse' or the parser will never run. *Note
928 Parser C-Language Interface: Interface.
930 Aside from the token type names and the symbols in the actions you
931 write, all variable and function names used in the Bison parser file
932 begin with `yy' or `YY'. This includes interface functions such as the
933 lexical analyzer function `yylex', the error reporting function
934 `yyerror' and the parser function `yyparse' itself. This also includes
935 numerous identifiers used for internal purposes. Therefore, you should
936 avoid using C identifiers starting with `yy' or `YY' in the Bison
937 grammar file except for the ones defined in this manual.
940 File: bison.info, Node: Stages, Next: Grammar Layout, Prev: Bison Parser, Up: Concepts
942 Stages in Using Bison
943 =====================
945 The actual language-design process using Bison, from grammar
946 specification to a working compiler or interpreter, has these parts:
948 1. Formally specify the grammar in a form recognized by Bison (*note
949 Bison Grammar Files: Grammar File.). For each grammatical rule in
950 the language, describe the action that is to be taken when an
951 instance of that rule is recognized. The action is described by a
952 sequence of C statements.
954 2. Write a lexical analyzer to process input and pass tokens to the
955 parser. The lexical analyzer may be written by hand in C (*note
956 The Lexical Analyzer Function `yylex': Lexical.). It could also
957 be produced using Lex, but the use of Lex is not discussed in this
960 3. Write a controlling function that calls the Bison-produced parser.
962 4. Write error-reporting routines.
964 To turn this source code as written into a runnable program, you
965 must follow these steps:
967 1. Run Bison on the grammar to produce the parser.
969 2. Compile the code output by Bison, as well as any other source
972 3. Link the object files to produce the finished product.
975 File: bison.info, Node: Grammar Layout, Prev: Stages, Up: Concepts
977 The Overall Layout of a Bison Grammar
978 =====================================
980 The input file for the Bison utility is a "Bison grammar file". The
981 general form of a Bison grammar file is as follows:
984 PROLOGUE (DECLARATIONS)
992 EPILOGUE (ADDITIONAL CODE)
994 The `%%', `%{' and `%}' are punctuation that appears in every Bison
995 grammar file to separate the sections.
997 The prologue may define types and variables used in the actions. You
998 can also use preprocessor commands to define macros used there, and use
999 `#include' to include header files that do any of these things.
1001 The Bison declarations declare the names of the terminal and
1002 nonterminal symbols, and may also describe operator precedence and the
1003 data types of semantic values of various symbols.
1005 The grammar rules define how to construct each nonterminal symbol
1008 The epilogue can contain any code you want to use. Often the
1009 definition of the lexical analyzer `yylex' goes here, plus subroutines
1010 called by the actions in the grammar rules. In a simple program, all
1011 the rest of the program can go here.
1014 File: bison.info, Node: Examples, Next: Grammar File, Prev: Concepts, Up: Top
1019 Now we show and explain three sample programs written using Bison: a
1020 reverse polish notation calculator, an algebraic (infix) notation
1021 calculator, and a multi-function calculator. All three have been tested
1022 under BSD Unix 4.3; each produces a usable, though limited, interactive
1023 desk-top calculator.
1025 These examples are simple, but Bison grammars for real programming
1026 languages are written the same way. You can copy these examples out of
1027 the Info file and into a source file to try them.
1031 * RPN Calc:: Reverse polish notation calculator;
1032 a first example with no operator precedence.
1033 * Infix Calc:: Infix (algebraic) notation calculator.
1034 Operator precedence is introduced.
1035 * Simple Error Recovery:: Continuing after syntax errors.
1036 * Multi-function Calc:: Calculator with memory and trig functions.
1037 It uses multiple data-types for semantic values.
1038 * Exercises:: Ideas for improving the multi-function calculator.
1041 File: bison.info, Node: RPN Calc, Next: Infix Calc, Up: Examples
1043 Reverse Polish Notation Calculator
1044 ==================================
1046 The first example is that of a simple double-precision "reverse
1047 polish notation" calculator (a calculator using postfix operators).
1048 This example provides a good starting point, since operator precedence
1049 is not an issue. The second example will illustrate how operator
1050 precedence is handled.
1052 The source code for this calculator is named `rpcalc.y'. The `.y'
1053 extension is a convention used for Bison input files.
1057 * Decls: Rpcalc Decls. Prologue (declarations) for rpcalc.
1058 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1059 * Lexer: Rpcalc Lexer. The lexical analyzer.
1060 * Main: Rpcalc Main. The controlling function.
1061 * Error: Rpcalc Error. The error reporting function.
1062 * Gen: Rpcalc Gen. Running Bison on the grammar file.
1063 * Comp: Rpcalc Compile. Run the C compiler on the output code.