home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / bison-1.25-bin.lha / info / bison.info-1 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  50KB  |  847 lines

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