1 Ceci est le fichier Info bison.info, produit par Makeinfo version 4.0 à
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 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.28a 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 * Index:: Cross-references to the text.
60 --- The Detailed Node Listing ---
64 * Language and Grammar:: Languages and context-free grammars,
65 as mathematical ideas.
66 * Grammar in Bison:: How we represent grammars for Bison's sake.
67 * Semantic Values:: Each token or syntactic grouping can have
68 a semantic value (the value of an integer,
69 the name of an identifier, etc.).
70 * Semantic Actions:: Each rule can have an action containing C code.
71 * Bison Parser:: What are Bison's input and output,
72 how is the output used?
73 * Stages:: Stages in writing and running Bison grammars.
74 * Grammar Layout:: Overall structure of a Bison grammar file.
78 * RPN Calc:: Reverse polish notation calculator;
79 a first example with no operator precedence.
80 * Infix Calc:: Infix (algebraic) notation calculator.
81 Operator precedence is introduced.
82 * Simple Error Recovery:: Continuing after syntax errors.
83 * Multi-function Calc:: Calculator with memory and trig functions.
84 It uses multiple data-types for semantic values.
85 * Exercises:: Ideas for improving the multi-function calculator.
87 Reverse Polish Notation Calculator
89 * Decls: Rpcalc Decls. Bison and C declarations for rpcalc.
90 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
91 * Lexer: Rpcalc Lexer. The lexical analyzer.
92 * Main: Rpcalc Main. The controlling function.
93 * Error: Rpcalc Error. The error reporting function.
94 * Gen: Rpcalc Gen. Running Bison on the grammar file.
95 * Comp: Rpcalc Compile. Run the C compiler on the output code.
97 Grammar Rules for `rpcalc'
103 Multi-Function Calculator: `mfcalc'
105 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
106 * Rules: Mfcalc Rules. Grammar rules for the calculator.
107 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
111 * Grammar Outline:: Overall layout of the grammar file.
112 * Symbols:: Terminal and nonterminal symbols.
113 * Rules:: How to write grammar rules.
114 * Recursion:: Writing recursive rules.
115 * Semantics:: Semantic values and actions.
116 * Declarations:: All kinds of Bison declarations are described here.
117 * Multiple Parsers:: Putting more than one Bison parser in one program.
119 Outline of a Bison Grammar
121 * C Declarations:: Syntax and usage of the C declarations section.
122 * Bison Declarations:: Syntax and usage of the Bison declarations section.
123 * Grammar Rules:: Syntax and usage of the grammar rules section.
124 * C Code:: Syntax and usage of the additional C code section.
126 Defining Language Semantics
128 * Value Type:: Specifying one data type for all semantic values.
129 * Multiple Types:: Specifying several alternative data types.
130 * Actions:: An action is the semantic definition of a grammar rule.
131 * Action Types:: Specifying data types for actions to operate on.
132 * Mid-Rule Actions:: Most actions go at the end of a rule.
133 This says when, why and how to use the exceptional
134 action in the middle of a rule.
138 * Token Decl:: Declaring terminal symbols.
139 * Precedence Decl:: Declaring terminals with precedence and associativity.
140 * Union Decl:: Declaring the set of all semantic value types.
141 * Type Decl:: Declaring the choice of type for a nonterminal symbol.
142 * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
143 * Start Decl:: Specifying the start symbol.
144 * Pure Decl:: Requesting a reentrant parser.
145 * Decl Summary:: Table of all Bison declarations.
147 Parser C-Language Interface
149 * Parser Function:: How to call `yyparse' and what it returns.
150 * Lexical:: You must supply a function `yylex'
152 * Error Reporting:: You must supply a function `yyerror'.
153 * Action Features:: Special features for use in actions.
155 The Lexical Analyzer Function `yylex'
157 * Calling Convention:: How `yyparse' calls `yylex'.
158 * Token Values:: How `yylex' must return the semantic value
159 of the token it has read.
160 * Token Positions:: How `yylex' must return the text position
161 (line number, etc.) of the token, if the
163 * Pure Calling:: How the calling convention differs
164 in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
166 The Bison Parser Algorithm
168 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
169 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
170 * Precedence:: Operator precedence works by resolving conflicts.
171 * Contextual Precedence:: When an operator's precedence depends on context.
172 * Parser States:: The parser is a finite-state-machine with stack.
173 * Reduce/Reduce:: When two rules are applicable in the same situation.
174 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
175 * Stack Overflow:: What happens when stack gets full. How to avoid it.
179 * Why Precedence:: An example showing why precedence is needed.
180 * Using Precedence:: How to specify precedence in Bison grammars.
181 * Precedence Examples:: How these features are used in the previous example.
182 * How Precedence:: How they work.
184 Handling Context Dependencies
186 * Semantic Tokens:: Token parsing can depend on the semantic context.
187 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
188 * Tie-in Recovery:: Lexical tie-ins have implications for how
189 error recovery rules must be written.
193 * Bison Options:: All the options described in detail,
194 in alphabetical order by short options.
195 * Option Cross Key:: Alphabetical list of long options.
196 * VMS Invocation:: Bison command syntax on VMS.
199 File: bison.info, Node: Introduction, Next: Conditions, Prev: Top, Up: Top
204 "Bison" is a general-purpose parser generator that converts a
205 grammar description for an LALR(1) context-free grammar into a C
206 program to parse that grammar. Once you are proficient with Bison, you
207 may use it to develop a wide range of language parsers, from those used
208 in simple desk calculators to complex programming languages.
210 Bison is upward compatible with Yacc: all properly-written Yacc
211 grammars ought to work with Bison with no change. Anyone familiar with
212 Yacc should be able to use Bison with little trouble. You need to be
213 fluent in C programming in order to use Bison or to understand this
216 We begin with tutorial chapters that explain the basic concepts of
217 using Bison and show three explained examples, each building on the
218 last. If you don't know Bison or Yacc, start by reading these
219 chapters. Reference chapters follow which describe specific aspects of
222 Bison was written primarily by Robert Corbett; Richard Stallman made
223 it Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added
224 multi-character string literals and other features.
226 This edition corresponds to version 1.28a of Bison.
229 File: bison.info, Node: Conditions, Next: Copying, Prev: Introduction, Up: Top
231 Conditions for Using Bison
232 **************************
234 As of Bison version 1.24, we have changed the distribution terms for
235 `yyparse' to permit using Bison's output in nonfree programs.
236 Formerly, Bison parsers could be used only in programs that were free
239 The other GNU programming tools, such as the GNU C compiler, have
240 never had such a requirement. They could always be used for nonfree
241 software. The reason Bison was different was not due to a special
242 policy decision; it resulted from applying the usual General Public
243 License to all of the Bison source code.
245 The output of the Bison utility--the Bison parser file--contains a
246 verbatim copy of a sizable piece of Bison, which is the code for the
247 `yyparse' function. (The actions from your grammar are inserted into
248 this function at one point, but the rest of the function is not
249 changed.) When we applied the GPL terms to the code for `yyparse', the
250 effect was to restrict the use of Bison output to free software.
252 We didn't change the terms because of sympathy for people who want to
253 make software proprietary. *Software should be free.* But we
254 concluded that limiting Bison's use to free software was doing little to
255 encourage people to make other software free. So we decided to make the
256 practical conditions for using Bison match the practical conditions for
257 using the other GNU tools.
260 File: bison.info, Node: Copying, Next: Concepts, Prev: Conditions, Up: Top
262 GNU GENERAL PUBLIC LICENSE
263 **************************
267 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
268 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
270 Everyone is permitted to copy and distribute verbatim copies
271 of this license document, but changing it is not allowed.
276 The licenses for most software are designed to take away your
277 freedom to share and change it. By contrast, the GNU General Public
278 License is intended to guarantee your freedom to share and change free
279 software--to make sure the software is free for all its users. This
280 General Public License applies to most of the Free Software
281 Foundation's software and to any other program whose authors commit to
282 using it. (Some other Free Software Foundation software is covered by
283 the GNU Library General Public License instead.) You can apply it to
286 When we speak of free software, we are referring to freedom, not
287 price. Our General Public Licenses are designed to make sure that you
288 have the freedom to distribute copies of free software (and charge for
289 this service if you wish), that you receive source code or can get it
290 if you want it, that you can change the software or use pieces of it in
291 new free programs; and that you know you can do these things.
293 To protect your rights, we need to make restrictions that forbid
294 anyone to deny you these rights or to ask you to surrender the rights.
295 These restrictions translate to certain responsibilities for you if you
296 distribute copies of the software, or if you modify it.
298 For example, if you distribute copies of such a program, whether
299 gratis or for a fee, you must give the recipients all the rights that
300 you have. You must make sure that they, too, receive or can get the
301 source code. And you must show them these terms so they know their
304 We protect your rights with two steps: (1) copyright the software,
305 and (2) offer you this license which gives you legal permission to copy,
306 distribute and/or modify the software.
308 Also, for each author's protection and ours, we want to make certain
309 that everyone understands that there is no warranty for this free
310 software. If the software is modified by someone else and passed on, we
311 want its recipients to know that what they have is not the original, so
312 that any problems introduced by others will not reflect on the original
313 authors' reputations.
315 Finally, any free program is threatened constantly by software
316 patents. We wish to avoid the danger that redistributors of a free
317 program will individually obtain patent licenses, in effect making the
318 program proprietary. To prevent this, we have made it clear that any
319 patent must be licensed for everyone's free use or not licensed at all.
321 The precise terms and conditions for copying, distribution and
324 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
326 0. This License applies to any program or other work which contains a
327 notice placed by the copyright holder saying it may be distributed
328 under the terms of this General Public License. The "Program",
329 below, refers to any such program or work, and a "work based on
330 the Program" means either the Program or any derivative work under
331 copyright law: that is to say, a work containing the Program or a
332 portion of it, either verbatim or with modifications and/or
333 translated into another language. (Hereinafter, translation is
334 included without limitation in the term "modification".) Each
335 licensee is addressed as "you".
337 Activities other than copying, distribution and modification are
338 not covered by this License; they are outside its scope. The act
339 of running the Program is not restricted, and the output from the
340 Program is covered only if its contents constitute a work based on
341 the Program (independent of having been made by running the
342 Program). Whether that is true depends on what the Program does.
344 1. You may copy and distribute verbatim copies of the Program's
345 source code as you receive it, in any medium, provided that you
346 conspicuously and appropriately publish on each copy an appropriate
347 copyright notice and disclaimer of warranty; keep intact all the
348 notices that refer to this License and to the absence of any
349 warranty; and give any other recipients of the Program a copy of
350 this License along with the Program.
352 You may charge a fee for the physical act of transferring a copy,
353 and you may at your option offer warranty protection in exchange
356 2. You may modify your copy or copies of the Program or any portion
357 of it, thus forming a work based on the Program, and copy and
358 distribute such modifications or work under the terms of Section 1
359 above, provided that you also meet all of these conditions:
361 a. You must cause the modified files to carry prominent notices
362 stating that you changed the files and the date of any change.
364 b. You must cause any work that you distribute or publish, that
365 in whole or in part contains or is derived from the Program
366 or any part thereof, to be licensed as a whole at no charge
367 to all third parties under the terms of this License.
369 c. If the modified program normally reads commands interactively
370 when run, you must cause it, when started running for such
371 interactive use in the most ordinary way, to print or display
372 an announcement including an appropriate copyright notice and
373 a notice that there is no warranty (or else, saying that you
374 provide a warranty) and that users may redistribute the
375 program under these conditions, and telling the user how to
376 view a copy of this License. (Exception: if the Program
377 itself is interactive but does not normally print such an
378 announcement, your work based on the Program is not required
379 to print an announcement.)
381 These requirements apply to the modified work as a whole. If
382 identifiable sections of that work are not derived from the
383 Program, and can be reasonably considered independent and separate
384 works in themselves, then this License, and its terms, do not
385 apply to those sections when you distribute them as separate
386 works. But when you distribute the same sections as part of a
387 whole which is a work based on the Program, the distribution of
388 the whole must be on the terms of this License, whose permissions
389 for other licensees extend to the entire whole, and thus to each
390 and every part regardless of who wrote it.
392 Thus, it is not the intent of this section to claim rights or
393 contest your rights to work written entirely by you; rather, the
394 intent is to exercise the right to control the distribution of
395 derivative or collective works based on the Program.
397 In addition, mere aggregation of another work not based on the
398 Program with the Program (or with a work based on the Program) on
399 a volume of a storage or distribution medium does not bring the
400 other work under the scope of this License.
402 3. You may copy and distribute the Program (or a work based on it,
403 under Section 2) in object code or executable form under the terms
404 of Sections 1 and 2 above provided that you also do one of the
407 a. Accompany it with the complete corresponding machine-readable
408 source code, which must be distributed under the terms of
409 Sections 1 and 2 above on a medium customarily used for
410 software interchange; or,
412 b. Accompany it with a written offer, valid for at least three
413 years, to give any third party, for a charge no more than your
414 cost of physically performing source distribution, a complete
415 machine-readable copy of the corresponding source code, to be
416 distributed under the terms of Sections 1 and 2 above on a
417 medium customarily used for software interchange; or,
419 c. Accompany it with the information you received as to the offer
420 to distribute corresponding source code. (This alternative is
421 allowed only for noncommercial distribution and only if you
422 received the program in object code or executable form with
423 such an offer, in accord with Subsection b above.)
425 The source code for a work means the preferred form of the work for
426 making modifications to it. For an executable work, complete
427 source code means all the source code for all modules it contains,
428 plus any associated interface definition files, plus the scripts
429 used to control compilation and installation of the executable.
430 However, as a special exception, the source code distributed need
431 not include anything that is normally distributed (in either
432 source or binary form) with the major components (compiler,
433 kernel, and so on) of the operating system on which the executable
434 runs, unless that component itself accompanies the executable.
436 If distribution of executable or object code is made by offering
437 access to copy from a designated place, then offering equivalent
438 access to copy the source code from the same place counts as
439 distribution of the source code, even though third parties are not
440 compelled to copy the source along with the object code.
442 4. You may not copy, modify, sublicense, or distribute the Program
443 except as expressly provided under this License. Any attempt
444 otherwise to copy, modify, sublicense or distribute the Program is
445 void, and will automatically terminate your rights under this
446 License. However, parties who have received copies, or rights,
447 from you under this License will not have their licenses
448 terminated so long as such parties remain in full compliance.
450 5. You are not required to accept this License, since you have not
451 signed it. However, nothing else grants you permission to modify
452 or distribute the Program or its derivative works. These actions
453 are prohibited by law if you do not accept this License.
454 Therefore, by modifying or distributing the Program (or any work
455 based on the Program), you indicate your acceptance of this
456 License to do so, and all its terms and conditions for copying,
457 distributing or modifying the Program or works based on it.
459 6. Each time you redistribute the Program (or any work based on the
460 Program), the recipient automatically receives a license from the
461 original licensor to copy, distribute or modify the Program
462 subject to these terms and conditions. You may not impose any
463 further restrictions on the recipients' exercise of the rights
464 granted herein. You are not responsible for enforcing compliance
465 by third parties to this License.
467 7. If, as a consequence of a court judgment or allegation of patent
468 infringement or for any other reason (not limited to patent
469 issues), conditions are imposed on you (whether by court order,
470 agreement or otherwise) that contradict the conditions of this
471 License, they do not excuse you from the conditions of this
472 License. If you cannot distribute so as to satisfy simultaneously
473 your obligations under this License and any other pertinent
474 obligations, then as a consequence you may not distribute the
475 Program at all. For example, if a patent license would not permit
476 royalty-free redistribution of the Program by all those who
477 receive copies directly or indirectly through you, then the only
478 way you could satisfy both it and this License would be to refrain
479 entirely from distribution of the Program.
481 If any portion of this section is held invalid or unenforceable
482 under any particular circumstance, the balance of the section is
483 intended to apply and the section as a whole is intended to apply
484 in other circumstances.
486 It is not the purpose of this section to induce you to infringe any
487 patents or other property right claims or to contest validity of
488 any such claims; this section has the sole purpose of protecting
489 the integrity of the free software distribution system, which is
490 implemented by public license practices. Many people have made
491 generous contributions to the wide range of software distributed
492 through that system in reliance on consistent application of that
493 system; it is up to the author/donor to decide if he or she is
494 willing to distribute software through any other system and a
495 licensee cannot impose that choice.
497 This section is intended to make thoroughly clear what is believed
498 to be a consequence of the rest of this License.
500 8. If the distribution and/or use of the Program is restricted in
501 certain countries either by patents or by copyrighted interfaces,
502 the original copyright holder who places the Program under this
503 License may add an explicit geographical distribution limitation
504 excluding those countries, so that distribution is permitted only
505 in or among countries not thus excluded. In such case, this
506 License incorporates the limitation as if written in the body of
509 9. The Free Software Foundation may publish revised and/or new
510 versions of the General Public License from time to time. Such
511 new versions will be similar in spirit to the present version, but
512 may differ in detail to address new problems or concerns.
514 Each version is given a distinguishing version number. If the
515 Program specifies a version number of this License which applies
516 to it and "any later version", you have the option of following
517 the terms and conditions either of that version or of any later
518 version published by the Free Software Foundation. If the Program
519 does not specify a version number of this License, you may choose
520 any version ever published by the Free Software Foundation.
522 10. If you wish to incorporate parts of the Program into other free
523 programs whose distribution conditions are different, write to the
524 author to ask for permission. For software which is copyrighted
525 by the Free Software Foundation, write to the Free Software
526 Foundation; we sometimes make exceptions for this. Our decision
527 will be guided by the two goals of preserving the free status of
528 all derivatives of our free software and of promoting the sharing
529 and reuse of software generally.
533 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
534 WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
535 LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
536 HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
537 WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
538 NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
539 FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
540 QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
541 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
542 SERVICING, REPAIR OR CORRECTION.
544 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
545 WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
546 MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
547 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
548 INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
549 INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
550 DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
551 OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
552 OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
553 ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
555 END OF TERMS AND CONDITIONS
557 How to Apply These Terms to Your New Programs
558 =============================================
560 If you develop a new program, and you want it to be of the greatest
561 possible use to the public, the best way to achieve this is to make it
562 free software which everyone can redistribute and change under these
565 To do so, attach the following notices to the program. It is safest
566 to attach them to the start of each source file to most effectively
567 convey the exclusion of warranty; and each file should have at least
568 the "copyright" line and a pointer to where the full notice is found.
570 ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
571 Copyright (C) 19YY NAME OF AUTHOR
573 This program is free software; you can redistribute it and/or modify
574 it under the terms of the GNU General Public License as published by
575 the Free Software Foundation; either version 2 of the License, or
576 (at your option) any later version.
578 This program is distributed in the hope that it will be useful,
579 but WITHOUT ANY WARRANTY; without even the implied warranty of
580 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
581 GNU General Public License for more details.
583 You should have received a copy of the GNU General Public License
584 along with this program; if not, write to the Free Software
585 Foundation, Inc., 59 Temple Place - Suite 330,
586 Boston, MA 02111-1307, USA.
588 Also add information on how to contact you by electronic and paper
591 If the program is interactive, make it output a short notice like
592 this when it starts in an interactive mode:
594 Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
595 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
597 This is free software, and you are welcome to redistribute it
598 under certain conditions; type `show c' for details.
600 The hypothetical commands `show w' and `show c' should show the
601 appropriate parts of the General Public License. Of course, the
602 commands you use may be called something other than `show w' and `show
603 c'; they could even be mouse-clicks or menu items--whatever suits your
606 You should also get your employer (if you work as a programmer) or
607 your school, if any, to sign a "copyright disclaimer" for the program,
608 if necessary. Here is a sample; alter the names:
610 Yoyodyne, Inc., hereby disclaims all copyright interest in the program
611 `Gnomovision' (which makes passes at compilers) written by James Hacker.
613 SIGNATURE OF TY COON, 1 April 1989
614 Ty Coon, President of Vice
616 This General Public License does not permit incorporating your
617 program into proprietary programs. If your program is a subroutine
618 library, you may consider it more useful to permit linking proprietary
619 applications with the library. If this is what you want to do, use the
620 GNU Library General Public License instead of this License.
623 File: bison.info, Node: Concepts, Next: Examples, Prev: Copying, Up: Top
625 The Concepts of Bison
626 *********************
628 This chapter introduces many of the basic concepts without which the
629 details of Bison will not make sense. If you do not already know how to
630 use Bison or Yacc, we suggest you start by reading this chapter
635 * Language and Grammar:: Languages and context-free grammars,
636 as mathematical ideas.
637 * Grammar in Bison:: How we represent grammars for Bison's sake.
638 * Semantic Values:: Each token or syntactic grouping can have
639 a semantic value (the value of an integer,
640 the name of an identifier, etc.).
641 * Semantic Actions:: Each rule can have an action containing C code.
642 * Bison Parser:: What are Bison's input and output,
643 how is the output used?
644 * Stages:: Stages in writing and running Bison grammars.
645 * Grammar Layout:: Overall structure of a Bison grammar file.
648 File: bison.info, Node: Language and Grammar, Next: Grammar in Bison, Up: Concepts
650 Languages and Context-Free Grammars
651 ===================================
653 In order for Bison to parse a language, it must be described by a
654 "context-free grammar". This means that you specify one or more
655 "syntactic groupings" and give rules for constructing them from their
656 parts. For example, in the C language, one kind of grouping is called
657 an `expression'. One rule for making an expression might be, "An
658 expression can be made of a minus sign and another expression".
659 Another would be, "An expression can be an integer". As you can see,
660 rules are often recursive, but there must be at least one rule which
661 leads out of the recursion.
663 The most common formal system for presenting such rules for humans
664 to read is "Backus-Naur Form" or "BNF", which was developed in order to
665 specify the language Algol 60. Any grammar expressed in BNF is a
666 context-free grammar. The input to Bison is essentially
667 machine-readable BNF.
669 Not all context-free languages can be handled by Bison, only those
670 that are LALR(1). In brief, this means that it must be possible to
671 tell how to parse any portion of an input string with just a single
672 token of look-ahead. Strictly speaking, that is a description of an
673 LR(1) grammar, and LALR(1) involves additional restrictions that are
674 hard to explain simply; but it is rare in actual practice to find an
675 LR(1) grammar that fails to be LALR(1). *Note Mysterious Reduce/Reduce
676 Conflicts: Mystery Conflicts, for more information on this.
678 In the formal grammatical rules for a language, each kind of
679 syntactic unit or grouping is named by a "symbol". Those which are
680 built by grouping smaller constructs according to grammatical rules are
681 called "nonterminal symbols"; those which can't be subdivided are called
682 "terminal symbols" or "token types". We call a piece of input
683 corresponding to a single terminal symbol a "token", and a piece
684 corresponding to a single nonterminal symbol a "grouping".
686 We can use the C language as an example of what symbols, terminal and
687 nonterminal, mean. The tokens of C are identifiers, constants (numeric
688 and string), and the various keywords, arithmetic operators and
689 punctuation marks. So the terminal symbols of a grammar for C include
690 `identifier', `number', `string', plus one symbol for each keyword,
691 operator or punctuation mark: `if', `return', `const', `static', `int',
692 `char', `plus-sign', `open-brace', `close-brace', `comma' and many
693 more. (These tokens can be subdivided into characters, but that is a
694 matter of lexicography, not grammar.)
696 Here is a simple C function subdivided into tokens:
698 int /* keyword `int' */
699 square (x) /* identifier, open-paren, */
700 /* identifier, close-paren */
701 int x; /* keyword `int', identifier, semicolon */
703 return x * x; /* keyword `return', identifier, */
704 /* asterisk, identifier, semicolon */
707 The syntactic groupings of C include the expression, the statement,
708 the declaration, and the function definition. These are represented in
709 the grammar of C by nonterminal symbols `expression', `statement',
710 `declaration' and `function definition'. The full grammar uses dozens
711 of additional language constructs, each with its own nonterminal
712 symbol, in order to express the meanings of these four. The example
713 above is a function definition; it contains one declaration, and one
714 statement. In the statement, each `x' is an expression and so is `x *
717 Each nonterminal symbol must have grammatical rules showing how it
718 is made out of simpler constructs. For example, one kind of C
719 statement is the `return' statement; this would be described with a
720 grammar rule which reads informally as follows:
722 A `statement' can be made of a `return' keyword, an `expression'
725 There would be many other rules for `statement', one for each kind of
728 One nonterminal symbol must be distinguished as the special one which
729 defines a complete utterance in the language. It is called the "start
730 symbol". In a compiler, this means a complete input program. In the C
731 language, the nonterminal symbol `sequence of definitions and
732 declarations' plays this role.
734 For example, `1 + 2' is a valid C expression--a valid part of a C
735 program--but it is not valid as an _entire_ C program. In the
736 context-free grammar of C, this follows from the fact that `expression'
737 is not the start symbol.
739 The Bison parser reads a sequence of tokens as its input, and groups
740 the tokens using the grammar rules. If the input is valid, the end
741 result is that the entire token sequence reduces to a single grouping
742 whose symbol is the grammar's start symbol. If we use a grammar for C,
743 the entire input must be a `sequence of definitions and declarations'.
744 If not, the parser reports a syntax error.
747 File: bison.info, Node: Grammar in Bison, Next: Semantic Values, Prev: Language and Grammar, Up: Concepts
749 From Formal Rules to Bison Input
750 ================================
752 A formal grammar is a mathematical construct. To define the language
753 for Bison, you must write a file expressing the grammar in Bison syntax:
754 a "Bison grammar" file. *Note Bison Grammar Files: Grammar File.
756 A nonterminal symbol in the formal grammar is represented in Bison
757 input as an identifier, like an identifier in C. By convention, it
758 should be in lower case, such as `expr', `stmt' or `declaration'.
760 The Bison representation for a terminal symbol is also called a
761 "token type". Token types as well can be represented as C-like
762 identifiers. By convention, these identifiers should be upper case to
763 distinguish them from nonterminals: for example, `INTEGER',
764 `IDENTIFIER', `IF' or `RETURN'. A terminal symbol that stands for a
765 particular keyword in the language should be named after that keyword
766 converted to upper case. The terminal symbol `error' is reserved for
767 error recovery. *Note Symbols::.
769 A terminal symbol can also be represented as a character literal,
770 just like a C character constant. You should do this whenever a token
771 is just a single character (parenthesis, plus-sign, etc.): use that
772 same character in a literal as the terminal symbol for that token.
774 A third way to represent a terminal symbol is with a C string
775 constant containing several characters. *Note Symbols::, for more
778 The grammar rules also have an expression in Bison syntax. For
779 example, here is the Bison rule for a C `return' statement. The
780 semicolon in quotes is a literal character token, representing part of
781 the C syntax for the statement; the naked semicolon, and the colon, are
782 Bison punctuation used in every rule.
784 stmt: RETURN expr ';'
787 *Note Syntax of Grammar Rules: Rules.
790 File: bison.info, Node: Semantic Values, Next: Semantic Actions, Prev: Grammar in Bison, Up: Concepts
795 A formal grammar selects tokens only by their classifications: for
796 example, if a rule mentions the terminal symbol `integer constant', it
797 means that _any_ integer constant is grammatically valid in that
798 position. The precise value of the constant is irrelevant to how to
799 parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
802 But the precise value is very important for what the input means
803 once it is parsed. A compiler is useless if it fails to distinguish
804 between 4, 1 and 3989 as constants in the program! Therefore, each
805 token in a Bison grammar has both a token type and a "semantic value".
806 *Note Defining Language Semantics: Semantics, for details.
808 The token type is a terminal symbol defined in the grammar, such as
809 `INTEGER', `IDENTIFIER' or `',''. It tells everything you need to know
810 to decide where the token may validly appear and how to group it with
811 other tokens. The grammar rules know nothing about tokens except their
814 The semantic value has all the rest of the information about the
815 meaning of the token, such as the value of an integer, or the name of an
816 identifier. (A token such as `','' which is just punctuation doesn't
817 need to have any semantic value.)
819 For example, an input token might be classified as token type
820 `INTEGER' and have the semantic value 4. Another input token might
821 have the same token type `INTEGER' but value 3989. When a grammar rule
822 says that `INTEGER' is allowed, either of these tokens is acceptable
823 because each is an `INTEGER'. When the parser accepts the token, it
824 keeps track of the token's semantic value.
826 Each grouping can also have a semantic value as well as its
827 nonterminal symbol. For example, in a calculator, an expression
828 typically has a semantic value that is a number. In a compiler for a
829 programming language, an expression typically has a semantic value that
830 is a tree structure describing the meaning of the expression.
833 File: bison.info, Node: Semantic Actions, Next: Bison Parser, Prev: Semantic Values, Up: Concepts
838 In order to be useful, a program must do more than parse input; it
839 must also produce some output based on the input. In a Bison grammar,
840 a grammar rule can have an "action" made up of C statements. Each time
841 the parser recognizes a match for that rule, the action is executed.
844 Most of the time, the purpose of an action is to compute the
845 semantic value of the whole construct from the semantic values of its
846 parts. For example, suppose we have a rule which says an expression
847 can be the sum of two expressions. When the parser recognizes such a
848 sum, each of the subexpressions has a semantic value which describes
849 how it was built up. The action for this rule should create a similar
850 sort of value for the newly recognized larger expression.
852 For example, here is a rule that says an expression can be the sum of
855 expr: expr '+' expr { $$ = $1 + $3; }
858 The action says how to produce the semantic value of the sum expression
859 from the values of the two subexpressions.
862 File: bison.info, Node: Bison Parser, Next: Stages, Prev: Semantic Actions, Up: Concepts
864 Bison Output: the Parser File
865 =============================
867 When you run Bison, you give it a Bison grammar file as input. The
868 output is a C source file that parses the language described by the
869 grammar. This file is called a "Bison parser". Keep in mind that the
870 Bison utility and the Bison parser are two distinct programs: the Bison
871 utility is a program whose output is the Bison parser that becomes part
874 The job of the Bison parser is to group tokens into groupings
875 according to the grammar rules--for example, to build identifiers and
876 operators into expressions. As it does this, it runs the actions for
877 the grammar rules it uses.
879 The tokens come from a function called the "lexical analyzer" that
880 you must supply in some fashion (such as by writing it in C). The
881 Bison parser calls the lexical analyzer each time it wants a new token.
882 It doesn't know what is "inside" the tokens (though their semantic
883 values may reflect this). Typically the lexical analyzer makes the
884 tokens by parsing characters of text, but Bison does not depend on
885 this. *Note The Lexical Analyzer Function `yylex': Lexical.
887 The Bison parser file is C code which defines a function named
888 `yyparse' which implements that grammar. This function does not make a
889 complete C program: you must supply some additional functions. One is
890 the lexical analyzer. Another is an error-reporting function which the
891 parser calls to report an error. In addition, a complete C program must
892 start with a function called `main'; you have to provide this, and
893 arrange for it to call `yyparse' or the parser will never run. *Note
894 Parser C-Language Interface: Interface.
896 Aside from the token type names and the symbols in the actions you
897 write, all variable and function names used in the Bison parser file
898 begin with `yy' or `YY'. This includes interface functions such as the
899 lexical analyzer function `yylex', the error reporting function
900 `yyerror' and the parser function `yyparse' itself. This also includes
901 numerous identifiers used for internal purposes. Therefore, you should
902 avoid using C identifiers starting with `yy' or `YY' in the Bison
903 grammar file except for the ones defined in this manual.
906 File: bison.info, Node: Stages, Next: Grammar Layout, Prev: Bison Parser, Up: Concepts
908 Stages in Using Bison
909 =====================
911 The actual language-design process using Bison, from grammar
912 specification to a working compiler or interpreter, has these parts:
914 1. Formally specify the grammar in a form recognized by Bison (*note
915 Bison Grammar Files: Grammar File.). For each grammatical rule in
916 the language, describe the action that is to be taken when an
917 instance of that rule is recognized. The action is described by a
918 sequence of C statements.
920 2. Write a lexical analyzer to process input and pass tokens to the
921 parser. The lexical analyzer may be written by hand in C (*note
922 The Lexical Analyzer Function `yylex': Lexical.). It could also
923 be produced using Lex, but the use of Lex is not discussed in this
926 3. Write a controlling function that calls the Bison-produced parser.
928 4. Write error-reporting routines.
930 To turn this source code as written into a runnable program, you
931 must follow these steps:
933 1. Run Bison on the grammar to produce the parser.
935 2. Compile the code output by Bison, as well as any other source
938 3. Link the object files to produce the finished product.
941 File: bison.info, Node: Grammar Layout, Prev: Stages, Up: Concepts
943 The Overall Layout of a Bison Grammar
944 =====================================
946 The input file for the Bison utility is a "Bison grammar file". The
947 general form of a Bison grammar file is as follows:
960 The `%%', `%{' and `%}' are punctuation that appears in every Bison
961 grammar file to separate the sections.
963 The C declarations may define types and variables used in the
964 actions. You can also use preprocessor commands to define macros used
965 there, and use `#include' to include header files that do any of these
968 The Bison declarations declare the names of the terminal and
969 nonterminal symbols, and may also describe operator precedence and the
970 data types of semantic values of various symbols.
972 The grammar rules define how to construct each nonterminal symbol
975 The additional C code can contain any C code you want to use. Often
976 the definition of the lexical analyzer `yylex' goes here, plus
977 subroutines called by the actions in the grammar rules. In a simple
978 program, all the rest of the program can go here.
981 File: bison.info, Node: Examples, Next: Grammar File, Prev: Concepts, Up: Top
986 Now we show and explain three sample programs written using Bison: a
987 reverse polish notation calculator, an algebraic (infix) notation
988 calculator, and a multi-function calculator. All three have been tested
989 under BSD Unix 4.3; each produces a usable, though limited, interactive
992 These examples are simple, but Bison grammars for real programming
993 languages are written the same way. You can copy these examples out of
994 the Info file and into a source file to try them.
998 * RPN Calc:: Reverse polish notation calculator;
999 a first example with no operator precedence.
1000 * Infix Calc:: Infix (algebraic) notation calculator.
1001 Operator precedence is introduced.
1002 * Simple Error Recovery:: Continuing after syntax errors.
1003 * Multi-function Calc:: Calculator with memory and trig functions.
1004 It uses multiple data-types for semantic values.
1005 * Exercises:: Ideas for improving the multi-function calculator.
1008 File: bison.info, Node: RPN Calc, Next: Infix Calc, Up: Examples
1010 Reverse Polish Notation Calculator
1011 ==================================
1013 The first example is that of a simple double-precision "reverse
1014 polish notation" calculator (a calculator using postfix operators).
1015 This example provides a good starting point, since operator precedence
1016 is not an issue. The second example will illustrate how operator
1017 precedence is handled.
1019 The source code for this calculator is named `rpcalc.y'. The `.y'
1020 extension is a convention used for Bison input files.
1024 * Decls: Rpcalc Decls. Bison and C declarations for rpcalc.
1025 * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
1026 * Lexer: Rpcalc Lexer. The lexical analyzer.
1027 * Main: Rpcalc Main. The controlling function.
1028 * Error: Rpcalc Error. The error reporting function.
1029 * Gen: Rpcalc Gen. Running Bison on the grammar file.
1030 * Comp: Rpcalc Compile. Run the C compiler on the output code.
1033 File: bison.info, Node: Rpcalc Decls, Next: Rpcalc Rules, Up: RPN Calc
1035 Declarations for `rpcalc'
1036 -------------------------
1038 Here are the C and Bison declarations for the reverse polish notation
1039 calculator. As in C, comments are placed between `/*...*/'.
1041 /* Reverse polish notation calculator. */
1044 #define YYSTYPE double
1050 %% /* Grammar rules and actions follow */
1052 The C declarations section (*note The C Declarations Section: C
1053 Declarations.) contains two preprocessor directives.
1055 The `#define' directive defines the macro `YYSTYPE', thus specifying
1056 the C data type for semantic values of both tokens and groupings (*note
1057 Data Types of Semantic Values: Value Type.). The Bison parser will use
1058 whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
1059 the default. Because we specify `double', each token and each
1060 expression has an associated value, which is a floating point number.
1062 The `#include' directive is used to declare the exponentiation
1065 The second section, Bison declarations, provides information to
1066 Bison about the token types (*note The Bison Declarations Section:
1067 Bison Declarations.). Each terminal symbol that is not a
1068 single-character literal must be declared here. (Single-character
1069 literals normally don't need to be declared.) In this example, all the
1070 arithmetic operators are designated by single-character literals, so the
1071 only terminal symbol that needs to be declared is `NUM', the token type
1072 for numeric constants.