home *** CD-ROM | disk | FTP | other *** search
/ Gold Fish 2 / goldfish_vol2_cd1.bin / gnu / info / bison.info-1 (.txt) < prev    next >
GNU Info File  |  1994-11-17  |  50KB  |  848 lines

  1. This is Info file bison.info, produced by Makeinfo-1.54 from the input
  2. file /home/gd2/gnu/bison/bison.texinfo.
  3.    This file documents the Bison parser generator.
  4.    Copyright (C) 1988, 1989, 1990, 1991, 1992 Free Software Foundation,
  5.    Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8.    Permission is granted to copy and distribute modified versions of
  9. this manual under the conditions for verbatim copying, provided also
  10. that the sections entitled "GNU General Public License" and "Conditions
  11. for Using Bison" are included exactly as in the original, and provided
  12. that the entire resulting derived work is distributed under the terms
  13. of a permission notice identical to this one.
  14.    Permission is granted to copy and distribute translations of this
  15. manual into another language, under the above conditions for modified
  16. versions, except that the sections entitled "GNU General Public
  17. License", "Conditions for Using Bison" and this permission notice may be
  18. included in translations approved by the Free Software Foundation
  19. instead of in the original English.
  20. File: bison.info,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
  21.    This manual documents version 1.20 of Bison.
  22. * Menu:
  23. * Introduction::
  24. * Conditions::
  25. * Copying::           The GNU General Public License says
  26.                         how you can copy and share Bison
  27. Tutorial sections:
  28. * Concepts::          Basic concepts for understanding Bison.
  29. * Examples::          Three simple explained examples of using Bison.
  30. Reference sections:
  31. * Grammar File::      Writing Bison declarations and rules.
  32. * Interface::         C-language interface to the parser function `yyparse'.
  33. * Algorithm::         How the Bison parser works at run-time.
  34. * Error Recovery::    Writing rules for error recovery.
  35. * Context Dependency::  What to do if your language syntax is too
  36.                         messy for Bison to handle straightforwardly.
  37. * Debugging::         Debugging Bison parsers that parse wrong.
  38. * Invocation::        How to run Bison (to produce the parser source file).
  39. * Table of Symbols::  All the keywords of the Bison language are explained.
  40. * Glossary::          Basic concepts are explained.
  41. * Index::             Cross-references to the text.
  42.  -- The Detailed Node Listing --
  43. The Concepts of Bison
  44. * Language and Grammar::  Languages and context-free grammars,
  45.                             as mathematical ideas.
  46. * Grammar in Bison::  How we represent grammars for Bison's sake.
  47. * Semantic Values::   Each token or syntactic grouping can have
  48.                         a semantic value (the value of an integer,
  49.                         the name of an identifier, etc.).
  50. * Semantic Actions::  Each rule can have an action containing C code.
  51. * Bison Parser::      What are Bison's input and output,
  52.                         how is the output used?
  53. * Stages::            Stages in writing and running Bison grammars.
  54. * Grammar Layout::    Overall structure of a Bison grammar file.
  55. Examples
  56. * RPN Calc::          Reverse polish notation calculator;
  57.                         a first example with no operator precedence.
  58. * Infix Calc::        Infix (algebraic) notation calculator.
  59.                         Operator precedence is introduced.
  60. * Simple Error Recovery::  Continuing after syntax errors.
  61. * Multi-function Calc::    Calculator with memory and trig functions.
  62.                         It uses multiple data-types for semantic values.
  63. * Exercises::         Ideas for improving the multi-function calculator.
  64. Reverse Polish Notation Calculator
  65. * Decls: Rpcalc Decls.  Bison and C declarations for rpcalc.
  66. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  67. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  68. * Main: Rpcalc Main.    The controlling function.
  69. * Error: Rpcalc Error.  The error reporting function.
  70. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  71. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  72. Grammar Rules for `rpcalc'
  73. * Rpcalc Input::
  74. * Rpcalc Line::
  75. * Rpcalc Expr::
  76. Multi-Function Calculator: `mfcalc'
  77. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  78. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  79. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  80. Bison Grammar Files
  81. * Grammar Outline::   Overall layout of the grammar file.
  82. * Symbols::           Terminal and nonterminal symbols.
  83. * Rules::             How to write grammar rules.
  84. * Recursion::         Writing recursive rules.
  85. * Semantics::         Semantic values and actions.
  86. * Declarations::      All kinds of Bison declarations are described here.
  87. * Multiple Parsers::  Putting more than one Bison parser in one program.
  88. Outline of a Bison Grammar
  89. * C Declarations::    Syntax and usage of the C declarations section.
  90. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  91. * Grammar Rules::     Syntax and usage of the grammar rules section.
  92. * C Code::            Syntax and usage of the additional C code section.
  93. Defining Language Semantics
  94. * Value Type::        Specifying one data type for all semantic values.
  95. * Multiple Types::    Specifying several alternative data types.
  96. * Actions::           An action is the semantic definition of a grammar rule.
  97. * Action Types::      Specifying data types for actions to operate on.
  98. * Mid-Rule Actions::  Most actions go at the end of a rule.
  99.                       This says when, why and how to use the exceptional
  100.                         action in the middle of a rule.
  101. Bison Declarations
  102. * Token Decl::        Declaring terminal symbols.
  103. * Precedence Decl::   Declaring terminals with precedence and associativity.
  104. * Union Decl::        Declaring the set of all semantic value types.
  105. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  106. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  107. * Start Decl::        Specifying the start symbol.
  108. * Pure Decl::         Requesting a reentrant parser.
  109. * Decl Summary::      Table of all Bison declarations.
  110. Parser C-Language Interface
  111. * Parser Function::   How to call `yyparse' and what it returns.
  112. * Lexical::           You must supply a function `yylex'
  113.                         which reads tokens.
  114. * Error Reporting::   You must supply a function `yyerror'.
  115. * Action Features::   Special features for use in actions.
  116. The Lexical Analyzer Function `yylex'
  117. * Calling Convention::  How `yyparse' calls `yylex'.
  118. * Token Values::      How `yylex' must return the semantic value
  119.                         of the token it has read.
  120. * Token Positions::   How `yylex' must return the text position
  121.                         (line number, etc.) of the token, if the
  122.                          actions want that.
  123. * Pure Calling::      How the calling convention differs
  124.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  125. The Bison Parser Algorithm
  126. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  127. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  128. * Precedence::        Operator precedence works by resolving conflicts.
  129. * Contextual Precedence::  When an operator's precedence depends on context.
  130. * Parser States::     The parser is a finite-state-machine with stack.
  131. * Reduce/Reduce::     When two rules are applicable in the same situation.
  132. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  133. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  134. Operator Precedence
  135. * Why Precedence::    An example showing why precedence is needed.
  136. * Using Precedence::  How to specify precedence in Bison grammars.
  137. * Precedence Examples::  How these features are used in the previous example.
  138. * How Precedence::    How they work.
  139. Handling Context Dependencies
  140. * Semantic Tokens::   Token parsing can depend on the semantic context.
  141. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  142. * Tie-in Recovery::   Lexical tie-ins have implications for how
  143.                         error recovery rules must be written.
  144. Invoking Bison
  145. * Bison Options::     All the options described in detail,
  146.             in alphabetical order by short options.
  147. * Option Cross Key::  Alphabetical list of long options.
  148. * VMS Invocation::    Bison command syntax on VMS.
  149. File: bison.info,  Node: Introduction,  Next: Conditions,  Prev: Top,  Up: Top
  150. Introduction
  151. ************
  152.    "Bison" is a general-purpose parser generator that converts a
  153. grammar description for an LALR(1) context-free grammar into a C
  154. program to parse that grammar.  Once you are proficient with Bison, you
  155. may use it to develop a wide range of language parsers, from those used
  156. in simple desk calculators to complex programming languages.
  157.    Bison is upward compatible with Yacc: all properly-written Yacc
  158. grammars ought to work with Bison with no change.  Anyone familiar with
  159. Yacc should be able to use Bison with little trouble.  You need to be
  160. fluent in C programming in order to use Bison or to understand this
  161. manual.
  162.    We begin with tutorial chapters that explain the basic concepts of
  163. using Bison and show three explained examples, each building on the
  164. last.  If you don't know Bison or Yacc, start by reading these
  165. chapters.  Reference chapters follow which describe specific aspects of
  166. Bison in detail.
  167.    Bison was written primarily by Robert Corbett; Richard Stallman made
  168. it Yacc-compatible.  This edition corresponds to version 1.20 of Bison.
  169. File: bison.info,  Node: Conditions,  Next: Copying,  Prev: Introduction,  Up: Top
  170. Conditions for Using Bison
  171. **************************
  172.    Bison grammars can be used only in programs that are free software.
  173. This is in contrast to what happens with the GNU C compiler and the
  174. other GNU programming tools.
  175.    The reason Bison is special is that the output of the Bison
  176. utility--the Bison parser file--contains a verbatim copy of a sizable
  177. piece of Bison, which is the code for the `yyparse' function.  (The
  178. actions from your grammar are inserted into this function at one point,
  179. but the rest of the function is not changed.)
  180.    As a result, the Bison parser file is covered by the same copying
  181. conditions that cover Bison itself and the rest of the GNU system: any
  182. program containing it has to be distributed under the standard GNU
  183. copying conditions.
  184.    Occasionally people who would like to use Bison to develop
  185. proprietary programs complain about this.
  186.    We don't particularly sympathize with their complaints.  The purpose
  187. of the GNU project is to promote the right to share software and the
  188. practice of sharing software; it is a means of changing society.  The
  189. people who complain are planning to be uncooperative toward the rest of
  190. the world; why should they deserve our help in doing so?
  191.    However, it's possible that a change in these conditions might
  192. encourage computer companies to use and distribute the GNU system.  If
  193. so, then we might decide to change the terms on `yyparse' as a matter
  194. of the strategy of promoting the right to share.  Such a change would be
  195. irrevocable.  Since we stand by the copying permissions we have
  196. announced, we cannot withdraw them once given.
  197.    We mustn't make an irrevocable change hastily.  We have to wait
  198. until there is a complete GNU system and there has been time to learn
  199. how this issue affects its reception.
  200. File: bison.info,  Node: Copying,  Next: Concepts,  Prev: Conditions,  Up: Top
  201. GNU GENERAL PUBLIC LICENSE
  202. **************************
  203.                          Version 2, June 1991
  204.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  205.      675 Mass Ave, Cambridge, MA 02139, USA
  206.      
  207.      Everyone is permitted to copy and distribute verbatim copies
  208.      of this license document, but changing it is not allowed.
  209. Preamble
  210. ========
  211.    The licenses for most software are designed to take away your
  212. freedom to share and change it.  By contrast, the GNU General Public
  213. License is intended to guarantee your freedom to share and change free
  214. software--to make sure the software is free for all its users.  This
  215. General Public License applies to most of the Free Software
  216. Foundation's software and to any other program whose authors commit to
  217. using it.  (Some other Free Software Foundation software is covered by
  218. the GNU Library General Public License instead.)  You can apply it to
  219. your programs, too.
  220.    When we speak of free software, we are referring to freedom, not
  221. price.  Our General Public Licenses are designed to make sure that you
  222. have the freedom to distribute copies of free software (and charge for
  223. this service if you wish), that you receive source code or can get it
  224. if you want it, that you can change the software or use pieces of it in
  225. new free programs; and that you know you can do these things.
  226.    To protect your rights, we need to make restrictions that forbid
  227. anyone to deny you these rights or to ask you to surrender the rights.
  228. These restrictions translate to certain responsibilities for you if you
  229. distribute copies of the software, or if you modify it.
  230.    For example, if you distribute copies of such a program, whether
  231. gratis or for a fee, you must give the recipients all the rights that
  232. you have.  You must make sure that they, too, receive or can get the
  233. source code.  And you must show them these terms so they know their
  234. rights.
  235.    We protect your rights with two steps: (1) copyright the software,
  236. and (2) offer you this license which gives you legal permission to copy,
  237. distribute and/or modify the software.
  238.    Also, for each author's protection and ours, we want to make certain
  239. that everyone understands that there is no warranty for this free
  240. software.  If the software is modified by someone else and passed on, we
  241. want its recipients to know that what they have is not the original, so
  242. that any problems introduced by others will not reflect on the original
  243. authors' reputations.
  244.    Finally, any free program is threatened constantly by software
  245. patents.  We wish to avoid the danger that redistributors of a free
  246. program will individually obtain patent licenses, in effect making the
  247. program proprietary.  To prevent this, we have made it clear that any
  248. patent must be licensed for everyone's free use or not licensed at all.
  249.    The precise terms and conditions for copying, distribution and
  250. modification follow.
  251.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  252.   0. This License applies to any program or other work which contains a
  253.      notice placed by the copyright holder saying it may be distributed
  254.      under the terms of this General Public License.  The "Program",
  255.      below, refers to any such program or work, and a "work based on
  256.      the Program" means either the Program or any derivative work under
  257.      copyright law: that is to say, a work containing the Program or a
  258.      portion of it, either verbatim or with modifications and/or
  259.      translated into another language.  (Hereinafter, translation is
  260.      included without limitation in the term "modification".)  Each
  261.      licensee is addressed as "you".
  262.      Activities other than copying, distribution and modification are
  263.      not covered by this License; they are outside its scope.  The act
  264.      of running the Program is not restricted, and the output from the
  265.      Program is covered only if its contents constitute a work based on
  266.      the Program (independent of having been made by running the
  267.      Program).  Whether that is true depends on what the Program does.
  268.   1. You may copy and distribute verbatim copies of the Program's
  269.      source code as you receive it, in any medium, provided that you
  270.      conspicuously and appropriately publish on each copy an appropriate
  271.      copyright notice and disclaimer of warranty; keep intact all the
  272.      notices that refer to this License and to the absence of any
  273.      warranty; and give any other recipients of the Program a copy of
  274.      this License along with the Program.
  275.      You may charge a fee for the physical act of transferring a copy,
  276.      and you may at your option offer warranty protection in exchange
  277.      for a fee.
  278.   2. You may modify your copy or copies of the Program or any portion
  279.      of it, thus forming a work based on the Program, and copy and
  280.      distribute such modifications or work under the terms of Section 1
  281.      above, provided that you also meet all of these conditions:
  282.        a. You must cause the modified files to carry prominent notices
  283.           stating that you changed the files and the date of any change.
  284.        b. You must cause any work that you distribute or publish, that
  285.           in whole or in part contains or is derived from the Program
  286.           or any part thereof, to be licensed as a whole at no charge
  287.           to all third parties under the terms of this License.
  288.        c. If the modified program normally reads commands interactively
  289.           when run, you must cause it, when started running for such
  290.           interactive use in the most ordinary way, to print or display
  291.           an announcement including an appropriate copyright notice and
  292.           a notice that there is no warranty (or else, saying that you
  293.           provide a warranty) and that users may redistribute the
  294.           program under these conditions, and telling the user how to
  295.           view a copy of this License.  (Exception: if the Program
  296.           itself is interactive but does not normally print such an
  297.           announcement, your work based on the Program is not required
  298.           to print an announcement.)
  299.      These requirements apply to the modified work as a whole.  If
  300.      identifiable sections of that work are not derived from the
  301.      Program, and can be reasonably considered independent and separate
  302.      works in themselves, then this License, and its terms, do not
  303.      apply to those sections when you distribute them as separate
  304.      works.  But when you distribute the same sections as part of a
  305.      whole which is a work based on the Program, the distribution of
  306.      the whole must be on the terms of this License, whose permissions
  307.      for other licensees extend to the entire whole, and thus to each
  308.      and every part regardless of who wrote it.
  309.      Thus, it is not the intent of this section to claim rights or
  310.      contest your rights to work written entirely by you; rather, the
  311.      intent is to exercise the right to control the distribution of
  312.      derivative or collective works based on the Program.
  313.      In addition, mere aggregation of another work not based on the
  314.      Program with the Program (or with a work based on the Program) on
  315.      a volume of a storage or distribution medium does not bring the
  316.      other work under the scope of this License.
  317.   3. You may copy and distribute the Program (or a work based on it,
  318.      under Section 2) in object code or executable form under the terms
  319.      of Sections 1 and 2 above provided that you also do one of the
  320.      following:
  321.        a. Accompany it with the complete corresponding machine-readable
  322.           source code, which must be distributed under the terms of
  323.           Sections 1 and 2 above on a medium customarily used for
  324.           software interchange; or,
  325.        b. Accompany it with a written offer, valid for at least three
  326.           years, to give any third party, for a charge no more than your
  327.           cost of physically performing source distribution, a complete
  328.           machine-readable copy of the corresponding source code, to be
  329.           distributed under the terms of Sections 1 and 2 above on a
  330.           medium customarily used for software interchange; or,
  331.        c. Accompany it with the information you received as to the offer
  332.           to distribute corresponding source code.  (This alternative is
  333.           allowed only for noncommercial distribution and only if you
  334.           received the program in object code or executable form with
  335.           such an offer, in accord with Subsection b above.)
  336.      The source code for a work means the preferred form of the work for
  337.      making modifications to it.  For an executable work, complete
  338.      source code means all the source code for all modules it contains,
  339.      plus any associated interface definition files, plus the scripts
  340.      used to control compilation and installation of the executable.
  341.      However, as a special exception, the source code distributed need
  342.      not include anything that is normally distributed (in either
  343.      source or binary form) with the major components (compiler,
  344.      kernel, and so on) of the operating system on which the executable
  345.      runs, unless that component itself accompanies the executable.
  346.      If distribution of executable or object code is made by offering
  347.      access to copy from a designated place, then offering equivalent
  348.      access to copy the source code from the same place counts as
  349.      distribution of the source code, even though third parties are not
  350.      compelled to copy the source along with the object code.
  351.   4. You may not copy, modify, sublicense, or distribute the Program
  352.      except as expressly provided under this License.  Any attempt
  353.      otherwise to copy, modify, sublicense or distribute the Program is
  354.      void, and will automatically terminate your rights under this
  355.      License.  However, parties who have received copies, or rights,
  356.      from you under this License will not have their licenses
  357.      terminated so long as such parties remain in full compliance.
  358.   5. You are not required to accept this License, since you have not
  359.      signed it.  However, nothing else grants you permission to modify
  360.      or distribute the Program or its derivative works.  These actions
  361.      are prohibited by law if you do not accept this License.
  362.      Therefore, by modifying or distributing the Program (or any work
  363.      based on the Program), you indicate your acceptance of this
  364.      License to do so, and all its terms and conditions for copying,
  365.      distributing or modifying the Program or works based on it.
  366.   6. Each time you redistribute the Program (or any work based on the
  367.      Program), the recipient automatically receives a license from the
  368.      original licensor to copy, distribute or modify the Program
  369.      subject to these terms and conditions.  You may not impose any
  370.      further restrictions on the recipients' exercise of the rights
  371.      granted herein.  You are not responsible for enforcing compliance
  372.      by third parties to this License.
  373.   7. If, as a consequence of a court judgment or allegation of patent
  374.      infringement or for any other reason (not limited to patent
  375.      issues), conditions are imposed on you (whether by court order,
  376.      agreement or otherwise) that contradict the conditions of this
  377.      License, they do not excuse you from the conditions of this
  378.      License.  If you cannot distribute so as to satisfy simultaneously
  379.      your obligations under this License and any other pertinent
  380.      obligations, then as a consequence you may not distribute the
  381.      Program at all.  For example, if a patent license would not permit
  382.      royalty-free redistribution of the Program by all those who
  383.      receive copies directly or indirectly through you, then the only
  384.      way you could satisfy both it and this License would be to refrain
  385.      entirely from distribution of the Program.
  386.      If any portion of this section is held invalid or unenforceable
  387.      under any particular circumstance, the balance of the section is
  388.      intended to apply and the section as a whole is intended to apply
  389.      in other circumstances.
  390.      It is not the purpose of this section to induce you to infringe any
  391.      patents or other property right claims or to contest validity of
  392.      any such claims; this section has the sole purpose of protecting
  393.      the integrity of the free software distribution system, which is
  394.      implemented by public license practices.  Many people have made
  395.      generous contributions to the wide range of software distributed
  396.      through that system in reliance on consistent application of that
  397.      system; it is up to the author/donor to decide if he or she is
  398.      willing to distribute software through any other system and a
  399.      licensee cannot impose that choice.
  400.      This section is intended to make thoroughly clear what is believed
  401.      to be a consequence of the rest of this License.
  402.   8. If the distribution and/or use of the Program is restricted in
  403.      certain countries either by patents or by copyrighted interfaces,
  404.      the original copyright holder who places the Program under this
  405.      License may add an explicit geographical distribution limitation
  406.      excluding those countries, so that distribution is permitted only
  407.      in or among countries not thus excluded.  In such case, this
  408.      License incorporates the limitation as if written in the body of
  409.      this License.
  410.   9. The Free Software Foundation may publish revised and/or new
  411.      versions of the General Public License from time to time.  Such
  412.      new versions will be similar in spirit to the present version, but
  413.      may differ in detail to address new problems or concerns.
  414.      Each version is given a distinguishing version number.  If the
  415.      Program specifies a version number of this License which applies
  416.      to it and "any later version", you have the option of following
  417.      the terms and conditions either of that version or of any later
  418.      version published by the Free Software Foundation.  If the Program
  419.      does not specify a version number of this License, you may choose
  420.      any version ever published by the Free Software Foundation.
  421.  10. If you wish to incorporate parts of the Program into other free
  422.      programs whose distribution conditions are different, write to the
  423.      author to ask for permission.  For software which is copyrighted
  424.      by the Free Software Foundation, write to the Free Software
  425.      Foundation; we sometimes make exceptions for this.  Our decision
  426.      will be guided by the two goals of preserving the free status of
  427.      all derivatives of our free software and of promoting the sharing
  428.      and reuse of software generally.
  429.                                 NO WARRANTY
  430.  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  431.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  432.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  433.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  434.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  435.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  436.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  437.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  438.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  439.      SERVICING, REPAIR OR CORRECTION.
  440.  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  441.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  442.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  443.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  444.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  445.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  446.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  447.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  448.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  449.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  450.                       END OF TERMS AND CONDITIONS
  451. How to Apply These Terms to Your New Programs
  452. =============================================
  453.    If you develop a new program, and you want it to be of the greatest
  454. possible use to the public, the best way to achieve this is to make it
  455. free software which everyone can redistribute and change under these
  456. terms.
  457.    To do so, attach the following notices to the program.  It is safest
  458. to attach them to the start of each source file to most effectively
  459. convey the exclusion of warranty; and each file should have at least
  460. the "copyright" line and a pointer to where the full notice is found.
  461.      ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  462.      Copyright (C) 19YY  NAME OF AUTHOR
  463.      
  464.      This program is free software; you can redistribute it and/or modify
  465.      it under the terms of the GNU General Public License as published by
  466.      the Free Software Foundation; either version 2 of the License, or
  467.      (at your option) any later version.
  468.      
  469.      This program is distributed in the hope that it will be useful,
  470.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  471.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  472.      GNU General Public License for more details.
  473.      
  474.      You should have received a copy of the GNU General Public License
  475.      along with this program; if not, write to the Free Software
  476.      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  477.    Also add information on how to contact you by electronic and paper
  478. mail.
  479.    If the program is interactive, make it output a short notice like
  480. this when it starts in an interactive mode:
  481.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  482.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  483.      type `show w'.
  484.      This is free software, and you are welcome to redistribute it
  485.      under certain conditions; type `show c' for details.
  486.    The hypothetical commands `show w' and `show c' should show the
  487. appropriate parts of the General Public License.  Of course, the
  488. commands you use may be called something other than `show w' and `show
  489. c'; they could even be mouse-clicks or menu items--whatever suits your
  490. program.
  491.    You should also get your employer (if you work as a programmer) or
  492. your school, if any, to sign a "copyright disclaimer" for the program,
  493. if necessary.  Here is a sample; alter the names:
  494.      Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  495.      `Gnomovision' (which makes passes at compilers) written by James Hacker.
  496.      
  497.      SIGNATURE OF TY COON, 1 April 1989
  498.      Ty Coon, President of Vice
  499.    This General Public License does not permit incorporating your
  500. program into proprietary programs.  If your program is a subroutine
  501. library, you may consider it more useful to permit linking proprietary
  502. applications with the library.  If this is what you want to do, use the
  503. GNU Library General Public License instead of this License.
  504. File: bison.info,  Node: Concepts,  Next: Examples,  Prev: Copying,  Up: Top
  505. The Concepts of Bison
  506. *********************
  507.    This chapter introduces many of the basic concepts without which the
  508. details of Bison will not make sense.  If you do not already know how to
  509. use Bison or Yacc, we suggest you start by reading this chapter
  510. carefully.
  511. * Menu:
  512. * Language and Grammar::  Languages and context-free grammars,
  513.                             as mathematical ideas.
  514. * Grammar in Bison::  How we represent grammars for Bison's sake.
  515. * Semantic Values::   Each token or syntactic grouping can have
  516.                         a semantic value (the value of an integer,
  517.                         the name of an identifier, etc.).
  518. * Semantic Actions::  Each rule can have an action containing C code.
  519. * Bison Parser::      What are Bison's input and output,
  520.                         how is the output used?
  521. * Stages::            Stages in writing and running Bison grammars.
  522. * Grammar Layout::    Overall structure of a Bison grammar file.
  523. File: bison.info,  Node: Language and Grammar,  Next: Grammar in Bison,  Up: Concepts
  524. Languages and Context-Free Grammars
  525. ===================================
  526.    In order for Bison to parse a language, it must be described by a
  527. "context-free grammar".  This means that you specify one or more
  528. "syntactic groupings" and give rules for constructing them from their
  529. parts.  For example, in the C language, one kind of grouping is called
  530. an `expression'.  One rule for making an expression might be, "An
  531. expression can be made of a minus sign and another expression".
  532. Another would be, "An expression can be an integer".  As you can see,
  533. rules are often recursive, but there must be at least one rule which
  534. leads out of the recursion.
  535.    The most common formal system for presenting such rules for humans
  536. to read is "Backus-Naur Form" or "BNF", which was developed in order to
  537. specify the language Algol 60.  Any grammar expressed in BNF is a
  538. context-free grammar.  The input to Bison is essentially
  539. machine-readable BNF.
  540.    Not all context-free languages can be handled by Bison, only those
  541. that are LALR(1).  In brief, this means that it must be possible to
  542. tell how to parse any portion of an input string with just a single
  543. token of look-ahead.  Strictly speaking, that is a description of an
  544. LR(1) grammar, and LALR(1) involves additional restrictions that are
  545. hard to explain simply; but it is rare in actual practice to find an
  546. LR(1) grammar that fails to be LALR(1).  *Note Mysterious Reduce/Reduce
  547. Conflicts: Mystery Conflicts, for more information on this.
  548.    In the formal grammatical rules for a language, each kind of
  549. syntactic unit or grouping is named by a "symbol".  Those which are
  550. built by grouping smaller constructs according to grammatical rules are
  551. called "nonterminal symbols"; those which can't be subdivided are called
  552. "terminal symbols" or "token types".  We call a piece of input
  553. corresponding to a single terminal symbol a "token", and a piece
  554. corresponding to a single nonterminal symbol a "grouping".
  555.    We can use the C language as an example of what symbols, terminal and
  556. nonterminal, mean.  The tokens of C are identifiers, constants (numeric
  557. and string), and the various keywords, arithmetic operators and
  558. punctuation marks.  So the terminal symbols of a grammar for C include
  559. `identifier', `number', `string', plus one symbol for each keyword,
  560. operator or punctuation mark: `if', `return', `const', `static', `int',
  561. `char', `plus-sign', `open-brace', `close-brace', `comma' and many
  562. more.  (These tokens can be subdivided into characters, but that is a
  563. matter of lexicography, not grammar.)
  564.    Here is a simple C function subdivided into tokens:
  565.      int             /* keyword `int' */
  566.      square (x)      /* identifier, open-paren, */
  567.                      /* identifier, close-paren */
  568.           int x;     /* keyword `int', identifier, semicolon */
  569.      {               /* open-brace */
  570.        return x * x; /* keyword `return', identifier, */
  571.                      /* asterisk, identifier, semicolon */
  572.      }               /* close-brace */
  573.    The syntactic groupings of C include the expression, the statement,
  574. the declaration, and the function definition.  These are represented in
  575. the grammar of C by nonterminal symbols `expression', `statement',
  576. `declaration' and `function definition'.  The full grammar uses dozens
  577. of additional language constructs, each with its own nonterminal
  578. symbol, in order to express the meanings of these four.  The example
  579. above is a function definition; it contains one declaration, and one
  580. statement.  In the statement, each `x' is an expression and so is `x *
  581.    Each nonterminal symbol must have grammatical rules showing how it
  582. is made out of simpler constructs.  For example, one kind of C
  583. statement is the `return' statement; this would be described with a
  584. grammar rule which reads informally as follows:
  585.      A `statement' can be made of a `return' keyword, an `expression'
  586.      and a `semicolon'.
  587. There would be many other rules for `statement', one for each kind of
  588. statement in C.
  589.    One nonterminal symbol must be distinguished as the special one which
  590. defines a complete utterance in the language.  It is called the "start
  591. symbol".  In a compiler, this means a complete input program.  In the C
  592. language, the nonterminal symbol `sequence of definitions and
  593. declarations' plays this role.
  594.    For example, `1 + 2' is a valid C expression--a valid part of a C
  595. program--but it is not valid as an *entire* C program.  In the
  596. context-free grammar of C, this follows from the fact that `expression'
  597. is not the start symbol.
  598.    The Bison parser reads a sequence of tokens as its input, and groups
  599. the tokens using the grammar rules.  If the input is valid, the end
  600. result is that the entire token sequence reduces to a single grouping
  601. whose symbol is the grammar's start symbol.  If we use a grammar for C,
  602. the entire input must be a `sequence of definitions and declarations'.
  603. If not, the parser reports a syntax error.
  604. File: bison.info,  Node: Grammar in Bison,  Next: Semantic Values,  Prev: Language and Grammar,  Up: Concepts
  605. From Formal Rules to Bison Input
  606. ================================
  607.    A formal grammar is a mathematical construct.  To define the language
  608. for Bison, you must write a file expressing the grammar in Bison syntax:
  609. a "Bison grammar" file.  *Note Bison Grammar Files: Grammar File.
  610.    A nonterminal symbol in the formal grammar is represented in Bison
  611. input as an identifier, like an identifier in C.  By convention, it
  612. should be in lower case, such as `expr', `stmt' or `declaration'.
  613.    The Bison representation for a terminal symbol is also called a
  614. "token type".  Token types as well can be represented as C-like
  615. identifiers.  By convention, these identifiers should be upper case to
  616. distinguish them from nonterminals: for example, `INTEGER',
  617. `IDENTIFIER', `IF' or `RETURN'.  A terminal symbol that stands for a
  618. particular keyword in the language should be named after that keyword
  619. converted to upper case.  The terminal symbol `error' is reserved for
  620. error recovery.  *Note Symbols::.
  621.    A terminal symbol can also be represented as a character literal,
  622. just like a C character constant.  You should do this whenever a token
  623. is just a single character (parenthesis, plus-sign, etc.): use that
  624. same character in a literal as the terminal symbol for that token.
  625.    The grammar rules also have an expression in Bison syntax.  For
  626. example, here is the Bison rule for a C `return' statement.  The
  627. semicolon in quotes is a literal character token, representing part of
  628. the C syntax for the statement; the naked semicolon, and the colon, are
  629. Bison punctuation used in every rule.
  630.      stmt:   RETURN expr ';'
  631.              ;
  632. *Note Syntax of Grammar Rules: Rules.
  633. File: bison.info,  Node: Semantic Values,  Next: Semantic Actions,  Prev: Grammar in Bison,  Up: Concepts
  634. Semantic Values
  635. ===============
  636.    A formal grammar selects tokens only by their classifications: for
  637. example, if a rule mentions the terminal symbol `integer constant', it
  638. means that *any* integer constant is grammatically valid in that
  639. position.  The precise value of the constant is irrelevant to how to
  640. parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
  641. equally grammatical.
  642.    But the precise value is very important for what the input means
  643. once it is parsed.  A compiler is useless if it fails to distinguish
  644. between 4, 1 and 3989 as constants in the program!  Therefore, each
  645. token in a Bison grammar has both a token type and a "semantic value".
  646. *Note Defining Language Semantics: Semantics, for details.
  647.    The token type is a terminal symbol defined in the grammar, such as
  648. `INTEGER', `IDENTIFIER' or `',''.  It tells everything you need to know
  649. to decide where the token may validly appear and how to group it with
  650. other tokens.  The grammar rules know nothing about tokens except their
  651. types.
  652.    The semantic value has all the rest of the information about the
  653. meaning of the token, such as the value of an integer, or the name of an
  654. identifier.  (A token such as `','' which is just punctuation doesn't
  655. need to have any semantic value.)
  656.    For example, an input token might be classified as token type
  657. `INTEGER' and have the semantic value 4.  Another input token might
  658. have the same token type `INTEGER' but value 3989.  When a grammar rule
  659. says that `INTEGER' is allowed, either of these tokens is acceptable
  660. because each is an `INTEGER'.  When the parser accepts the token, it
  661. keeps track of the token's semantic value.
  662.    Each grouping can also have a semantic value as well as its
  663. nonterminal symbol.  For example, in a calculator, an expression
  664. typically has a semantic value that is a number.  In a compiler for a
  665. programming language, an expression typically has a semantic value that
  666. is a tree structure describing the meaning of the expression.
  667. File: bison.info,  Node: Semantic Actions,  Next: Bison Parser,  Prev: Semantic Values,  Up: Concepts
  668. Semantic Actions
  669. ================
  670.    In order to be useful, a program must do more than parse input; it
  671. must also produce some output based on the input.  In a Bison grammar,
  672. a grammar rule can have an "action" made up of C statements.  Each time
  673. the parser recognizes a match for that rule, the action is executed.
  674. *Note Actions::.
  675.    Most of the time, the purpose of an action is to compute the
  676. semantic value of the whole construct from the semantic values of its
  677. parts.  For example, suppose we have a rule which says an expression
  678. can be the sum of two expressions.  When the parser recognizes such a
  679. sum, each of the subexpressions has a semantic value which describes
  680. how it was built up.  The action for this rule should create a similar
  681. sort of value for the newly recognized larger expression.
  682.    For example, here is a rule that says an expression can be the sum of
  683. two subexpressions:
  684.      expr: expr '+' expr   { $$ = $1 + $3; }
  685.              ;
  686. The action says how to produce the semantic value of the sum expression
  687. from the values of the two subexpressions.
  688. File: bison.info,  Node: Bison Parser,  Next: Stages,  Prev: Semantic Actions,  Up: Concepts
  689. Bison Output: the Parser File
  690. =============================
  691.    When you run Bison, you give it a Bison grammar file as input.  The
  692. output is a C source file that parses the language described by the
  693. grammar.  This file is called a "Bison parser".  Keep in mind that the
  694. Bison utility and the Bison parser are two distinct programs: the Bison
  695. utility is a program whose output is the Bison parser that becomes part
  696. of your program.
  697.    The job of the Bison parser is to group tokens into groupings
  698. according to the grammar rules--for example, to build identifiers and
  699. operators into expressions.  As it does this, it runs the actions for
  700. the grammar rules it uses.
  701.    The tokens come from a function called the "lexical analyzer" that
  702. you must supply in some fashion (such as by writing it in C).  The
  703. Bison parser calls the lexical analyzer each time it wants a new token.
  704. It doesn't know what is "inside" the tokens (though their semantic
  705. values may reflect this).  Typically the lexical analyzer makes the
  706. tokens by parsing characters of text, but Bison does not depend on
  707. this.  *Note The Lexical Analyzer Function `yylex': Lexical.
  708.    The Bison parser file is C code which defines a function named
  709. `yyparse' which implements that grammar.  This function does not make a
  710. complete C program: you must supply some additional functions.  One is
  711. the lexical analyzer.  Another is an error-reporting function which the
  712. parser calls to report an error.  In addition, a complete C program must
  713. start with a function called `main'; you have to provide this, and
  714. arrange for it to call `yyparse' or the parser will never run.  *Note
  715. Parser C-Language Interface: Interface.
  716.    Aside from the token type names and the symbols in the actions you
  717. write, all variable and function names used in the Bison parser file
  718. begin with `yy' or `YY'.  This includes interface functions such as the
  719. lexical analyzer function `yylex', the error reporting function
  720. `yyerror' and the parser function `yyparse' itself.  This also includes
  721. numerous identifiers used for internal purposes.  Therefore, you should
  722. avoid using C identifiers starting with `yy' or `YY' in the Bison
  723. grammar file except for the ones defined in this manual.
  724. File: bison.info,  Node: Stages,  Next: Grammar Layout,  Prev: Bison Parser,  Up: Concepts
  725. Stages in Using Bison
  726. =====================
  727.    The actual language-design process using Bison, from grammar
  728. specification to a working compiler or interpreter, has these parts:
  729.   1. Formally specify the grammar in a form recognized by Bison (*note
  730.      Bison Grammar Files: Grammar File.).  For each grammatical rule in
  731.      the language, describe the action that is to be taken when an
  732.      instance of that rule is recognized.  The action is described by a
  733.      sequence of C statements.
  734.   2. Write a lexical analyzer to process input and pass tokens to the
  735.      parser.  The lexical analyzer may be written by hand in C (*note
  736.      The Lexical Analyzer Function `yylex': Lexical.).  It could also
  737.      be produced using Lex, but the use of Lex is not discussed in this
  738.      manual.
  739.   3. Write a controlling function that calls the Bison-produced parser.
  740.   4. Write error-reporting routines.
  741.    To turn this source code as written into a runnable program, you
  742. must follow these steps:
  743.   1. Run Bison on the grammar to produce the parser.
  744.   2. Compile the code output by Bison, as well as any other source
  745.      files.
  746.   3. Link the object files to produce the finished product.
  747. File: bison.info,  Node: Grammar Layout,  Prev: Stages,  Up: Concepts
  748. The Overall Layout of a Bison Grammar
  749. =====================================
  750.    The input file for the Bison utility is a "Bison grammar file".  The
  751. general form of a Bison grammar file is as follows:
  752.      %{
  753.      C DECLARATIONS
  754.      %}
  755.      
  756.      BISON DECLARATIONS
  757.      
  758.      %%
  759.      GRAMMAR RULES
  760.      %%
  761.      ADDITIONAL C CODE
  762. The `%%', `%{' and `%}' are punctuation that appears in every Bison
  763. grammar file to separate the sections.
  764.    The C declarations may define types and variables used in the
  765. actions.  You can also use preprocessor commands to define macros used
  766. there, and use `#include' to include header files that do any of these
  767. things.
  768.    The Bison declarations declare the names of the terminal and
  769. nonterminal symbols, and may also describe operator precedence and the
  770. data types of semantic values of various symbols.
  771.    The grammar rules define how to construct each nonterminal symbol
  772. from its parts.
  773.    The additional C code can contain any C code you want to use.  Often
  774. the definition of the lexical analyzer `yylex' goes here, plus
  775. subroutines called by the actions in the grammar rules.  In a simple
  776. program, all the rest of the program can go here.
  777. File: bison.info,  Node: Examples,  Next: Grammar File,  Prev: Concepts,  Up: Top
  778. Examples
  779. ********
  780.    Now we show and explain three sample programs written using Bison: a
  781. reverse polish notation calculator, an algebraic (infix) notation
  782. calculator, and a multi-function calculator.  All three have been tested
  783. under BSD Unix 4.3; each produces a usable, though limited, interactive
  784. desk-top calculator.
  785.    These examples are simple, but Bison grammars for real programming
  786. languages are written the same way.  You can copy these examples out of
  787. the Info file and into a source file to try them.
  788. * Menu:
  789. * RPN Calc::          Reverse polish notation calculator;
  790.                         a first example with no operator precedence.
  791. * Infix Calc::        Infix (algebraic) notation calculator.
  792.                         Operator precedence is introduced.
  793. * Simple Error Recovery::  Continuing after syntax errors.
  794. * Multi-function Calc::  Calculator with memory and trig functions.
  795.                            It uses multiple data-types for semantic values.
  796. * Exercises::         Ideas for improving the multi-function calculator.
  797. File: bison.info,  Node: RPN Calc,  Next: Infix Calc,  Up: Examples
  798. Reverse Polish Notation Calculator
  799. ==================================
  800.    The first example is that of a simple double-precision "reverse
  801. polish notation" calculator (a calculator using postfix operators).
  802. This example provides a good starting point, since operator precedence
  803. is not an issue.  The second example will illustrate how operator
  804. precedence is handled.
  805.    The source code for this calculator is named `rpcalc.y'.  The `.y'
  806. extension is a convention used for Bison input files.
  807. * Menu:
  808. * Decls: Rpcalc Decls.  Bison and C declarations for rpcalc.
  809. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  810. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  811. * Main: Rpcalc Main.    The controlling function.
  812. * Error: Rpcalc Error.  The error reporting function.
  813. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  814. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  815. File: bison.info,  Node: Rpcalc Decls,  Next: Rpcalc Rules,  Up: RPN Calc
  816. Declarations for `rpcalc'
  817. -------------------------
  818.    Here are the C and Bison declarations for the reverse polish notation
  819. calculator.  As in C, comments are placed between `/*...*/'.
  820.      /* Reverse polish notation calculator. */
  821.      
  822.      %{
  823.      #define YYSTYPE double
  824.      #include <math.h>
  825.      %}
  826.      
  827.      %token NUM
  828.      
  829.      %% /* Grammar rules and actions follow */
  830.    The C declarations section (*note The C Declarations Section: C
  831. Declarations.) contains two preprocessor directives.
  832.    The `#define' directive defines the macro `YYSTYPE', thus specifying
  833. the C data type for semantic values of both tokens and groupings (*note
  834. Data Types of Semantic Values: Value Type.).  The Bison parser will use
  835. whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
  836. the default.  Because we specify `double', each token and each
  837. expression has an associated value, which is a floating point number.
  838.    The `#include' directive is used to declare the exponentiation
  839. function `pow'.
  840.    The second section, Bison declarations, provides information to
  841. Bison about the token types (*note The Bison Declarations Section:
  842. Bison Declarations.).  Each terminal symbol that is not a
  843. single-character literal must be declared here.  (Single-character
  844. literals normally don't need to be declared.)  In this example, all the
  845. arithmetic operators are designated by single-character literals, so the
  846. only terminal symbol that needs to be declared is `NUM', the token type
  847. for numeric constants.
  848.