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