home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / gnu / djgpp / docs / bison / bison.inf next >
Encoding:
GNU Info File  |  1993-11-13  |  198.7 KB  |  4,962 lines

  1. This is Info file bison.info, produced by Makeinfo-1.55 from the input
  2. file bison.tex.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 1989, 1990, 1991, 1992 Free Software Foundation,
  7. Inc.
  8.  
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.  
  13.    Permission is granted to copy and distribute modified versions of
  14. this manual under the conditions for verbatim copying, provided also
  15. that the sections entitled "GNU General Public License" and "Conditions
  16. for Using Bison" are included exactly as in the original, and provided
  17. that the entire resulting derived work is distributed under the terms
  18. of a permission notice identical to this one.
  19.  
  20.    Permission is granted to copy and distribute translations of this
  21. manual into another language, under the above conditions for modified
  22. versions, except that the sections entitled "GNU General Public
  23. License", "Conditions for Using Bison" and this permission notice may be
  24. included in translations approved by the Free Software Foundation
  25. instead of in the original English.
  26.  
  27. 
  28. File: bison,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
  29.  
  30.    This manual documents version 1.20 of Bison.
  31.  
  32. * Menu:
  33.  
  34. * Introduction::
  35. * Conditions::
  36. * Copying::           The GNU General Public License says
  37.                         how you can copy and share Bison
  38.  
  39. Tutorial sections:
  40. * Concepts::          Basic concepts for understanding Bison.
  41. * Examples::          Three simple explained examples of using Bison.
  42.  
  43. Reference sections:
  44. * Grammar File::      Writing Bison declarations and rules.
  45. * Interface::         C-language interface to the parser function `yyparse'.
  46. * Algorithm::         How the Bison parser works at run-time.
  47. * Error Recovery::    Writing rules for error recovery.
  48. * Context Dependency::  What to do if your language syntax is too
  49.                         messy for Bison to handle straightforwardly.
  50. * Debugging::         Debugging Bison parsers that parse wrong.
  51. * Invocation::        How to run Bison (to produce the parser source file).
  52. * Table of Symbols::  All the keywords of the Bison language are explained.
  53. * Glossary::          Basic concepts are explained.
  54. * Index::             Cross-references to the text.
  55.  
  56.  -- The Detailed Node Listing --
  57.  
  58. The Concepts of Bison
  59.  
  60. * Language and Grammar::  Languages and context-free grammars,
  61.                             as mathematical ideas.
  62. * Grammar in Bison::  How we represent grammars for Bison's sake.
  63. * Semantic Values::   Each token or syntactic grouping can have
  64.                         a semantic value (the value of an integer,
  65.                         the name of an identifier, etc.).
  66. * Semantic Actions::  Each rule can have an action containing C code.
  67. * Bison Parser::      What are Bison's input and output,
  68.                         how is the output used?
  69. * Stages::            Stages in writing and running Bison grammars.
  70. * Grammar Layout::    Overall structure of a Bison grammar file.
  71.  
  72. Examples
  73.  
  74. * RPN Calc::          Reverse polish notation calculator;
  75.                         a first example with no operator precedence.
  76. * Infix Calc::        Infix (algebraic) notation calculator.
  77.                         Operator precedence is introduced.
  78. * Simple Error Recovery::  Continuing after syntax errors.
  79. * Multi-function Calc::    Calculator with memory and trig functions.
  80.                         It uses multiple data-types for semantic values.
  81. * Exercises::         Ideas for improving the multi-function calculator.
  82.  
  83. Reverse Polish Notation Calculator
  84.  
  85. * Decls: Rpcalc Decls.  Bison and C declarations for rpcalc.
  86. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  87. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  88. * Main: Rpcalc Main.    The controlling function.
  89. * Error: Rpcalc Error.  The error reporting function.
  90. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  91. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  92.  
  93. Grammar Rules for `rpcalc'
  94.  
  95. * Rpcalc Input::
  96. * Rpcalc Line::
  97. * Rpcalc Expr::
  98.  
  99. Multi-Function Calculator: `mfcalc'
  100.  
  101. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  102. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  103. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  104.  
  105. Bison Grammar Files
  106.  
  107. * Grammar Outline::   Overall layout of the grammar file.
  108. * Symbols::           Terminal and nonterminal symbols.
  109. * Rules::             How to write grammar rules.
  110. * Recursion::         Writing recursive rules.
  111. * Semantics::         Semantic values and actions.
  112. * Declarations::      All kinds of Bison declarations are described here.
  113. * Multiple Parsers::  Putting more than one Bison parser in one program.
  114.  
  115. Outline of a Bison Grammar
  116.  
  117. * C Declarations::    Syntax and usage of the C declarations section.
  118. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  119. * Grammar Rules::     Syntax and usage of the grammar rules section.
  120. * C Code::            Syntax and usage of the additional C code section.
  121.  
  122. Defining Language Semantics
  123.  
  124. * Value Type::        Specifying one data type for all semantic values.
  125. * Multiple Types::    Specifying several alternative data types.
  126. * Actions::           An action is the semantic definition of a grammar rule.
  127. * Action Types::      Specifying data types for actions to operate on.
  128. * Mid-Rule Actions::  Most actions go at the end of a rule.
  129.                       This says when, why and how to use the exceptional
  130.                         action in the middle of a rule.
  131.  
  132. Bison Declarations
  133.  
  134. * Token Decl::        Declaring terminal symbols.
  135. * Precedence Decl::   Declaring terminals with precedence and associativity.
  136. * Union Decl::        Declaring the set of all semantic value types.
  137. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  138. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  139. * Start Decl::        Specifying the start symbol.
  140. * Pure Decl::         Requesting a reentrant parser.
  141. * Decl Summary::      Table of all Bison declarations.
  142.  
  143. Parser C-Language Interface
  144.  
  145. * Parser Function::   How to call `yyparse' and what it returns.
  146. * Lexical::           You must supply a function `yylex'
  147.                         which reads tokens.
  148. * Error Reporting::   You must supply a function `yyerror'.
  149. * Action Features::   Special features for use in actions.
  150.  
  151. The Lexical Analyzer Function `yylex'
  152.  
  153. * Calling Convention::  How `yyparse' calls `yylex'.
  154. * Token Values::      How `yylex' must return the semantic value
  155.                         of the token it has read.
  156. * Token Positions::   How `yylex' must return the text position
  157.                         (line number, etc.) of the token, if the
  158.                          actions want that.
  159. * Pure Calling::      How the calling convention differs
  160.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  161.  
  162. The Bison Parser Algorithm
  163.  
  164. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  165. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  166. * Precedence::        Operator precedence works by resolving conflicts.
  167. * Contextual Precedence::  When an operator's precedence depends on context.
  168. * Parser States::     The parser is a finite-state-machine with stack.
  169. * Reduce/Reduce::     When two rules are applicable in the same situation.
  170. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  171. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  172.  
  173. Operator Precedence
  174.  
  175. * Why Precedence::    An example showing why precedence is needed.
  176. * Using Precedence::  How to specify precedence in Bison grammars.
  177. * Precedence Examples::  How these features are used in the previous example.
  178. * How Precedence::    How they work.
  179.  
  180. Handling Context Dependencies
  181.  
  182. * Semantic Tokens::   Token parsing can depend on the semantic context.
  183. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  184. * Tie-in Recovery::   Lexical tie-ins have implications for how
  185.                         error recovery rules must be written.
  186.  
  187. Invoking Bison
  188.  
  189. * Bison Options::     All the options described in detail,
  190.             in alphabetical order by short options.
  191. * Option Cross Key::  Alphabetical list of long options.
  192. * VMS Invocation::    Bison command syntax on VMS.
  193.  
  194. 
  195. File: bison,  Node: Introduction,  Next: Conditions,  Prev: Top,  Up: Top
  196.  
  197. Introduction
  198. ************
  199.  
  200.    "Bison" is a general-purpose parser generator that converts a
  201. grammar description for an LALR(1) context-free grammar into a C
  202. program to parse that grammar.  Once you are proficient with Bison, you
  203. may use it to develop a wide range of language parsers, from those used
  204. in simple desk calculators to complex programming languages.
  205.  
  206.    Bison is upward compatible with Yacc: all properly-written Yacc
  207. grammars ought to work with Bison with no change.  Anyone familiar with
  208. Yacc should be able to use Bison with little trouble.  You need to be
  209. fluent in C programming in order to use Bison or to understand this
  210. manual.
  211.  
  212.    We begin with tutorial chapters that explain the basic concepts of
  213. using Bison and show three explained examples, each building on the
  214. last.  If you don't know Bison or Yacc, start by reading these
  215. chapters.  Reference chapters follow which describe specific aspects of
  216. Bison in detail.
  217.  
  218.    Bison was written primarily by Robert Corbett; Richard Stallman made
  219. it Yacc-compatible.  This edition corresponds to version 1.20 of Bison.
  220.  
  221. 
  222. File: bison,  Node: Conditions,  Next: Copying,  Prev: Introduction,  Up: Top
  223.  
  224. Conditions for Using Bison
  225. **************************
  226.  
  227.    Bison grammars can be used only in programs that are free software.
  228. This is in contrast to what happens with the GNU C compiler and the
  229. other GNU programming tools.
  230.  
  231.    The reason Bison is special is that the output of the Bison
  232. utility--the Bison parser file--contains a verbatim copy of a sizable
  233. piece of Bison, which is the code for the `yyparse' function.  (The
  234. actions from your grammar are inserted into this function at one point,
  235. but the rest of the function is not changed.)
  236.  
  237.    As a result, the Bison parser file is covered by the same copying
  238. conditions that cover Bison itself and the rest of the GNU system: any
  239. program containing it has to be distributed under the standard GNU
  240. copying conditions.
  241.  
  242.    Occasionally people who would like to use Bison to develop
  243. proprietary programs complain about this.
  244.  
  245.    We don't particularly sympathize with their complaints.  The purpose
  246. of the GNU project is to promote the right to share software and the
  247. practice of sharing software; it is a means of changing society.  The
  248. people who complain are planning to be uncooperative toward the rest of
  249. the world; why should they deserve our help in doing so?
  250.  
  251.    However, it's possible that a change in these conditions might
  252. encourage computer companies to use and distribute the GNU system.  If
  253. so, then we might decide to change the terms on `yyparse' as a matter
  254. of the strategy of promoting the right to share.  Such a change would be
  255. irrevocable.  Since we stand by the copying permissions we have
  256. announced, we cannot withdraw them once given.
  257.  
  258.    We mustn't make an irrevocable change hastily.  We have to wait
  259. until there is a complete GNU system and there has been time to learn
  260. how this issue affects its reception.
  261.  
  262. 
  263. File: bison,  Node: Copying,  Next: Concepts,  Prev: Conditions,  Up: Top
  264.  
  265. GNU GENERAL PUBLIC LICENSE
  266. **************************
  267.  
  268.                          Version 2, June 1991
  269.  
  270.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  271.      675 Mass Ave, Cambridge, MA 02139, USA
  272.      
  273.      Everyone is permitted to copy and distribute verbatim copies
  274.      of this license document, but changing it is not allowed.
  275.  
  276. Preamble
  277. ========
  278.  
  279.    The licenses for most software are designed to take away your
  280. freedom to share and change it.  By contrast, the GNU General Public
  281. License is intended to guarantee your freedom to share and change free
  282. software--to make sure the software is free for all its users.  This
  283. General Public License applies to most of the Free Software
  284. Foundation's software and to any other program whose authors commit to
  285. using it.  (Some other Free Software Foundation software is covered by
  286. the GNU Library General Public License instead.)  You can apply it to
  287. your programs, too.
  288.  
  289.    When we speak of free software, we are referring to freedom, not
  290. price.  Our General Public Licenses are designed to make sure that you
  291. have the freedom to distribute copies of free software (and charge for
  292. this service if you wish), that you receive source code or can get it
  293. if you want it, that you can change the software or use pieces of it in
  294. new free programs; and that you know you can do these things.
  295.  
  296.    To protect your rights, we need to make restrictions that forbid
  297. anyone to deny you these rights or to ask you to surrender the rights.
  298. These restrictions translate to certain responsibilities for you if you
  299. distribute copies of the software, or if you modify it.
  300.  
  301.    For example, if you distribute copies of such a program, whether
  302. gratis or for a fee, you must give the recipients all the rights that
  303. you have.  You must make sure that they, too, receive or can get the
  304. source code.  And you must show them these terms so they know their
  305. rights.
  306.  
  307.    We protect your rights with two steps: (1) copyright the software,
  308. and (2) offer you this license which gives you legal permission to copy,
  309. distribute and/or modify the software.
  310.  
  311.    Also, for each author's protection and ours, we want to make certain
  312. that everyone understands that there is no warranty for this free
  313. software.  If the software is modified by someone else and passed on, we
  314. want its recipients to know that what they have is not the original, so
  315. that any problems introduced by others will not reflect on the original
  316. authors' reputations.
  317.  
  318.    Finally, any free program is threatened constantly by software
  319. patents.  We wish to avoid the danger that redistributors of a free
  320. program will individually obtain patent licenses, in effect making the
  321. program proprietary.  To prevent this, we have made it clear that any
  322. patent must be licensed for everyone's free use or not licensed at all.
  323.  
  324.    The precise terms and conditions for copying, distribution and
  325. modification follow.
  326.  
  327.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  328.  
  329.   0. This License applies to any program or other work which contains a
  330.      notice placed by the copyright holder saying it may be distributed
  331.      under the terms of this General Public License.  The "Program",
  332.      below, refers to any such program or work, and a "work based on
  333.      the Program" means either the Program or any derivative work under
  334.      copyright law: that is to say, a work containing the Program or a
  335.      portion of it, either verbatim or with modifications and/or
  336.      translated into another language.  (Hereinafter, translation is
  337.      included without limitation in the term "modification".)  Each
  338.      licensee is addressed as "you".
  339.  
  340.      Activities other than copying, distribution and modification are
  341.      not covered by this License; they are outside its scope.  The act
  342.      of running the Program is not restricted, and the output from the
  343.      Program is covered only if its contents constitute a work based on
  344.      the Program (independent of having been made by running the
  345.      Program).  Whether that is true depends on what the Program does.
  346.  
  347.   1. You may copy and distribute verbatim copies of the Program's
  348.      source code as you receive it, in any medium, provided that you
  349.      conspicuously and appropriately publish on each copy an appropriate
  350.      copyright notice and disclaimer of warranty; keep intact all the
  351.      notices that refer to this License and to the absence of any
  352.      warranty; and give any other recipients of the Program a copy of
  353.      this License along with the Program.
  354.  
  355.      You may charge a fee for the physical act of transferring a copy,
  356.      and you may at your option offer warranty protection in exchange
  357.      for a fee.
  358.  
  359.   2. You may modify your copy or copies of the Program or any portion
  360.      of it, thus forming a work based on the Program, and copy and
  361.      distribute such modifications or work under the terms of Section 1
  362.      above, provided that you also meet all of these conditions:
  363.  
  364.        a. You must cause the modified files to carry prominent notices
  365.           stating that you changed the files and the date of any change.
  366.  
  367.        b. You must cause any work that you distribute or publish, that
  368.           in whole or in part contains or is derived from the Program
  369.           or any part thereof, to be licensed as a whole at no charge
  370.           to all third parties under the terms of this License.
  371.  
  372.        c. If the modified program normally reads commands interactively
  373.           when run, you must cause it, when started running for such
  374.           interactive use in the most ordinary way, to print or display
  375.           an announcement including an appropriate copyright notice and
  376.           a notice that there is no warranty (or else, saying that you
  377.           provide a warranty) and that users may redistribute the
  378.           program under these conditions, and telling the user how to
  379.           view a copy of this License.  (Exception: if the Program
  380.           itself is interactive but does not normally print such an
  381.           announcement, your work based on the Program is not required
  382.           to print an announcement.)
  383.  
  384.      These requirements apply to the modified work as a whole.  If
  385.      identifiable sections of that work are not derived from the
  386.      Program, and can be reasonably considered independent and separate
  387.      works in themselves, then this License, and its terms, do not
  388.      apply to those sections when you distribute them as separate
  389.      works.  But when you distribute the same sections as part of a
  390.      whole which is a work based on the Program, the distribution of
  391.      the whole must be on the terms of this License, whose permissions
  392.      for other licensees extend to the entire whole, and thus to each
  393.      and every part regardless of who wrote it.
  394.  
  395.      Thus, it is not the intent of this section to claim rights or
  396.      contest your rights to work written entirely by you; rather, the
  397.      intent is to exercise the right to control the distribution of
  398.      derivative or collective works based on the Program.
  399.  
  400.      In addition, mere aggregation of another work not based on the
  401.      Program with the Program (or with a work based on the Program) on
  402.      a volume of a storage or distribution medium does not bring the
  403.      other work under the scope of this License.
  404.  
  405.   3. You may copy and distribute the Program (or a work based on it,
  406.      under Section 2) in object code or executable form under the terms
  407.      of Sections 1 and 2 above provided that you also do one of the
  408.      following:
  409.  
  410.        a. Accompany it with the complete corresponding machine-readable
  411.           source code, which must be distributed under the terms of
  412.           Sections 1 and 2 above on a medium customarily used for
  413.           software interchange; or,
  414.  
  415.        b. Accompany it with a written offer, valid for at least three
  416.           years, to give any third party, for a charge no more than your
  417.           cost of physically performing source distribution, a complete
  418.           machine-readable copy of the corresponding source code, to be
  419.           distributed under the terms of Sections 1 and 2 above on a
  420.           medium customarily used for software interchange; or,
  421.  
  422.        c. Accompany it with the information you received as to the offer
  423.           to distribute corresponding source code.  (This alternative is
  424.           allowed only for noncommercial distribution and only if you
  425.           received the program in object code or executable form with
  426.           such an offer, in accord with Subsection b above.)
  427.  
  428.      The source code for a work means the preferred form of the work for
  429.      making modifications to it.  For an executable work, complete
  430.      source code means all the source code for all modules it contains,
  431.      plus any associated interface definition files, plus the scripts
  432.      used to control compilation and installation of the executable.
  433.      However, as a special exception, the source code distributed need
  434.      not include anything that is normally distributed (in either
  435.      source or binary form) with the major components (compiler,
  436.      kernel, and so on) of the operating system on which the executable
  437.      runs, unless that component itself accompanies the executable.
  438.  
  439.      If distribution of executable or object code is made by offering
  440.      access to copy from a designated place, then offering equivalent
  441.      access to copy the source code from the same place counts as
  442.      distribution of the source code, even though third parties are not
  443.      compelled to copy the source along with the object code.
  444.  
  445.   4. You may not copy, modify, sublicense, or distribute the Program
  446.      except as expressly provided under this License.  Any attempt
  447.      otherwise to copy, modify, sublicense or distribute the Program is
  448.      void, and will automatically terminate your rights under this
  449.      License.  However, parties who have received copies, or rights,
  450.      from you under this License will not have their licenses
  451.      terminated so long as such parties remain in full compliance.
  452.  
  453.   5. You are not required to accept this License, since you have not
  454.      signed it.  However, nothing else grants you permission to modify
  455.      or distribute the Program or its derivative works.  These actions
  456.      are prohibited by law if you do not accept this License.
  457.      Therefore, by modifying or distributing the Program (or any work
  458.      based on the Program), you indicate your acceptance of this
  459.      License to do so, and all its terms and conditions for copying,
  460.      distributing or modifying the Program or works based on it.
  461.  
  462.   6. Each time you redistribute the Program (or any work based on the
  463.      Program), the recipient automatically receives a license from the
  464.      original licensor to copy, distribute or modify the Program
  465.      subject to these terms and conditions.  You may not impose any
  466.      further restrictions on the recipients' exercise of the rights
  467.      granted herein.  You are not responsible for enforcing compliance
  468.      by third parties to this License.
  469.  
  470.   7. If, as a consequence of a court judgment or allegation of patent
  471.      infringement or for any other reason (not limited to patent
  472.      issues), conditions are imposed on you (whether by court order,
  473.      agreement or otherwise) that contradict the conditions of this
  474.      License, they do not excuse you from the conditions of this
  475.      License.  If you cannot distribute so as to satisfy simultaneously
  476.      your obligations under this License and any other pertinent
  477.      obligations, then as a consequence you may not distribute the
  478.      Program at all.  For example, if a patent license would not permit
  479.      royalty-free redistribution of the Program by all those who
  480.      receive copies directly or indirectly through you, then the only
  481.      way you could satisfy both it and this License would be to refrain
  482.      entirely from distribution of the Program.
  483.  
  484.      If any portion of this section is held invalid or unenforceable
  485.      under any particular circumstance, the balance of the section is
  486.      intended to apply and the section as a whole is intended to apply
  487.      in other circumstances.
  488.  
  489.      It is not the purpose of this section to induce you to infringe any
  490.      patents or other property right claims or to contest validity of
  491.      any such claims; this section has the sole purpose of protecting
  492.      the integrity of the free software distribution system, which is
  493.      implemented by public license practices.  Many people have made
  494.      generous contributions to the wide range of software distributed
  495.      through that system in reliance on consistent application of that
  496.      system; it is up to the author/donor to decide if he or she is
  497.      willing to distribute software through any other system and a
  498.      licensee cannot impose that choice.
  499.  
  500.      This section is intended to make thoroughly clear what is believed
  501.      to be a consequence of the rest of this License.
  502.  
  503.   8. If the distribution and/or use of the Program is restricted in
  504.      certain countries either by patents or by copyrighted interfaces,
  505.      the original copyright holder who places the Program under this
  506.      License may add an explicit geographical distribution limitation
  507.      excluding those countries, so that distribution is permitted only
  508.      in or among countries not thus excluded.  In such case, this
  509.      License incorporates the limitation as if written in the body of
  510.      this License.
  511.  
  512.   9. The Free Software Foundation may publish revised and/or new
  513.      versions of the General Public License from time to time.  Such
  514.      new versions will be similar in spirit to the present version, but
  515.      may differ in detail to address new problems or concerns.
  516.  
  517.      Each version is given a distinguishing version number.  If the
  518.      Program specifies a version number of this License which applies
  519.      to it and "any later version", you have the option of following
  520.      the terms and conditions either of that version or of any later
  521.      version published by the Free Software Foundation.  If the Program
  522.      does not specify a version number of this License, you may choose
  523.      any version ever published by the Free Software Foundation.
  524.  
  525.  10. If you wish to incorporate parts of the Program into other free
  526.      programs whose distribution conditions are different, write to the
  527.      author to ask for permission.  For software which is copyrighted
  528.      by the Free Software Foundation, write to the Free Software
  529.      Foundation; we sometimes make exceptions for this.  Our decision
  530.      will be guided by the two goals of preserving the free status of
  531.      all derivatives of our free software and of promoting the sharing
  532.      and reuse of software generally.
  533.  
  534.                                 NO WARRANTY
  535.  
  536.  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  537.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  538.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  539.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  540.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  541.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  542.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  543.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  544.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  545.      SERVICING, REPAIR OR CORRECTION.
  546.  
  547.  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  548.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  549.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  550.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  551.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  552.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  553.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  554.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  555.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  556.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  557.  
  558.                       END OF TERMS AND CONDITIONS
  559.  
  560. How to Apply These Terms to Your New Programs
  561. =============================================
  562.  
  563.    If you develop a new program, and you want it to be of the greatest
  564. possible use to the public, the best way to achieve this is to make it
  565. free software which everyone can redistribute and change under these
  566. terms.
  567.  
  568.    To do so, attach the following notices to the program.  It is safest
  569. to attach them to the start of each source file to most effectively
  570. convey the exclusion of warranty; and each file should have at least
  571. the "copyright" line and a pointer to where the full notice is found.
  572.  
  573.      ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  574.      Copyright (C) 19YY  NAME OF AUTHOR
  575.      
  576.      This program is free software; you can redistribute it and/or modify
  577.      it under the terms of the GNU General Public License as published by
  578.      the Free Software Foundation; either version 2 of the License, or
  579.      (at your option) any later version.
  580.      
  581.      This program is distributed in the hope that it will be useful,
  582.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  583.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  584.      GNU General Public License for more details.
  585.      
  586.      You should have received a copy of the GNU General Public License
  587.      along with this program; if not, write to the Free Software
  588.      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  589.  
  590.    Also add information on how to contact you by electronic and paper
  591. mail.
  592.  
  593.    If the program is interactive, make it output a short notice like
  594. this when it starts in an interactive mode:
  595.  
  596.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  597.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  598.      type `show w'.
  599.      This is free software, and you are welcome to redistribute it
  600.      under certain conditions; type `show c' for details.
  601.  
  602.    The hypothetical commands `show w' and `show c' should show the
  603. appropriate parts of the General Public License.  Of course, the
  604. commands you use may be called something other than `show w' and `show
  605. c'; they could even be mouse-clicks or menu items--whatever suits your
  606. program.
  607.  
  608.    You should also get your employer (if you work as a programmer) or
  609. your school, if any, to sign a "copyright disclaimer" for the program,
  610. if necessary.  Here is a sample; alter the names:
  611.  
  612.      Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  613.      `Gnomovision' (which makes passes at compilers) written by James Hacker.
  614.      
  615.      SIGNATURE OF TY COON, 1 April 1989
  616.      Ty Coon, President of Vice
  617.  
  618.    This General Public License does not permit incorporating your
  619. program into proprietary programs.  If your program is a subroutine
  620. library, you may consider it more useful to permit linking proprietary
  621. applications with the library.  If this is what you want to do, use the
  622. GNU Library General Public License instead of this License.
  623.  
  624. 
  625. File: bison,  Node: Concepts,  Next: Examples,  Prev: Copying,  Up: Top
  626.  
  627. The Concepts of Bison
  628. *********************
  629.  
  630.    This chapter introduces many of the basic concepts without which the
  631. details of Bison will not make sense.  If you do not already know how to
  632. use Bison or Yacc, we suggest you start by reading this chapter
  633. carefully.
  634.  
  635. * Menu:
  636.  
  637. * Language and Grammar::  Languages and context-free grammars,
  638.                             as mathematical ideas.
  639. * Grammar in Bison::  How we represent grammars for Bison's sake.
  640. * Semantic Values::   Each token or syntactic grouping can have
  641.                         a semantic value (the value of an integer,
  642.                         the name of an identifier, etc.).
  643. * Semantic Actions::  Each rule can have an action containing C code.
  644. * Bison Parser::      What are Bison's input and output,
  645.                         how is the output used?
  646. * Stages::            Stages in writing and running Bison grammars.
  647. * Grammar Layout::    Overall structure of a Bison grammar file.
  648.  
  649. 
  650. File: bison,  Node: Language and Grammar,  Next: Grammar in Bison,  Up: Concepts
  651.  
  652. Languages and Context-Free Grammars
  653. ===================================
  654.  
  655.    In order for Bison to parse a language, it must be described by a
  656. "context-free grammar".  This means that you specify one or more
  657. "syntactic groupings" and give rules for constructing them from their
  658. parts.  For example, in the C language, one kind of grouping is called
  659. an `expression'.  One rule for making an expression might be, "An
  660. expression can be made of a minus sign and another expression".
  661. Another would be, "An expression can be an integer".  As you can see,
  662. rules are often recursive, but there must be at least one rule which
  663. leads out of the recursion.
  664.  
  665.    The most common formal system for presenting such rules for humans
  666. to read is "Backus-Naur Form" or "BNF", which was developed in order to
  667. specify the language Algol 60.  Any grammar expressed in BNF is a
  668. context-free grammar.  The input to Bison is essentially
  669. machine-readable BNF.
  670.  
  671.    Not all context-free languages can be handled by Bison, only those
  672. that are LALR(1).  In brief, this means that it must be possible to
  673. tell how to parse any portion of an input string with just a single
  674. token of look-ahead.  Strictly speaking, that is a description of an
  675. LR(1) grammar, and LALR(1) involves additional restrictions that are
  676. hard to explain simply; but it is rare in actual practice to find an
  677. LR(1) grammar that fails to be LALR(1).  *Note Mysterious Reduce/Reduce
  678. Conflicts: Mystery Conflicts, for more information on this.
  679.  
  680.    In the formal grammatical rules for a language, each kind of
  681. syntactic unit or grouping is named by a "symbol".  Those which are
  682. built by grouping smaller constructs according to grammatical rules are
  683. called "nonterminal symbols"; those which can't be subdivided are called
  684. "terminal symbols" or "token types".  We call a piece of input
  685. corresponding to a single terminal symbol a "token", and a piece
  686. corresponding to a single nonterminal symbol a "grouping".
  687.  
  688.    We can use the C language as an example of what symbols, terminal and
  689. nonterminal, mean.  The tokens of C are identifiers, constants (numeric
  690. and string), and the various keywords, arithmetic operators and
  691. punctuation marks.  So the terminal symbols of a grammar for C include
  692. `identifier', `number', `string', plus one symbol for each keyword,
  693. operator or punctuation mark: `if', `return', `const', `static', `int',
  694. `char', `plus-sign', `open-brace', `close-brace', `comma' and many
  695. more.  (These tokens can be subdivided into characters, but that is a
  696. matter of lexicography, not grammar.)
  697.  
  698.    Here is a simple C function subdivided into tokens:
  699.  
  700.      int             /* keyword `int' */
  701.      square (x)      /* identifier, open-paren, */
  702.                      /* identifier, close-paren */
  703.           int x;     /* keyword `int', identifier, semicolon */
  704.      {               /* open-brace */
  705.        return x * x; /* keyword `return', identifier, */
  706.                      /* asterisk, identifier, semicolon */
  707.      }               /* close-brace */
  708.  
  709.    The syntactic groupings of C include the expression, the statement,
  710. the declaration, and the function definition.  These are represented in
  711. the grammar of C by nonterminal symbols `expression', `statement',
  712. `declaration' and `function definition'.  The full grammar uses dozens
  713. of additional language constructs, each with its own nonterminal
  714. symbol, in order to express the meanings of these four.  The example
  715. above is a function definition; it contains one declaration, and one
  716. statement.  In the statement, each `x' is an expression and so is `x *
  717. x'.
  718.  
  719.    Each nonterminal symbol must have grammatical rules showing how it
  720. is made out of simpler constructs.  For example, one kind of C
  721. statement is the `return' statement; this would be described with a
  722. grammar rule which reads informally as follows:
  723.  
  724.      A `statement' can be made of a `return' keyword, an `expression'
  725.      and a `semicolon'.
  726.  
  727. There would be many other rules for `statement', one for each kind of
  728. statement in C.
  729.  
  730.    One nonterminal symbol must be distinguished as the special one which
  731. defines a complete utterance in the language.  It is called the "start
  732. symbol".  In a compiler, this means a complete input program.  In the C
  733. language, the nonterminal symbol `sequence of definitions and
  734. declarations' plays this role.
  735.  
  736.    For example, `1 + 2' is a valid C expression--a valid part of a C
  737. program--but it is not valid as an *entire* C program.  In the
  738. context-free grammar of C, this follows from the fact that `expression'
  739. is not the start symbol.
  740.  
  741.    The Bison parser reads a sequence of tokens as its input, and groups
  742. the tokens using the grammar rules.  If the input is valid, the end
  743. result is that the entire token sequence reduces to a single grouping
  744. whose symbol is the grammar's start symbol.  If we use a grammar for C,
  745. the entire input must be a `sequence of definitions and declarations'.
  746. If not, the parser reports a syntax error.
  747.  
  748. 
  749. File: bison,  Node: Grammar in Bison,  Next: Semantic Values,  Prev: Language and Grammar,  Up: Concepts
  750.  
  751. From Formal Rules to Bison Input
  752. ================================
  753.  
  754.    A formal grammar is a mathematical construct.  To define the language
  755. for Bison, you must write a file expressing the grammar in Bison syntax:
  756. a "Bison grammar" file.  *Note Bison Grammar Files: Grammar File.
  757.  
  758.    A nonterminal symbol in the formal grammar is represented in Bison
  759. input as an identifier, like an identifier in C.  By convention, it
  760. should be in lower case, such as `expr', `stmt' or `declaration'.
  761.  
  762.    The Bison representation for a terminal symbol is also called a
  763. "token type".  Token types as well can be represented as C-like
  764. identifiers.  By convention, these identifiers should be upper case to
  765. distinguish them from nonterminals: for example, `INTEGER',
  766. `IDENTIFIER', `IF' or `RETURN'.  A terminal symbol that stands for a
  767. particular keyword in the language should be named after that keyword
  768. converted to upper case.  The terminal symbol `error' is reserved for
  769. error recovery.  *Note Symbols::.
  770.  
  771.    A terminal symbol can also be represented as a character literal,
  772. just like a C character constant.  You should do this whenever a token
  773. is just a single character (parenthesis, plus-sign, etc.): use that
  774. same character in a literal as the terminal symbol for that token.
  775.  
  776.    The grammar rules also have an expression in Bison syntax.  For
  777. example, here is the Bison rule for a C `return' statement.  The
  778. semicolon in quotes is a literal character token, representing part of
  779. the C syntax for the statement; the naked semicolon, and the colon, are
  780. Bison punctuation used in every rule.
  781.  
  782.      stmt:   RETURN expr ';'
  783.              ;
  784.  
  785. *Note Syntax of Grammar Rules: Rules.
  786.  
  787. 
  788. File: bison,  Node: Semantic Values,  Next: Semantic Actions,  Prev: Grammar in Bison,  Up: Concepts
  789.  
  790. Semantic Values
  791. ===============
  792.  
  793.    A formal grammar selects tokens only by their classifications: for
  794. example, if a rule mentions the terminal symbol `integer constant', it
  795. means that *any* integer constant is grammatically valid in that
  796. position.  The precise value of the constant is irrelevant to how to
  797. parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
  798. equally grammatical.
  799.  
  800.    But the precise value is very important for what the input means
  801. once it is parsed.  A compiler is useless if it fails to distinguish
  802. between 4, 1 and 3989 as constants in the program!  Therefore, each
  803. token in a Bison grammar has both a token type and a "semantic value".
  804. *Note Defining Language Semantics: Semantics, for details.
  805.  
  806.    The token type is a terminal symbol defined in the grammar, such as
  807. `INTEGER', `IDENTIFIER' or `',''.  It tells everything you need to know
  808. to decide where the token may validly appear and how to group it with
  809. other tokens.  The grammar rules know nothing about tokens except their
  810. types.
  811.  
  812.    The semantic value has all the rest of the information about the
  813. meaning of the token, such as the value of an integer, or the name of an
  814. identifier.  (A token such as `','' which is just punctuation doesn't
  815. need to have any semantic value.)
  816.  
  817.    For example, an input token might be classified as token type
  818. `INTEGER' and have the semantic value 4.  Another input token might
  819. have the same token type `INTEGER' but value 3989.  When a grammar rule
  820. says that `INTEGER' is allowed, either of these tokens is acceptable
  821. because each is an `INTEGER'.  When the parser accepts the token, it
  822. keeps track of the token's semantic value.
  823.  
  824.    Each grouping can also have a semantic value as well as its
  825. nonterminal symbol.  For example, in a calculator, an expression
  826. typically has a semantic value that is a number.  In a compiler for a
  827. programming language, an expression typically has a semantic value that
  828. is a tree structure describing the meaning of the expression.
  829.  
  830. 
  831. File: bison,  Node: Semantic Actions,  Next: Bison Parser,  Prev: Semantic Values,  Up: Concepts
  832.  
  833. Semantic Actions
  834. ================
  835.  
  836.    In order to be useful, a program must do more than parse input; it
  837. must also produce some output based on the input.  In a Bison grammar,
  838. a grammar rule can have an "action" made up of C statements.  Each time
  839. the parser recognizes a match for that rule, the action is executed.
  840. *Note Actions::.
  841.  
  842.    Most of the time, the purpose of an action is to compute the
  843. semantic value of the whole construct from the semantic values of its
  844. parts.  For example, suppose we have a rule which says an expression
  845. can be the sum of two expressions.  When the parser recognizes such a
  846. sum, each of the subexpressions has a semantic value which describes
  847. how it was built up.  The action for this rule should create a similar
  848. sort of value for the newly recognized larger expression.
  849.  
  850.    For example, here is a rule that says an expression can be the sum of
  851. two subexpressions:
  852.  
  853.      expr: expr '+' expr   { $$ = $1 + $3; }
  854.              ;
  855.  
  856. The action says how to produce the semantic value of the sum expression
  857. from the values of the two subexpressions.
  858.  
  859. 
  860. File: bison,  Node: Bison Parser,  Next: Stages,  Prev: Semantic Actions,  Up: Concepts
  861.  
  862. Bison Output: the Parser File
  863. =============================
  864.  
  865.    When you run Bison, you give it a Bison grammar file as input.  The
  866. output is a C source file that parses the language described by the
  867. grammar.  This file is called a "Bison parser".  Keep in mind that the
  868. Bison utility and the Bison parser are two distinct programs: the Bison
  869. utility is a program whose output is the Bison parser that becomes part
  870. of your program.
  871.  
  872.    The job of the Bison parser is to group tokens into groupings
  873. according to the grammar rules--for example, to build identifiers and
  874. operators into expressions.  As it does this, it runs the actions for
  875. the grammar rules it uses.
  876.  
  877.    The tokens come from a function called the "lexical analyzer" that
  878. you must supply in some fashion (such as by writing it in C).  The
  879. Bison parser calls the lexical analyzer each time it wants a new token.
  880. It doesn't know what is "inside" the tokens (though their semantic
  881. values may reflect this).  Typically the lexical analyzer makes the
  882. tokens by parsing characters of text, but Bison does not depend on
  883. this.  *Note The Lexical Analyzer Function `yylex': Lexical.
  884.  
  885.    The Bison parser file is C code which defines a function named
  886. `yyparse' which implements that grammar.  This function does not make a
  887. complete C program: you must supply some additional functions.  One is
  888. the lexical analyzer.  Another is an error-reporting function which the
  889. parser calls to report an error.  In addition, a complete C program must
  890. start with a function called `main'; you have to provide this, and
  891. arrange for it to call `yyparse' or the parser will never run.  *Note
  892. Parser C-Language Interface: Interface.
  893.  
  894.    Aside from the token type names and the symbols in the actions you
  895. write, all variable and function names used in the Bison parser file
  896. begin with `yy' or `YY'.  This includes interface functions such as the
  897. lexical analyzer function `yylex', the error reporting function
  898. `yyerror' and the parser function `yyparse' itself.  This also includes
  899. numerous identifiers used for internal purposes.  Therefore, you should
  900. avoid using C identifiers starting with `yy' or `YY' in the Bison
  901. grammar file except for the ones defined in this manual.
  902.  
  903. 
  904. File: bison,  Node: Stages,  Next: Grammar Layout,  Prev: Bison Parser,  Up: Concepts
  905.  
  906. Stages in Using Bison
  907. =====================
  908.  
  909.    The actual language-design process using Bison, from grammar
  910. specification to a working compiler or interpreter, has these parts:
  911.  
  912.   1. Formally specify the grammar in a form recognized by Bison (*note
  913.      Bison Grammar Files: Grammar File.).  For each grammatical rule in
  914.      the language, describe the action that is to be taken when an
  915.      instance of that rule is recognized.  The action is described by a
  916.      sequence of C statements.
  917.  
  918.   2. Write a lexical analyzer to process input and pass tokens to the
  919.      parser.  The lexical analyzer may be written by hand in C (*note
  920.      The Lexical Analyzer Function `yylex': Lexical.).  It could also
  921.      be produced using Lex, but the use of Lex is not discussed in this
  922.      manual.
  923.  
  924.   3. Write a controlling function that calls the Bison-produced parser.
  925.  
  926.   4. Write error-reporting routines.
  927.  
  928.    To turn this source code as written into a runnable program, you
  929. must follow these steps:
  930.  
  931.   1. Run Bison on the grammar to produce the parser.
  932.  
  933.   2. Compile the code output by Bison, as well as any other source
  934.      files.
  935.  
  936.   3. Link the object files to produce the finished product.
  937.  
  938. 
  939. File: bison,  Node: Grammar Layout,  Prev: Stages,  Up: Concepts
  940.  
  941. The Overall Layout of a Bison Grammar
  942. =====================================
  943.  
  944.    The input file for the Bison utility is a "Bison grammar file".  The
  945. general form of a Bison grammar file is as follows:
  946.  
  947.      %{
  948.      C DECLARATIONS
  949.      %}
  950.      
  951.      BISON DECLARATIONS
  952.      
  953.      %%
  954.      GRAMMAR RULES
  955.      %%
  956.      ADDITIONAL C CODE
  957.  
  958. The `%%', `%{' and `%}' are punctuation that appears in every Bison
  959. grammar file to separate the sections.
  960.  
  961.    The C declarations may define types and variables used in the
  962. actions.  You can also use preprocessor commands to define macros used
  963. there, and use `#include' to include header files that do any of these
  964. things.
  965.  
  966.    The Bison declarations declare the names of the terminal and
  967. nonterminal symbols, and may also describe operator precedence and the
  968. data types of semantic values of various symbols.
  969.  
  970.    The grammar rules define how to construct each nonterminal symbol
  971. from its parts.
  972.  
  973.    The additional C code can contain any C code you want to use.  Often
  974. the definition of the lexical analyzer `yylex' goes here, plus
  975. subroutines called by the actions in the grammar rules.  In a simple
  976. program, all the rest of the program can go here.
  977.  
  978. 
  979. File: bison,  Node: Examples,  Next: Grammar File,  Prev: Concepts,  Up: Top
  980.  
  981. Examples
  982. ********
  983.  
  984.    Now we show and explain three sample programs written using Bison: a
  985. reverse polish notation calculator, an algebraic (infix) notation
  986. calculator, and a multi-function calculator.  All three have been tested
  987. under BSD Unix 4.3; each produces a usable, though limited, interactive
  988. desk-top calculator.
  989.  
  990.    These examples are simple, but Bison grammars for real programming
  991. languages are written the same way.  You can copy these examples out of
  992. the Info file and into a source file to try them.
  993.  
  994. * Menu:
  995.  
  996. * RPN Calc::          Reverse polish notation calculator;
  997.                         a first example with no operator precedence.
  998. * Infix Calc::        Infix (algebraic) notation calculator.
  999.                         Operator precedence is introduced.
  1000. * Simple Error Recovery::  Continuing after syntax errors.
  1001. * Multi-function Calc::  Calculator with memory and trig functions.
  1002.                            It uses multiple data-types for semantic values.
  1003. * Exercises::         Ideas for improving the multi-function calculator.
  1004.  
  1005. 
  1006. File: bison,  Node: RPN Calc,  Next: Infix Calc,  Up: Examples
  1007.  
  1008. Reverse Polish Notation Calculator
  1009. ==================================
  1010.  
  1011.    The first example is that of a simple double-precision "reverse
  1012. polish notation" calculator (a calculator using postfix operators).
  1013. This example provides a good starting point, since operator precedence
  1014. is not an issue.  The second example will illustrate how operator
  1015. precedence is handled.
  1016.  
  1017.    The source code for this calculator is named `rpcalc.y'.  The `.y'
  1018. extension is a convention used for Bison input files.
  1019.  
  1020. * Menu:
  1021.  
  1022. * Decls: Rpcalc Decls.  Bison and C declarations for rpcalc.
  1023. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  1024. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  1025. * Main: Rpcalc Main.    The controlling function.
  1026. * Error: Rpcalc Error.  The error reporting function.
  1027. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  1028. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  1029.  
  1030. 
  1031. File: bison,  Node: Rpcalc Decls,  Next: Rpcalc Rules,  Up: RPN Calc
  1032.  
  1033. Declarations for `rpcalc'
  1034. -------------------------
  1035.  
  1036.    Here are the C and Bison declarations for the reverse polish notation
  1037. calculator.  As in C, comments are placed between `/*...*/'.
  1038.  
  1039.      /* Reverse polish notation calculator. */
  1040.      
  1041.      %{
  1042.      #define YYSTYPE double
  1043.      #include <math.h>
  1044.      %}
  1045.      
  1046.      %token NUM
  1047.      
  1048.      %% /* Grammar rules and actions follow */
  1049.  
  1050.    The C declarations section (*note The C Declarations Section: C
  1051. Declarations.) contains two preprocessor directives.
  1052.  
  1053.    The `#define' directive defines the macro `YYSTYPE', thus specifying
  1054. the C data type for semantic values of both tokens and groupings (*note
  1055. Data Types of Semantic Values: Value Type.).  The Bison parser will use
  1056. whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
  1057. the default.  Because we specify `double', each token and each
  1058. expression has an associated value, which is a floating point number.
  1059.  
  1060.    The `#include' directive is used to declare the exponentiation
  1061. function `pow'.
  1062.  
  1063.    The second section, Bison declarations, provides information to
  1064. Bison about the token types (*note The Bison Declarations Section:
  1065. Bison Declarations.).  Each terminal symbol that is not a
  1066. single-character literal must be declared here.  (Single-character
  1067. literals normally don't need to be declared.)  In this example, all the
  1068. arithmetic operators are designated by single-character literals, so the
  1069. only terminal symbol that needs to be declared is `NUM', the token type
  1070. for numeric constants.
  1071.  
  1072. 
  1073. File: bison,  Node: Rpcalc Rules,  Next: Rpcalc Lexer,  Prev: Rpcalc Decls,  Up: RPN Calc
  1074.  
  1075. Grammar Rules for `rpcalc'
  1076. --------------------------
  1077.  
  1078.    Here are the grammar rules for the reverse polish notation
  1079. calculator.
  1080.  
  1081.      input:    /* empty */
  1082.              | input line
  1083.      ;
  1084.      
  1085.      line:     '\n'
  1086.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1087.      ;
  1088.      
  1089.      exp:      NUM             { $$ = $1;         }
  1090.              | exp exp '+'     { $$ = $1 + $2;    }
  1091.              | exp exp '-'     { $$ = $1 - $2;    }
  1092.              | exp exp '*'     { $$ = $1 * $2;    }
  1093.              | exp exp '/'     { $$ = $1 / $2;    }
  1094.            /* Exponentiation */
  1095.              | exp exp '^'     { $$ = pow ($1, $2); }
  1096.            /* Unary minus    */
  1097.              | exp 'n'         { $$ = -$1;        }
  1098.      ;
  1099.      %%
  1100.  
  1101.    The groupings of the rpcalc "language" defined here are the
  1102. expression (given the name `exp'), the line of input (`line'), and the
  1103. complete input transcript (`input').  Each of these nonterminal symbols
  1104. has several alternate rules, joined by the `|' punctuator which is read
  1105. as "or".  The following sections explain what these rules mean.
  1106.  
  1107.    The semantics of the language is determined by the actions taken
  1108. when a grouping is recognized.  The actions are the C code that appears
  1109. inside braces.  *Note Actions::.
  1110.  
  1111.    You must specify these actions in C, but Bison provides the means for
  1112. passing semantic values between the rules.  In each action, the
  1113. pseudo-variable `$$' stands for the semantic value for the grouping
  1114. that the rule is going to construct.  Assigning a value to `$$' is the
  1115. main job of most actions.  The semantic values of the components of the
  1116. rule are referred to as `$1', `$2', and so on.
  1117.  
  1118. * Menu:
  1119.  
  1120. * Rpcalc Input::
  1121. * Rpcalc Line::
  1122. * Rpcalc Expr::
  1123.  
  1124. 
  1125. File: bison,  Node: Rpcalc Input,  Next: Rpcalc Line,  Up: Rpcalc Rules
  1126.  
  1127. Explanation of `input'
  1128. ......................
  1129.  
  1130.    Consider the definition of `input':
  1131.  
  1132.      input:    /* empty */
  1133.              | input line
  1134.      ;
  1135.  
  1136.    This definition reads as follows: "A complete input is either an
  1137. empty string, or a complete input followed by an input line".  Notice
  1138. that "complete input" is defined in terms of itself.  This definition
  1139. is said to be "left recursive" since `input' appears always as the
  1140. leftmost symbol in the sequence.  *Note Recursive Rules: Recursion.
  1141.  
  1142.    The first alternative is empty because there are no symbols between
  1143. the colon and the first `|'; this means that `input' can match an empty
  1144. string of input (no tokens).  We write the rules this way because it is
  1145. legitimate to type `Ctrl-d' right after you start the calculator.  It's
  1146. conventional to put an empty alternative first and write the comment
  1147. `/* empty */' in it.
  1148.  
  1149.    The second alternate rule (`input line') handles all nontrivial
  1150. input.  It means, "After reading any number of lines, read one more
  1151. line if possible."  The left recursion makes this rule into a loop.
  1152. Since the first alternative matches empty input, the loop can be
  1153. executed zero or more times.
  1154.  
  1155.    The parser function `yyparse' continues to process input until a
  1156. grammatical error is seen or the lexical analyzer says there are no more
  1157. input tokens; we will arrange for the latter to happen at end of file.
  1158.  
  1159. 
  1160. File: bison,  Node: Rpcalc Line,  Next: Rpcalc Expr,  Prev: Rpcalc Input,  Up: Rpcalc Rules
  1161.  
  1162. Explanation of `line'
  1163. .....................
  1164.  
  1165.    Now consider the definition of `line':
  1166.  
  1167.      line:     '\n'
  1168.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1169.      ;
  1170.  
  1171.    The first alternative is a token which is a newline character; this
  1172. means that rpcalc accepts a blank line (and ignores it, since there is
  1173. no action).  The second alternative is an expression followed by a
  1174. newline.  This is the alternative that makes rpcalc useful.  The
  1175. semantic value of the `exp' grouping is the value of `$1' because the
  1176. `exp' in question is the first symbol in the alternative.  The action
  1177. prints this value, which is the result of the computation the user
  1178. asked for.
  1179.  
  1180.    This action is unusual because it does not assign a value to `$$'.
  1181. As a consequence, the semantic value associated with the `line' is
  1182. uninitialized (its value will be unpredictable).  This would be a bug if
  1183. that value were ever used, but we don't use it: once rpcalc has printed
  1184. the value of the user's input line, that value is no longer needed.
  1185.  
  1186. 
  1187. File: bison,  Node: Rpcalc Expr,  Prev: Rpcalc Line,  Up: Rpcalc Rules
  1188.  
  1189. Explanation of `expr'
  1190. .....................
  1191.  
  1192.    The `exp' grouping has several rules, one for each kind of
  1193. expression.  The first rule handles the simplest expressions: those
  1194. that are just numbers.  The second handles an addition-expression,
  1195. which looks like two expressions followed by a plus-sign.  The third
  1196. handles subtraction, and so on.
  1197.  
  1198.      exp:      NUM
  1199.              | exp exp '+'     { $$ = $1 + $2;    }
  1200.              | exp exp '-'     { $$ = $1 - $2;    }
  1201.              ...
  1202.              ;
  1203.  
  1204.    We have used `|' to join all the rules for `exp', but we could
  1205. equally well have written them separately:
  1206.  
  1207.      exp:      NUM ;
  1208.      exp:      exp exp '+'     { $$ = $1 + $2;    } ;
  1209.      exp:      exp exp '-'     { $$ = $1 - $2;    } ;
  1210.              ...
  1211.  
  1212.    Most of the rules have actions that compute the value of the
  1213. expression in terms of the value of its parts.  For example, in the
  1214. rule for addition, `$1' refers to the first component `exp' and `$2'
  1215. refers to the second one.  The third component, `'+'', has no meaningful
  1216. associated semantic value, but if it had one you could refer to it as
  1217. `$3'.  When `yyparse' recognizes a sum expression using this rule, the
  1218. sum of the two subexpressions' values is produced as the value of the
  1219. entire expression.  *Note Actions::.
  1220.  
  1221.    You don't have to give an action for every rule.  When a rule has no
  1222. action, Bison by default copies the value of `$1' into `$$'.  This is
  1223. what happens in the first rule (the one that uses `NUM').
  1224.  
  1225.    The formatting shown here is the recommended convention, but Bison
  1226. does not require it.  You can add or change whitespace as much as you
  1227. wish.  For example, this:
  1228.  
  1229.      exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  1230.  
  1231. means the same thing as this:
  1232.  
  1233.      exp:      NUM
  1234.              | exp exp '+'    { $$ = $1 + $2; }
  1235.              | ...
  1236.  
  1237. The latter, however, is much more readable.
  1238.  
  1239. 
  1240. File: bison,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Rules,  Up: RPN Calc
  1241.  
  1242. The `rpcalc' Lexical Analyzer
  1243. -----------------------------
  1244.  
  1245.    The lexical analyzer's job is low-level parsing: converting
  1246. characters or sequences of characters into tokens.  The Bison parser
  1247. gets its tokens by calling the lexical analyzer.  *Note The Lexical
  1248. Analyzer Function `yylex': Lexical.
  1249.  
  1250.    Only a simple lexical analyzer is needed for the RPN calculator.
  1251. This lexical analyzer skips blanks and tabs, then reads in numbers as
  1252. `double' and returns them as `NUM' tokens.  Any other character that
  1253. isn't part of a number is a separate token.  Note that the token-code
  1254. for such a single-character token is the character itself.
  1255.  
  1256.    The return value of the lexical analyzer function is a numeric code
  1257. which represents a token type.  The same text used in Bison rules to
  1258. stand for this token type is also a C expression for the numeric code
  1259. for the type.  This works in two ways.  If the token type is a
  1260. character literal, then its numeric code is the ASCII code for that
  1261. character; you can use the same character literal in the lexical
  1262. analyzer to express the number.  If the token type is an identifier,
  1263. that identifier is defined by Bison as a C macro whose definition is
  1264. the appropriate number.  In this example, therefore, `NUM' becomes a
  1265. macro for `yylex' to use.
  1266.  
  1267.    The semantic value of the token (if it has one) is stored into the
  1268. global variable `yylval', which is where the Bison parser will look for
  1269. it.  (The C data type of `yylval' is `YYSTYPE', which was defined at
  1270. the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
  1271. Decls..)
  1272.  
  1273.    A token type code of zero is returned if the end-of-file is
  1274. encountered.  (Bison recognizes any nonpositive value as indicating the
  1275. end of the input.)
  1276.  
  1277.    Here is the code for the lexical analyzer:
  1278.  
  1279.      /* Lexical analyzer returns a double floating point
  1280.         number on the stack and the token NUM, or the ASCII
  1281.         character read if not a number.  Skips all blanks
  1282.         and tabs, returns 0 for EOF. */
  1283.      
  1284.      #include <ctype.h>
  1285.      
  1286.      yylex ()
  1287.      {
  1288.        int c;
  1289.      
  1290.        /* skip white space  */
  1291.        while ((c = getchar ()) == ' ' || c == '\t')
  1292.          ;
  1293.        /* process numbers   */
  1294.        if (c == '.' || isdigit (c))
  1295.          {
  1296.            ungetc (c, stdin);
  1297.            scanf ("%lf", &yylval);
  1298.            return NUM;
  1299.          }
  1300.        /* return end-of-file  */
  1301.        if (c == EOF)
  1302.          return 0;
  1303.        /* return single chars */
  1304.        return c;
  1305.      }
  1306.  
  1307. 
  1308. File: bison,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  1309.  
  1310. The Controlling Function
  1311. ------------------------
  1312.  
  1313.    In keeping with the spirit of this example, the controlling function
  1314. is kept to the bare minimum.  The only requirement is that it call
  1315. `yyparse' to start the process of parsing.
  1316.  
  1317.      main ()
  1318.      {
  1319.        yyparse ();
  1320.      }
  1321.  
  1322. 
  1323. File: bison,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  1324.  
  1325. The Error Reporting Routine
  1326. ---------------------------
  1327.  
  1328.    When `yyparse' detects a syntax error, it calls the error reporting
  1329. function `yyerror' to print an error message (usually but not always
  1330. `"parse error"').  It is up to the programmer to supply `yyerror'
  1331. (*note Parser C-Language Interface: Interface.), so here is the
  1332. definition we will use:
  1333.  
  1334.      #include <stdio.h>
  1335.      
  1336.      yyerror (s)  /* Called by yyparse on error */
  1337.           char *s;
  1338.      {
  1339.        printf ("%s\n", s);
  1340.      }
  1341.  
  1342.    After `yyerror' returns, the Bison parser may recover from the error
  1343. and continue parsing if the grammar contains a suitable error rule
  1344. (*note Error Recovery::.).  Otherwise, `yyparse' returns nonzero.  We
  1345. have not written any error rules in this example, so any invalid input
  1346. will cause the calculator program to exit.  This is not clean behavior
  1347. for a real calculator, but it is adequate in the first example.
  1348.  
  1349. 
  1350. File: bison,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  1351.  
  1352. Running Bison to Make the Parser
  1353. --------------------------------
  1354.  
  1355.    Before running Bison to produce a parser, we need to decide how to
  1356. arrange all the source code in one or more source files.  For such a
  1357. simple example, the easiest thing is to put everything in one file.
  1358. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  1359. "additional C code" section of the file (*note The Overall Layout of a
  1360. Bison Grammar: Grammar Layout.).
  1361.  
  1362.    For a large project, you would probably have several source files,
  1363. and use `make' to arrange to recompile them.
  1364.  
  1365.    With all the source in a single file, you use the following command
  1366. to convert it into a parser file:
  1367.  
  1368.      bison FILE_NAME.y
  1369.  
  1370. In this example the file was called `rpcalc.y' (for "Reverse Polish
  1371. CALCulator").  Bison produces a file named `FILE_NAME.tab.c', removing
  1372. the `.y' from the original file name. The file output by Bison contains
  1373. the source code for `yyparse'.  The additional functions in the input
  1374. file (`yylex', `yyerror' and `main') are copied verbatim to the output.
  1375.  
  1376. 
  1377. File: bison,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  1378.  
  1379. Compiling the Parser File
  1380. -------------------------
  1381.  
  1382.    Here is how to compile and run the parser file:
  1383.  
  1384.      # List files in current directory.
  1385.      % ls
  1386.      rpcalc.tab.c  rpcalc.y
  1387.      
  1388.      # Compile the Bison parser.
  1389.      # `-lm' tells compiler to search math library for `pow'.
  1390.      % cc rpcalc.tab.c -lm -o rpcalc
  1391.      
  1392.      # List files again.
  1393.      % ls
  1394.      rpcalc  rpcalc.tab.c  rpcalc.y
  1395.  
  1396.    The file `rpcalc' now contains the executable code.  Here is an
  1397. example session using `rpcalc'.
  1398.  
  1399.      % rpcalc
  1400.      4 9 +
  1401.      13
  1402.      3 7 + 3 4 5 *+-
  1403.      -13
  1404.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  1405.      13
  1406.      5 6 / 4 n +
  1407.      -3.166666667
  1408.      3 4 ^                            Exponentiation
  1409.      81
  1410.      ^D                               End-of-file indicator
  1411.      %
  1412.  
  1413. 
  1414. File: bison,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Examples
  1415.  
  1416. Infix Notation Calculator: `calc'
  1417. =================================
  1418.  
  1419.    We now modify rpcalc to handle infix operators instead of postfix.
  1420. Infix notation involves the concept of operator precedence and the need
  1421. for parentheses nested to arbitrary depth.  Here is the Bison code for
  1422. `calc.y', an infix desk-top calculator.
  1423.  
  1424.      /* Infix notation calculator--calc */
  1425.      
  1426.      %{
  1427.      #define YYSTYPE double
  1428.      #include <math.h>
  1429.      %}
  1430.      
  1431.      /* BISON Declarations */
  1432.      %token NUM
  1433.      %left '-' '+'
  1434.      %left '*' '/'
  1435.      %left NEG     /* negation--unary minus */
  1436.      %right '^'    /* exponentiation        */
  1437.      
  1438.      /* Grammar follows */
  1439.      %%
  1440.      input:    /* empty string */
  1441.              | input line
  1442.      ;
  1443.      
  1444.      line:     '\n'
  1445.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1446.      ;
  1447.      
  1448.      exp:      NUM                { $$ = $1;         }
  1449.              | exp '+' exp        { $$ = $1 + $3;    }
  1450.              | exp '-' exp        { $$ = $1 - $3;    }
  1451.              | exp '*' exp        { $$ = $1 * $3;    }
  1452.              | exp '/' exp        { $$ = $1 / $3;    }
  1453.              | '-' exp  %prec NEG { $$ = -$2;        }
  1454.              | exp '^' exp        { $$ = pow ($1, $3); }
  1455.              | '(' exp ')'        { $$ = $2;         }
  1456.      ;
  1457.      %%
  1458.  
  1459. The functions `yylex', `yyerror' and `main' can be the same as before.
  1460.  
  1461.    There are two important new features shown in this code.
  1462.  
  1463.    In the second section (Bison declarations), `%left' declares token
  1464. types and says they are left-associative operators.  The declarations
  1465. `%left' and `%right' (right associativity) take the place of `%token'
  1466. which is used to declare a token type name without associativity.
  1467. (These tokens are single-character literals, which ordinarily don't
  1468. need to be declared.  We declare them here to specify the
  1469. associativity.)
  1470.  
  1471.    Operator precedence is determined by the line ordering of the
  1472. declarations; the higher the line number of the declaration (lower on
  1473. the page or screen), the higher the precedence.  Hence, exponentiation
  1474. has the highest precedence, unary minus (`NEG') is next, followed by
  1475. `*' and `/', and so on.  *Note Operator Precedence: Precedence.
  1476.  
  1477.    The other important new feature is the `%prec' in the grammar section
  1478. for the unary minus operator.  The `%prec' simply instructs Bison that
  1479. the rule `| '-' exp' has the same precedence as `NEG'--in this case the
  1480. next-to-highest.  *Note Context-Dependent Precedence: Contextual
  1481. Precedence.
  1482.  
  1483.    Here is a sample run of `calc.y':
  1484.  
  1485.      % calc
  1486.      4 + 4.5 - (34/(8*3+-3))
  1487.      6.880952381
  1488.      -56 + 2
  1489.      -54
  1490.      3 ^ 2
  1491.      9
  1492.  
  1493. 
  1494. File: bison,  Node: Simple Error Recovery,  Next: Multi-function Calc,  Prev: Infix Calc,  Up: Examples
  1495.  
  1496. Simple Error Recovery
  1497. =====================
  1498.  
  1499.    Up to this point, this manual has not addressed the issue of "error
  1500. recovery"--how to continue parsing after the parser detects a syntax
  1501. error.  All we have handled is error reporting with `yyerror'.  Recall
  1502. that by default `yyparse' returns after calling `yyerror'.  This means
  1503. that an erroneous input line causes the calculator program to exit.
  1504. Now we show how to rectify this deficiency.
  1505.  
  1506.    The Bison language itself includes the reserved word `error', which
  1507. may be included in the grammar rules.  In the example below it has been
  1508. added to one of the alternatives for `line':
  1509.  
  1510.      line:     '\n'
  1511.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  1512.              | error '\n' { yyerrok;                  }
  1513.      ;
  1514.  
  1515.    This addition to the grammar allows for simple error recovery in the
  1516. event of a parse error.  If an expression that cannot be evaluated is
  1517. read, the error will be recognized by the third rule for `line', and
  1518. parsing will continue.  (The `yyerror' function is still called upon to
  1519. print its message as well.)  The action executes the statement
  1520. `yyerrok', a macro defined automatically by Bison; its meaning is that
  1521. error recovery is complete (*note Error Recovery::.).  Note the
  1522. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  1523.  
  1524.    This form of error recovery deals with syntax errors.  There are
  1525. other kinds of errors; for example, division by zero, which raises an
  1526. exception signal that is normally fatal.  A real calculator program
  1527. must handle this signal and use `longjmp' to return to `main' and
  1528. resume parsing input lines; it would also have to discard the rest of
  1529. the current line of input.  We won't discuss this issue further because
  1530. it is not specific to Bison programs.
  1531.  
  1532. 
  1533. File: bison,  Node: Multi-function Calc,  Next: Exercises,  Prev: Simple Error Recovery,  Up: Examples
  1534.  
  1535. Multi-Function Calculator: `mfcalc'
  1536. ===================================
  1537.  
  1538.    Now that the basics of Bison have been discussed, it is time to move
  1539. on to a more advanced problem.  The above calculators provided only five
  1540. functions, `+', `-', `*', `/' and `^'.  It would be nice to have a
  1541. calculator that provides other mathematical functions such as `sin',
  1542. `cos', etc.
  1543.  
  1544.    It is easy to add new operators to the infix calculator as long as
  1545. they are only single-character literals.  The lexical analyzer `yylex'
  1546. passes back all non-number characters as tokens, so new grammar rules
  1547. suffice for adding a new operator.  But we want something more
  1548. flexible: built-in functions whose syntax has this form:
  1549.  
  1550.      FUNCTION_NAME (ARGUMENT)
  1551.  
  1552. At the same time, we will add memory to the calculator, by allowing you
  1553. to create named variables, store values in them, and use them later.
  1554. Here is a sample session with the multi-function calculator:
  1555.  
  1556.      % acalc
  1557.      pi = 3.141592653589
  1558.      3.1415926536
  1559.      sin(pi)
  1560.      0.0000000000
  1561.      alpha = beta1 = 2.3
  1562.      2.3000000000
  1563.      alpha
  1564.      2.3000000000
  1565.      ln(alpha)
  1566.      0.8329091229
  1567.      exp(ln(beta1))
  1568.      2.3000000000
  1569.      %
  1570.  
  1571.    Note that multiple assignment and nested function calls are
  1572. permitted.
  1573.  
  1574. * Menu:
  1575.  
  1576. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  1577. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  1578. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  1579.  
  1580. 
  1581. File: bison,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Up: Multi-function Calc
  1582.  
  1583. Declarations for `mfcalc'
  1584. -------------------------
  1585.  
  1586.    Here are the C and Bison declarations for the multi-function
  1587. calculator.
  1588.  
  1589.      %{
  1590.      #include <math.h>  /* For math functions, cos(), sin(), etc. */
  1591.      #include "calc.h"  /* Contains definition of `symrec'        */
  1592.      %}
  1593.      %union {
  1594.      double     val;  /* For returning numbers.                   */
  1595.      symrec  *tptr;   /* For returning symbol-table pointers      */
  1596.      }
  1597.      
  1598.      %token <val>  NUM        /* Simple double precision number   */
  1599.      %token <tptr> VAR FNCT   /* Variable and Function            */
  1600.      %type  <val>  exp
  1601.      
  1602.      %right '='
  1603.      %left '-' '+'
  1604.      %left '*' '/'
  1605.      %left NEG     /* Negation--unary minus */
  1606.      %right '^'    /* Exponentiation        */
  1607.      
  1608.      /* Grammar follows */
  1609.      
  1610.      %%
  1611.  
  1612.    The above grammar introduces only two new features of the Bison
  1613. language.  These features allow semantic values to have various data
  1614. types (*note More Than One Value Type: Multiple Types.).
  1615.  
  1616.    The `%union' declaration specifies the entire list of possible types;
  1617. this is instead of defining `YYSTYPE'.  The allowable types are now
  1618. double-floats (for `exp' and `NUM') and pointers to entries in the
  1619. symbol table.  *Note The Collection of Value Types: Union Decl.
  1620.  
  1621.    Since values can now have various types, it is necessary to
  1622. associate a type with each grammar symbol whose semantic value is used.
  1623. These symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations
  1624. are augmented with information about their data type (placed between
  1625. angle brackets).
  1626.  
  1627.    The Bison construct `%type' is used for declaring nonterminal
  1628. symbols, just as `%token' is used for declaring token types.  We have
  1629. not used `%type' before because nonterminal symbols are normally
  1630. declared implicitly by the rules that define them.  But `exp' must be
  1631. declared explicitly so we can specify its value type.  *Note
  1632. Nonterminal Symbols: Type Decl.
  1633.  
  1634. 
  1635. File: bison,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  1636.  
  1637. Grammar Rules for `mfcalc'
  1638. --------------------------
  1639.  
  1640.    Here are the grammar rules for the multi-function calculator.  Most
  1641. of them are copied directly from `calc'; three rules, those which
  1642. mention `VAR' or `FNCT', are new.
  1643.  
  1644.      input:   /* empty */
  1645.              | input line
  1646.      ;
  1647.      
  1648.      line:
  1649.                '\n'
  1650.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  1651.              | error '\n' { yyerrok;                  }
  1652.      ;
  1653.      
  1654.      exp:      NUM                { $$ = $1;                         }
  1655.              | VAR                { $$ = $1->value.var;              }
  1656.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  1657.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  1658.              | exp '+' exp        { $$ = $1 + $3;                    }
  1659.              | exp '-' exp        { $$ = $1 - $3;                    }
  1660.              | exp '*' exp        { $$ = $1 * $3;                    }
  1661.              | exp '/' exp        { $$ = $1 / $3;                    }
  1662.              | '-' exp  %prec NEG { $$ = -$2;                        }
  1663.              | exp '^' exp        { $$ = pow ($1, $3);               }
  1664.              | '(' exp ')'        { $$ = $2;                         }
  1665.      ;
  1666.      /* End of grammar */
  1667.      %%
  1668.  
  1669. 
  1670. File: bison,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  1671.  
  1672. The `mfcalc' Symbol Table
  1673. -------------------------
  1674.  
  1675.    The multi-function calculator requires a symbol table to keep track
  1676. of the names and meanings of variables and functions.  This doesn't
  1677. affect the grammar rules (except for the actions) or the Bison
  1678. declarations, but it requires some additional C functions for support.
  1679.  
  1680.    The symbol table itself consists of a linked list of records.  Its
  1681. definition, which is kept in the header `calc.h', is as follows.  It
  1682. provides for either functions or variables to be placed in the table.
  1683.  
  1684.      /* Data type for links in the chain of symbols.      */
  1685.      struct symrec
  1686.      {
  1687.        char *name;  /* name of symbol                     */
  1688.        int type;    /* type of symbol: either VAR or FNCT */
  1689.        union {
  1690.          double var;           /* value of a VAR          */
  1691.          double (*fnctptr)();  /* value of a FNCT         */
  1692.        } value;
  1693.        struct symrec *next;    /* link field              */
  1694.      };
  1695.  
  1696.      typedef struct symrec symrec;
  1697.      
  1698.      /* The symbol table: a chain of `struct symrec'.     */
  1699.      extern symrec *sym_table;
  1700.      
  1701.      symrec *putsym ();
  1702.      symrec *getsym ();
  1703.  
  1704.    The new version of `main' includes a call to `init_table', a
  1705. function that initializes the symbol table.  Here it is, and
  1706. `init_table' as well:
  1707.  
  1708.      #include <stdio.h>
  1709.      
  1710.      main ()
  1711.      {
  1712.        init_table ();
  1713.        yyparse ();
  1714.      }
  1715.  
  1716.      yyerror (s)  /* Called by yyparse on error */
  1717.           char *s;
  1718.      {
  1719.        printf ("%s\n", s);
  1720.      }
  1721.      
  1722.      struct init
  1723.      {
  1724.        char *fname;
  1725.        double (*fnct)();
  1726.      };
  1727.  
  1728.      struct init arith_fncts[]
  1729.        = {
  1730.            "sin", sin,
  1731.            "cos", cos,
  1732.            "atan", atan,
  1733.            "ln", log,
  1734.            "exp", exp,
  1735.            "sqrt", sqrt,
  1736.            0, 0
  1737.          };
  1738.      
  1739.      /* The symbol table: a chain of `struct symrec'.  */
  1740.      symrec *sym_table = (symrec *)0;
  1741.  
  1742.      init_table ()  /* puts arithmetic functions in table. */
  1743.      {
  1744.        int i;
  1745.        symrec *ptr;
  1746.        for (i = 0; arith_fncts[i].fname != 0; i++)
  1747.          {
  1748.            ptr = putsym (arith_fncts[i].fname, FNCT);
  1749.            ptr->value.fnctptr = arith_fncts[i].fnct;
  1750.          }
  1751.      }
  1752.  
  1753.    By simply editing the initialization list and adding the necessary
  1754. include files, you can add additional functions to the calculator.
  1755.  
  1756.    Two important functions allow look-up and installation of symbols in
  1757. the symbol table.  The function `putsym' is passed a name and the type
  1758. (`VAR' or `FNCT') of the object to be installed.  The object is linked
  1759. to the front of the list, and a pointer to the object is returned.  The
  1760. function `getsym' is passed the name of the symbol to look up.  If
  1761. found, a pointer to that symbol is returned; otherwise zero is returned.
  1762.  
  1763.      symrec *
  1764.      putsym (sym_name,sym_type)
  1765.           char *sym_name;
  1766.           int sym_type;
  1767.      {
  1768.        symrec *ptr;
  1769.        ptr = (symrec *) malloc (sizeof (symrec));
  1770.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  1771.        strcpy (ptr->name,sym_name);
  1772.        ptr->type = sym_type;
  1773.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  1774.        ptr->next = (struct symrec *)sym_table;
  1775.        sym_table = ptr;
  1776.        return ptr;
  1777.      }
  1778.      
  1779.      symrec *
  1780.      getsym (sym_name)
  1781.           char *sym_name;
  1782.      {
  1783.        symrec *ptr;
  1784.        for (ptr = sym_table; ptr != (symrec *) 0;
  1785.             ptr = (symrec *)ptr->next)
  1786.          if (strcmp (ptr->name,sym_name) == 0)
  1787.            return ptr;
  1788.        return 0;
  1789.      }
  1790.  
  1791.    The function `yylex' must now recognize variables, numeric values,
  1792. and the single-character arithmetic operators.  Strings of alphanumeric
  1793. characters with a leading nondigit are recognized as either variables or
  1794. functions depending on what the symbol table says about them.
  1795.  
  1796.    The string is passed to `getsym' for look up in the symbol table.  If
  1797. the name appears in the table, a pointer to its location and its type
  1798. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  1799. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  1800. pointer and its type (which must be `VAR') is returned to `yyparse'.
  1801.  
  1802.    No change is needed in the handling of numeric values and arithmetic
  1803. operators in `yylex'.
  1804.  
  1805.      #include <ctype.h>
  1806.      yylex ()
  1807.      {
  1808.        int c;
  1809.      
  1810.        /* Ignore whitespace, get first nonwhite character.  */
  1811.        while ((c = getchar ()) == ' ' || c == '\t');
  1812.      
  1813.        if (c == EOF)
  1814.          return 0;
  1815.  
  1816.      /* Char starts a number => parse the number.         */
  1817.        if (c == '.' || isdigit (c))
  1818.          {
  1819.            ungetc (c, stdin);
  1820.            scanf ("%lf", &yylval.val);
  1821.            return NUM;
  1822.          }
  1823.  
  1824.      /* Char starts an identifier => read the name.       */
  1825.        if (isalpha (c))
  1826.          {
  1827.            symrec *s;
  1828.            static char *symbuf = 0;
  1829.            static int length = 0;
  1830.            int i;
  1831.  
  1832.      /* Initially make the buffer long enough
  1833.               for a 40-character symbol name.  */
  1834.            if (length == 0)
  1835.              length = 40, symbuf = (char *)malloc (length + 1);
  1836.      
  1837.            i = 0;
  1838.            do
  1839.  
  1840.      {
  1841.                /* If buffer is full, make it bigger.        */
  1842.                if (i == length)
  1843.                  {
  1844.                    length *= 2;
  1845.                    symbuf = (char *)realloc (symbuf, length + 1);
  1846.                  }
  1847.                /* Add this character to the buffer.         */
  1848.                symbuf[i++] = c;
  1849.                /* Get another character.                    */
  1850.                c = getchar ();
  1851.              }
  1852.  
  1853.      while (c != EOF && isalnum (c));
  1854.      
  1855.            ungetc (c, stdin);
  1856.            symbuf[i] = '\0';
  1857.  
  1858.      s = getsym (symbuf);
  1859.            if (s == 0)
  1860.              s = putsym (symbuf, VAR);
  1861.            yylval.tptr = s;
  1862.            return s->type;
  1863.          }
  1864.      
  1865.        /* Any other character is a token by itself.        */
  1866.        return c;
  1867.      }
  1868.  
  1869.    This program is both powerful and flexible. You may easily add new
  1870. functions, and it is a simple job to modify this code to install
  1871. predefined variables such as `pi' or `e' as well.
  1872.  
  1873. 
  1874. File: bison,  Node: Exercises,  Prev: Multi-function Calc,  Up: Examples
  1875.  
  1876. Exercises
  1877. =========
  1878.  
  1879.   1. Add some new functions from `math.h' to the initialization list.
  1880.  
  1881.   2. Add another array that contains constants and their values.  Then
  1882.      modify `init_table' to add these constants to the symbol table.
  1883.      It will be easiest to give the constants type `VAR'.
  1884.  
  1885.   3. Make the program report an error if the user refers to an
  1886.      uninitialized variable in any way except to store a value in it.
  1887.  
  1888. 
  1889. File: bison,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  1890.  
  1891. Bison Grammar Files
  1892. *******************
  1893.  
  1894.    Bison takes as input a context-free grammar specification and
  1895. produces a C-language function that recognizes correct instances of the
  1896. grammar.
  1897.  
  1898.    The Bison grammar input file conventionally has a name ending in
  1899. `.y'.
  1900.  
  1901. * Menu:
  1902.  
  1903. * Grammar Outline::   Overall layout of the grammar file.
  1904. * Symbols::           Terminal and nonterminal symbols.
  1905. * Rules::             How to write grammar rules.
  1906. * Recursion::         Writing recursive rules.
  1907. * Semantics::         Semantic values and actions.
  1908. * Declarations::      All kinds of Bison declarations are described here.
  1909. * Multiple Parsers::  Putting more than one Bison parser in one program.
  1910.  
  1911. 
  1912. File: bison,  Node: Grammar Outline,  Next: Symbols,  Up: Grammar File
  1913.  
  1914. Outline of a Bison Grammar
  1915. ==========================
  1916.  
  1917.    A Bison grammar file has four main sections, shown here with the
  1918. appropriate delimiters:
  1919.  
  1920.      %{
  1921.      C DECLARATIONS
  1922.      %}
  1923.      
  1924.      BISON DECLARATIONS
  1925.      
  1926.      %%
  1927.      GRAMMAR RULES
  1928.      %%
  1929.      
  1930.      ADDITIONAL C CODE
  1931.  
  1932.    Comments enclosed in `/* ... */' may appear in any of the sections.
  1933.  
  1934. * Menu:
  1935.  
  1936. * C Declarations::    Syntax and usage of the C declarations section.
  1937. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  1938. * Grammar Rules::     Syntax and usage of the grammar rules section.
  1939. * C Code::            Syntax and usage of the additional C code section.
  1940.  
  1941. 
  1942. File: bison,  Node: C Declarations,  Next: Bison Declarations,  Up: Grammar Outline
  1943.  
  1944. The C Declarations Section
  1945. --------------------------
  1946.  
  1947.    The C DECLARATIONS section contains macro definitions and
  1948. declarations of functions and variables that are used in the actions in
  1949. the grammar rules.  These are copied to the beginning of the parser
  1950. file so that they precede the definition of `yyparse'.  You can use
  1951. `#include' to get the declarations from a header file.  If you don't
  1952. need any C declarations, you may omit the `%{' and `%}' delimiters that
  1953. bracket this section.
  1954.  
  1955. 
  1956. File: bison,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  1957.  
  1958. The Bison Declarations Section
  1959. ------------------------------
  1960.  
  1961.    The BISON DECLARATIONS section contains declarations that define
  1962. terminal and nonterminal symbols, specify precedence, and so on.  In
  1963. some simple grammars you may not need any declarations.  *Note Bison
  1964. Declarations: Declarations.
  1965.  
  1966. 
  1967. File: bison,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  1968.  
  1969. The Grammar Rules Section
  1970. -------------------------
  1971.  
  1972.    The "grammar rules" section contains one or more Bison grammar
  1973. rules, and nothing else.  *Note Syntax of Grammar Rules: Rules.
  1974.  
  1975.    There must always be at least one grammar rule, and the first `%%'
  1976. (which precedes the grammar rules) may never be omitted even if it is
  1977. the first thing in the file.
  1978.  
  1979. 
  1980. File: bison,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  1981.  
  1982. The Additional C Code Section
  1983. -----------------------------
  1984.  
  1985.    The ADDITIONAL C CODE section is copied verbatim to the end of the
  1986. parser file, just as the C DECLARATIONS section is copied to the
  1987. beginning.  This is the most convenient place to put anything that you
  1988. want to have in the parser file but which need not come before the
  1989. definition of `yyparse'.  For example, the definitions of `yylex' and
  1990. `yyerror' often go here.  *Note Parser C-Language Interface: Interface.
  1991.  
  1992.    If the last section is empty, you may omit the `%%' that separates it
  1993. from the grammar rules.
  1994.  
  1995.    The Bison parser itself contains many static variables whose names
  1996. start with `yy' and many macros whose names start with `YY'.  It is a
  1997. good idea to avoid using any such names (except those documented in this
  1998. manual) in the additional C code section of the grammar file.
  1999.  
  2000. 
  2001. File: bison,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  2002.  
  2003. Symbols, Terminal and Nonterminal
  2004. =================================
  2005.  
  2006.    "Symbols" in Bison grammars represent the grammatical classifications
  2007. of the language.
  2008.  
  2009.    A "terminal symbol" (also known as a "token type") represents a
  2010. class of syntactically equivalent tokens.  You use the symbol in grammar
  2011. rules to mean that a token in that class is allowed.  The symbol is
  2012. represented in the Bison parser by a numeric code, and the `yylex'
  2013. function returns a token type code to indicate what kind of token has
  2014. been read.  You don't need to know what the code value is; you can use
  2015. the symbol to stand for it.
  2016.  
  2017.    A "nonterminal symbol" stands for a class of syntactically equivalent
  2018. groupings.  The symbol name is used in writing grammar rules.  By
  2019. convention, it should be all lower case.
  2020.  
  2021.    Symbol names can contain letters, digits (not at the beginning),
  2022. underscores and periods.  Periods make sense only in nonterminals.
  2023.  
  2024.    There are two ways of writing terminal symbols in the grammar:
  2025.  
  2026.    * A "named token type" is written with an identifier, like an
  2027.      identifier in C.  By convention, it should be all upper case.  Each
  2028.      such name must be defined with a Bison declaration such as
  2029.      `%token'.  *Note Token Type Names: Token Decl.
  2030.  
  2031.    * A "character token type" (or "literal token") is written in the
  2032.      grammar using the same syntax used in C for character constants;
  2033.      for example, `'+'' is a character token type.  A character token
  2034.      type doesn't need to be declared unless you need to specify its
  2035.      semantic value data type (*note Data Types of Semantic Values:
  2036.      Value Type.), associativity, or precedence (*note Operator
  2037.      Precedence: Precedence.).
  2038.  
  2039.      By convention, a character token type is used only to represent a
  2040.      token that consists of that particular character.  Thus, the token
  2041.      type `'+'' is used to represent the character `+' as a token.
  2042.      Nothing enforces this convention, but if you depart from it, your
  2043.      program will confuse other readers.
  2044.  
  2045.      All the usual escape sequences used in character literals in C can
  2046.      be used in Bison as well, but you must not use the null character
  2047.      as a character literal because its ASCII code, zero, is the code
  2048.      `yylex' returns for end-of-input (*note Calling Convention for
  2049.      `yylex': Calling Convention.).
  2050.  
  2051.    How you choose to write a terminal symbol has no effect on its
  2052. grammatical meaning.  That depends only on where it appears in rules and
  2053. on when the parser function returns that symbol.
  2054.  
  2055.    The value returned by `yylex' is always one of the terminal symbols
  2056. (or 0 for end-of-input).  Whichever way you write the token type in the
  2057. grammar rules, you write it the same way in the definition of `yylex'.
  2058. The numeric code for a character token type is simply the ASCII code for
  2059. the character, so `yylex' can use the identical character constant to
  2060. generate the requisite code.  Each named token type becomes a C macro in
  2061. the parser file, so `yylex' can use the name to stand for the code.
  2062. (This is why periods don't make sense in terminal symbols.) *Note
  2063. Calling Convention for `yylex': Calling Convention.
  2064.  
  2065.    If `yylex' is defined in a separate file, you need to arrange for the
  2066. token-type macro definitions to be available there.  Use the `-d'
  2067. option when you run Bison, so that it will write these macro definitions
  2068. into a separate header file `NAME.tab.h' which you can include in the
  2069. other source files that need it.  *Note Invoking Bison: Invocation.
  2070.  
  2071.    The symbol `error' is a terminal symbol reserved for error recovery
  2072. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  2073. In particular, `yylex' should never return this value.
  2074.  
  2075. 
  2076. File: bison,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  2077.  
  2078. Syntax of Grammar Rules
  2079. =======================
  2080.  
  2081.    A Bison grammar rule has the following general form:
  2082.  
  2083.      RESULT: COMPONENTS...
  2084.              ;
  2085.  
  2086. where RESULT is the nonterminal symbol that this rule describes and
  2087. COMPONENTS are various terminal and nonterminal symbols that are put
  2088. together by this rule (*note Symbols::.).
  2089.  
  2090.    For example,
  2091.  
  2092.      exp:      exp '+' exp
  2093.              ;
  2094.  
  2095. says that two groupings of type `exp', with a `+' token in between, can
  2096. be combined into a larger grouping of type `exp'.
  2097.  
  2098.    Whitespace in rules is significant only to separate symbols.  You
  2099. can add extra whitespace as you wish.
  2100.  
  2101.    Scattered among the components can be ACTIONS that determine the
  2102. semantics of the rule.  An action looks like this:
  2103.  
  2104.      {C STATEMENTS}
  2105.  
  2106. Usually there is only one action and it follows the components.  *Note
  2107. Actions::.
  2108.  
  2109.    Multiple rules for the same RESULT can be written separately or can
  2110. be joined with the vertical-bar character `|' as follows:
  2111.  
  2112.      RESULT:   RULE1-COMPONENTS...
  2113.              | RULE2-COMPONENTS...
  2114.              ...
  2115.              ;
  2116.  
  2117. They are still considered distinct rules even when joined in this way.
  2118.  
  2119.    If COMPONENTS in a rule is empty, it means that RESULT can match the
  2120. empty string.  For example, here is how to define a comma-separated
  2121. sequence of zero or more `exp' groupings:
  2122.  
  2123.      expseq:   /* empty */
  2124.              | expseq1
  2125.              ;
  2126.      
  2127.      expseq1:  exp
  2128.              | expseq1 ',' exp
  2129.              ;
  2130.  
  2131. It is customary to write a comment `/* empty */' in each rule with no
  2132. components.
  2133.  
  2134. 
  2135. File: bison,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  2136.  
  2137. Recursive Rules
  2138. ===============
  2139.  
  2140.    A rule is called "recursive" when its RESULT nonterminal appears
  2141. also on its right hand side.  Nearly all Bison grammars need to use
  2142. recursion, because that is the only way to define a sequence of any
  2143. number of somethings.  Consider this recursive definition of a
  2144. comma-separated sequence of one or more expressions:
  2145.  
  2146.      expseq1:  exp
  2147.              | expseq1 ',' exp
  2148.              ;
  2149.  
  2150. Since the recursive use of `expseq1' is the leftmost symbol in the
  2151. right hand side, we call this "left recursion".  By contrast, here the
  2152. same construct is defined using "right recursion":
  2153.  
  2154.      expseq1:  exp
  2155.              | exp ',' expseq1
  2156.              ;
  2157.  
  2158. Any kind of sequence can be defined using either left recursion or
  2159. right recursion, but you should always use left recursion, because it
  2160. can parse a sequence of any number of elements with bounded stack
  2161. space.  Right recursion uses up space on the Bison stack in proportion
  2162. to the number of elements in the sequence, because all the elements
  2163. must be shifted onto the stack before the rule can be applied even
  2164. once.  *Note The Bison Parser Algorithm: Algorithm, for further
  2165. explanation of this.
  2166.  
  2167.    "Indirect" or "mutual" recursion occurs when the result of the rule
  2168. does not appear directly on its right hand side, but does appear in
  2169. rules for other nonterminals which do appear on its right hand side.
  2170.  
  2171.    For example:
  2172.  
  2173.      expr:     primary
  2174.              | primary '+' primary
  2175.              ;
  2176.      
  2177.      primary:  constant
  2178.              | '(' expr ')'
  2179.              ;
  2180.  
  2181. defines two mutually-recursive nonterminals, since each refers to the
  2182. other.
  2183.  
  2184. 
  2185. File: bison,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  2186.  
  2187. Defining Language Semantics
  2188. ===========================
  2189.  
  2190.    The grammar rules for a language determine only the syntax.  The
  2191. semantics are determined by the semantic values associated with various
  2192. tokens and groupings, and by the actions taken when various groupings
  2193. are recognized.
  2194.  
  2195.    For example, the calculator calculates properly because the value
  2196. associated with each expression is the proper number; it adds properly
  2197. because the action for the grouping `X + Y' is to add the numbers
  2198. associated with X and Y.
  2199.  
  2200. * Menu:
  2201.  
  2202. * Value Type::        Specifying one data type for all semantic values.
  2203. * Multiple Types::    Specifying several alternative data types.
  2204. * Actions::           An action is the semantic definition of a grammar rule.
  2205. * Action Types::      Specifying data types for actions to operate on.
  2206. * Mid-Rule Actions::  Most actions go at the end of a rule.
  2207.                       This says when, why and how to use the exceptional
  2208.                         action in the middle of a rule.
  2209.  
  2210. 
  2211. File: bison,  Node: Value Type,  Next: Multiple Types,  Up: Semantics
  2212.  
  2213. Data Types of Semantic Values
  2214. -----------------------------
  2215.  
  2216.    In a simple program it may be sufficient to use the same data type
  2217. for the semantic values of all language constructs.  This was true in
  2218. the RPN and infix calculator examples (*note Reverse Polish Notation
  2219. Calculator: RPN Calc.).
  2220.  
  2221.    Bison's default is to use type `int' for all semantic values.  To
  2222. specify some other type, define `YYSTYPE' as a macro, like this:
  2223.  
  2224.      #define YYSTYPE double
  2225.  
  2226. This macro definition must go in the C declarations section of the
  2227. grammar file (*note Outline of a Bison Grammar: Grammar Outline.).
  2228.  
  2229. 
  2230. File: bison,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  2231.  
  2232. More Than One Value Type
  2233. ------------------------
  2234.  
  2235.    In most programs, you will need different data types for different
  2236. kinds of tokens and groupings.  For example, a numeric constant may
  2237. need type `int' or `long', while a string constant needs type `char *',
  2238. and an identifier might need a pointer to an entry in the symbol table.
  2239.  
  2240.    To use more than one data type for semantic values in one parser,
  2241. Bison requires you to do two things:
  2242.  
  2243.    * Specify the entire collection of possible data types, with the
  2244.      `%union' Bison declaration (*note The Collection of Value Types:
  2245.      Union Decl.).
  2246.  
  2247.    * Choose one of those types for each symbol (terminal or nonterminal)
  2248.      for which semantic values are used.  This is done for tokens with
  2249.      the `%token' Bison declaration (*note Token Type Names: Token
  2250.      Decl.) and for groupings with the `%type' Bison declaration (*note
  2251.      Nonterminal Symbols: Type Decl.).
  2252.  
  2253. 
  2254. File: bison,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  2255.  
  2256. Actions
  2257. -------
  2258.  
  2259.    An action accompanies a syntactic rule and contains C code to be
  2260. executed each time an instance of that rule is recognized.  The task of
  2261. most actions is to compute a semantic value for the grouping built by
  2262. the rule from the semantic values associated with tokens or smaller
  2263. groupings.
  2264.  
  2265.    An action consists of C statements surrounded by braces, much like a
  2266. compound statement in C.  It can be placed at any position in the rule;
  2267. it is executed at that position.  Most rules have just one action at
  2268. the end of the rule, following all the components.  Actions in the
  2269. middle of a rule are tricky and used only for special purposes (*note
  2270. Actions in Mid-Rule: Mid-Rule Actions.).
  2271.  
  2272.    The C code in an action can refer to the semantic values of the
  2273. components matched by the rule with the construct `$N', which stands for
  2274. the value of the Nth component.  The semantic value for the grouping
  2275. being constructed is `$$'.  (Bison translates both of these constructs
  2276. into array element references when it copies the actions into the parser
  2277. file.)
  2278.  
  2279.    Here is a typical example:
  2280.  
  2281.      exp:    ...
  2282.              | exp '+' exp
  2283.                  { $$ = $1 + $3; }
  2284.  
  2285. This rule constructs an `exp' from two smaller `exp' groupings
  2286. connected by a plus-sign token.  In the action, `$1' and `$3' refer to
  2287. the semantic values of the two component `exp' groupings, which are the
  2288. first and third symbols on the right hand side of the rule.  The sum is
  2289. stored into `$$' so that it becomes the semantic value of the
  2290. addition-expression just recognized by the rule.  If there were a
  2291. useful semantic value associated with the `+' token, it could be
  2292. referred to as `$2'.
  2293.  
  2294.    If you don't specify an action for a rule, Bison supplies a default:
  2295. `$$ = $1'.  Thus, the value of the first symbol in the rule becomes the
  2296. value of the whole rule.  Of course, the default rule is valid only if
  2297. the two data types match.  There is no meaningful default action for an
  2298. empty rule; every empty rule must have an explicit action unless the
  2299. rule's value does not matter.
  2300.  
  2301.    `$N' with N zero or negative is allowed for reference to tokens and
  2302. groupings on the stack *before* those that match the current rule.
  2303. This is a very risky practice, and to use it reliably you must be
  2304. certain of the context in which the rule is applied.  Here is a case in
  2305. which you can use this reliably:
  2306.  
  2307.      foo:      expr bar '+' expr  { ... }
  2308.              | expr bar '-' expr  { ... }
  2309.              ;
  2310.      
  2311.      bar:      /* empty */
  2312.              { previous_expr = $0; }
  2313.              ;
  2314.  
  2315.    As long as `bar' is used only in the fashion shown here, `$0' always
  2316. refers to the `expr' which precedes `bar' in the definition of `foo'.
  2317.  
  2318. 
  2319. File: bison,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  2320.  
  2321. Data Types of Values in Actions
  2322. -------------------------------
  2323.  
  2324.    If you have chosen a single data type for semantic values, the `$$'
  2325. and `$N' constructs always have that data type.
  2326.  
  2327.    If you have used `%union' to specify a variety of data types, then
  2328. you must declare a choice among these types for each terminal or
  2329. nonterminal symbol that can have a semantic value.  Then each time you
  2330. use `$$' or `$N', its data type is determined by which symbol it refers
  2331. to in the rule.  In this example,
  2332.  
  2333.      exp:    ...
  2334.              | exp '+' exp
  2335.                  { $$ = $1 + $3; }
  2336.  
  2337. `$1' and `$3' refer to instances of `exp', so they all have the data
  2338. type declared for the nonterminal symbol `exp'.  If `$2' were used, it
  2339. would have the data type declared for the terminal symbol `'+'',
  2340. whatever that might be.
  2341.  
  2342.    Alternatively, you can specify the data type when you refer to the
  2343. value, by inserting `<TYPE>' after the `$' at the beginning of the
  2344. reference.  For example, if you have defined types as shown here:
  2345.  
  2346.      %union {
  2347.        int itype;
  2348.        double dtype;
  2349.      }
  2350.  
  2351. then you can write `$<itype>1' to refer to the first subunit of the
  2352. rule as an integer, or `$<dtype>1' to refer to it as a double.
  2353.  
  2354. 
  2355. File: bison,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  2356.  
  2357. Actions in Mid-Rule
  2358. -------------------
  2359.  
  2360.    Occasionally it is useful to put an action in the middle of a rule.
  2361. These actions are written just like usual end-of-rule actions, but they
  2362. are executed before the parser even recognizes the following components.
  2363.  
  2364.    A mid-rule action may refer to the components preceding it using
  2365. `$N', but it may not refer to subsequent components because it is run
  2366. before they are parsed.
  2367.  
  2368.    The mid-rule action itself counts as one of the components of the
  2369. rule.  This makes a difference when there is another action later in
  2370. the same rule (and usually there is another at the end): you have to
  2371. count the actions along with the symbols when working out which number
  2372. N to use in `$N'.
  2373.  
  2374.    The mid-rule action can also have a semantic value.  The action can
  2375. set its value with an assignment to `$$', and actions later in the rule
  2376. can refer to the value using `$N'.  Since there is no symbol to name
  2377. the action, there is no way to declare a data type for the value in
  2378. advance, so you must use the `$<...>' construct to specify a data type
  2379. each time you refer to this value.
  2380.  
  2381.    There is no way to set the value of the entire rule with a mid-rule
  2382. action, because assignments to `$$' do not have that effect.  The only
  2383. way to set the value for the entire rule is with an ordinary action at
  2384. the end of the rule.
  2385.  
  2386.    Here is an example from a hypothetical compiler, handling a `let'
  2387. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  2388. create a variable named VARIABLE temporarily for the duration of
  2389. STATEMENT.  To parse this construct, we must put VARIABLE into the
  2390. symbol table while STATEMENT is parsed, then remove it afterward.  Here
  2391. is how it is done:
  2392.  
  2393.      stmt:   LET '(' var ')'
  2394.                      { $<context>$ = push_context ();
  2395.                        declare_variable ($3); }
  2396.              stmt    { $$ = $6;
  2397.                        pop_context ($<context>5); }
  2398.  
  2399. As soon as `let (VARIABLE)' has been recognized, the first action is
  2400. run.  It saves a copy of the current semantic context (the list of
  2401. accessible variables) as its semantic value, using alternative
  2402. `context' in the data-type union.  Then it calls `declare_variable' to
  2403. add the new variable to that list.  Once the first action is finished,
  2404. the embedded statement `stmt' can be parsed.  Note that the mid-rule
  2405. action is component number 5, so the `stmt' is component number 6.
  2406.  
  2407.    After the embedded statement is parsed, its semantic value becomes
  2408. the value of the entire `let'-statement.  Then the semantic value from
  2409. the earlier action is used to restore the prior list of variables.  This
  2410. removes the temporary `let'-variable from the list so that it won't
  2411. appear to exist while the rest of the program is parsed.
  2412.  
  2413.    Taking action before a rule is completely recognized often leads to
  2414. conflicts since the parser must commit to a parse in order to execute
  2415. the action.  For example, the following two rules, without mid-rule
  2416. actions, can coexist in a working parser because the parser can shift
  2417. the open-brace token and look at what follows before deciding whether
  2418. there is a declaration or not:
  2419.  
  2420.      compound: '{' declarations statements '}'
  2421.              | '{' statements '}'
  2422.              ;
  2423.  
  2424. But when we add a mid-rule action as follows, the rules become
  2425. nonfunctional:
  2426.  
  2427.      compound: { prepare_for_local_variables (); }
  2428.                '{' declarations statements '}'
  2429.              | '{' statements '}'
  2430.              ;
  2431.  
  2432. Now the parser is forced to decide whether to run the mid-rule action
  2433. when it has read no farther than the open-brace.  In other words, it
  2434. must commit to using one rule or the other, without sufficient
  2435. information to do it correctly.  (The open-brace token is what is called
  2436. the "look-ahead" token at this time, since the parser is still deciding
  2437. what to do about it.  *Note Look-Ahead Tokens: Look-Ahead.)
  2438.  
  2439.    You might think that you could correct the problem by putting
  2440. identical actions into the two rules, like this:
  2441.  
  2442.      compound: { prepare_for_local_variables (); }
  2443.                '{' declarations statements '}'
  2444.              | { prepare_for_local_variables (); }
  2445.                '{' statements '}'
  2446.              ;
  2447.  
  2448. But this does not help, because Bison does not realize that the two
  2449. actions are identical.  (Bison never tries to understand the C code in
  2450. an action.)
  2451.  
  2452.    If the grammar is such that a declaration can be distinguished from a
  2453. statement by the first token (which is true in C), then one solution
  2454. which does work is to put the action after the open-brace, like this:
  2455.  
  2456.      compound: '{' { prepare_for_local_variables (); }
  2457.                declarations statements '}'
  2458.              | '{' statements '}'
  2459.              ;
  2460.  
  2461. Now the first token of the following declaration or statement, which
  2462. would in any case tell Bison which rule to use, can still do so.
  2463.  
  2464.    Another solution is to bury the action inside a nonterminal symbol
  2465. which serves as a subroutine:
  2466.  
  2467.      subroutine: /* empty */
  2468.                { prepare_for_local_variables (); }
  2469.              ;
  2470.      
  2471.      compound: subroutine
  2472.                '{' declarations statements '}'
  2473.              | subroutine
  2474.                '{' statements '}'
  2475.              ;
  2476.  
  2477. Now Bison can execute the action in the rule for `subroutine' without
  2478. deciding which rule for `compound' it will eventually use.  Note that
  2479. the action is now at the end of its rule.  Any mid-rule action can be
  2480. converted to an end-of-rule action in this way, and this is what Bison
  2481. actually does to implement mid-rule actions.
  2482.  
  2483. 
  2484. File: bison,  Node: Declarations,  Next: Multiple Parsers,  Prev: Semantics,  Up: Grammar File
  2485.  
  2486. Bison Declarations
  2487. ==================
  2488.  
  2489.    The "Bison declarations" section of a Bison grammar defines the
  2490. symbols used in formulating the grammar and the data types of semantic
  2491. values.  *Note Symbols::.
  2492.  
  2493.    All token type names (but not single-character literal tokens such as
  2494. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  2495. declared if you need to specify which data type to use for the semantic
  2496. value (*note More Than One Value Type: Multiple Types.).
  2497.  
  2498.    The first rule in the file also specifies the start symbol, by
  2499. default.  If you want some other symbol to be the start symbol, you
  2500. must declare it explicitly (*note Languages and Context-Free Grammars:
  2501. Language and Grammar.).
  2502.  
  2503. * Menu:
  2504.  
  2505. * Token Decl::        Declaring terminal symbols.
  2506. * Precedence Decl::   Declaring terminals with precedence and associativity.
  2507. * Union Decl::        Declaring the set of all semantic value types.
  2508. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  2509. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  2510. * Start Decl::        Specifying the start symbol.
  2511. * Pure Decl::         Requesting a reentrant parser.
  2512. * Decl Summary::      Table of all Bison declarations.
  2513.  
  2514. 
  2515. File: bison,  Node: Token Decl,  Next: Precedence Decl,  Up: Declarations
  2516.  
  2517. Token Type Names
  2518. ----------------
  2519.  
  2520.    The basic way to declare a token type name (terminal symbol) is as
  2521. follows:
  2522.  
  2523.      %token NAME
  2524.  
  2525.    Bison will convert this into a `#define' directive in the parser, so
  2526. that the function `yylex' (if it is in this file) can use the name NAME
  2527. to stand for this token type's code.
  2528.  
  2529.    Alternatively, you can use `%left', `%right', or `%nonassoc' instead
  2530. of `%token', if you wish to specify precedence.  *Note Operator
  2531. Precedence: Precedence Decl.
  2532.  
  2533.    You can explicitly specify the numeric code for a token type by
  2534. appending an integer value in the field immediately following the token
  2535. name:
  2536.  
  2537.      %token NUM 300
  2538.  
  2539. It is generally best, however, to let Bison choose the numeric codes for
  2540. all token types.  Bison will automatically select codes that don't
  2541. conflict with each other or with ASCII characters.
  2542.  
  2543.    In the event that the stack type is a union, you must augment the
  2544. `%token' or other token declaration to include the data type
  2545. alternative delimited by angle-brackets (*note More Than One Value
  2546. Type: Multiple Types.).
  2547.  
  2548.    For example:
  2549.  
  2550.      %union {              /* define stack type */
  2551.        double val;
  2552.        symrec *tptr;
  2553.      }
  2554.      %token <val> NUM      /* define token NUM and its type */
  2555.  
  2556. 
  2557. File: bison,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  2558.  
  2559. Operator Precedence
  2560. -------------------
  2561.  
  2562.    Use the `%left', `%right' or `%nonassoc' declaration to declare a
  2563. token and specify its precedence and associativity, all at once.  These
  2564. are called "precedence declarations".  *Note Operator Precedence:
  2565. Precedence, for general information on operator precedence.
  2566.  
  2567.    The syntax of a precedence declaration is the same as that of
  2568. `%token': either
  2569.  
  2570.      %left SYMBOLS...
  2571.  
  2572. or
  2573.  
  2574.      %left <TYPE> SYMBOLS...
  2575.  
  2576.    And indeed any of these declarations serves the purposes of `%token'.
  2577. But in addition, they specify the associativity and relative precedence
  2578. for all the SYMBOLS:
  2579.  
  2580.    * The associativity of an operator OP determines how repeated uses
  2581.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  2582.      X with Y first or by grouping Y with Z first.  `%left' specifies
  2583.      left-associativity (grouping X with Y first) and `%right'
  2584.      specifies right-associativity (grouping Y with Z first).
  2585.      `%nonassoc' specifies no associativity, which means that `X OP Y
  2586.      OP Z' is considered a syntax error.
  2587.  
  2588.    * The precedence of an operator determines how it nests with other
  2589.      operators.  All the tokens declared in a single precedence
  2590.      declaration have equal precedence and nest together according to
  2591.      their associativity.  When two tokens declared in different
  2592.      precedence declarations associate, the one declared later has the
  2593.      higher precedence and is grouped first.
  2594.  
  2595. 
  2596. File: bison,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  2597.  
  2598. The Collection of Value Types
  2599. -----------------------------
  2600.  
  2601.    The `%union' declaration specifies the entire collection of possible
  2602. data types for semantic values.  The keyword `%union' is followed by a
  2603. pair of braces containing the same thing that goes inside a `union' in
  2604. C.
  2605.  
  2606.    For example:
  2607.  
  2608.      %union {
  2609.        double val;
  2610.        symrec *tptr;
  2611.      }
  2612.  
  2613. This says that the two alternative types are `double' and `symrec *'.
  2614. They are given names `val' and `tptr'; these names are used in the
  2615. `%token' and `%type' declarations to pick one of the types for a
  2616. terminal or nonterminal symbol (*note Nonterminal Symbols: Type Decl.).
  2617.  
  2618.    Note that, unlike making a `union' declaration in C, you do not write
  2619. a semicolon after the closing brace.
  2620.  
  2621. 
  2622. File: bison,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  2623.  
  2624. Nonterminal Symbols
  2625. -------------------
  2626.  
  2627. When you use `%union' to specify multiple value types, you must declare
  2628. the value type of each nonterminal symbol for which values are used.
  2629. This is done with a `%type' declaration, like this:
  2630.  
  2631.      %type <TYPE> NONTERMINAL...
  2632.  
  2633. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  2634. name given in the `%union' to the alternative that you want (*note The
  2635. Collection of Value Types: Union Decl.).  You can give any number of
  2636. nonterminal symbols in the same `%type' declaration, if they have the
  2637. same value type.  Use spaces to separate the symbol names.
  2638.  
  2639. 
  2640. File: bison,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  2641.  
  2642. Suppressing Conflict Warnings
  2643. -----------------------------
  2644.  
  2645.    Bison normally warns if there are any conflicts in the grammar
  2646. (*note Shift/Reduce Conflicts: Shift/Reduce.), but most real grammars
  2647. have harmless shift/reduce conflicts which are resolved in a
  2648. predictable way and would be difficult to eliminate.  It is desirable
  2649. to suppress the warning about these conflicts unless the number of
  2650. conflicts changes.  You can do this with the `%expect' declaration.
  2651.  
  2652.    The declaration looks like this:
  2653.  
  2654.      %expect N
  2655.  
  2656.    Here N is a decimal integer.  The declaration says there should be no
  2657. warning if there are N shift/reduce conflicts and no reduce/reduce
  2658. conflicts.  The usual warning is given if there are either more or fewer
  2659. conflicts, or if there are any reduce/reduce conflicts.
  2660.  
  2661.    In general, using `%expect' involves these steps:
  2662.  
  2663.    * Compile your grammar without `%expect'.  Use the `-v' option to
  2664.      get a verbose list of where the conflicts occur.  Bison will also
  2665.      print the number of conflicts.
  2666.  
  2667.    * Check each of the conflicts to make sure that Bison's default
  2668.      resolution is what you really want.  If not, rewrite the grammar
  2669.      and go back to the beginning.
  2670.  
  2671.    * Add an `%expect' declaration, copying the number N from the number
  2672.      which Bison printed.
  2673.  
  2674.    Now Bison will stop annoying you about the conflicts you have
  2675. checked, but it will warn you again if changes in the grammar result in
  2676. additional conflicts.
  2677.  
  2678. 
  2679. File: bison,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  2680.  
  2681. The Start-Symbol
  2682. ----------------
  2683.  
  2684.    Bison assumes by default that the start symbol for the grammar is
  2685. the first nonterminal specified in the grammar specification section.
  2686. The programmer may override this restriction with the `%start'
  2687. declaration as follows:
  2688.  
  2689.      %start SYMBOL
  2690.  
  2691. 
  2692. File: bison,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  2693.  
  2694. A Pure (Reentrant) Parser
  2695. -------------------------
  2696.  
  2697.    A "reentrant" program is one which does not alter in the course of
  2698. execution; in other words, it consists entirely of "pure" (read-only)
  2699. code.  Reentrancy is important whenever asynchronous execution is
  2700. possible; for example, a nonreentrant program may not be safe to call
  2701. from a signal handler.  In systems with multiple threads of control, a
  2702. nonreentrant program must be called only within interlocks.
  2703.  
  2704.    The Bison parser is not normally a reentrant program, because it uses
  2705. statically allocated variables for communication with `yylex'.  These
  2706. variables include `yylval' and `yylloc'.
  2707.  
  2708.    The Bison declaration `%pure_parser' says that you want the parser
  2709. to be reentrant.  It looks like this:
  2710.  
  2711.      %pure_parser
  2712.  
  2713.    The effect is that the two communication variables become local
  2714. variables in `yyparse', and a different calling convention is used for
  2715. the lexical analyzer function `yylex'.  *Note Calling for Pure Parsers:
  2716. Pure Calling, for the details of this.  The variable `yynerrs' also
  2717. becomes local in `yyparse' (*note The Error Reporting Function
  2718. `yyerror': Error Reporting.).  The convention for calling `yyparse'
  2719. itself is unchanged.
  2720.  
  2721. 
  2722. File: bison,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  2723.  
  2724. Bison Declaration Summary
  2725. -------------------------
  2726.  
  2727.    Here is a summary of all Bison declarations:
  2728.  
  2729. `%union'
  2730.      Declare the collection of data types that semantic values may have
  2731.      (*note The Collection of Value Types: Union Decl.).
  2732.  
  2733. `%token'
  2734.      Declare a terminal symbol (token type name) with no precedence or
  2735.      associativity specified (*note Token Type Names: Token Decl.).
  2736.  
  2737. `%right'
  2738.      Declare a terminal symbol (token type name) that is
  2739.      right-associative (*note Operator Precedence: Precedence Decl.).
  2740.  
  2741. `%left'
  2742.      Declare a terminal symbol (token type name) that is
  2743.      left-associative (*note Operator Precedence: Precedence Decl.).
  2744.  
  2745. `%nonassoc'
  2746.      Declare a terminal symbol (token type name) that is nonassociative
  2747.      (using it in a way that would be associative is a syntax error)
  2748.      (*note Operator Precedence: Precedence Decl.).
  2749.  
  2750. `%type'
  2751.      Declare the type of semantic values for a nonterminal symbol
  2752.      (*note Nonterminal Symbols: Type Decl.).
  2753.  
  2754. `%start'
  2755.      Specify the grammar's start symbol (*note The Start-Symbol: Start
  2756.      Decl.).
  2757.  
  2758. `%expect'
  2759.      Declare the expected number of shift-reduce conflicts (*note
  2760.      Suppressing Conflict Warnings: Expect Decl.).
  2761.  
  2762. `%pure_parser'
  2763.      Request a pure (reentrant) parser program (*note A Pure
  2764.      (Reentrant) Parser: Pure Decl.).
  2765.  
  2766. 
  2767. File: bison,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  2768.  
  2769. Multiple Parsers in the Same Program
  2770. ====================================
  2771.  
  2772.    Most programs that use Bison parse only one language and therefore
  2773. contain only one Bison parser.  But what if you want to parse more than
  2774. one language with the same program?  Then you need to avoid a name
  2775. conflict between different definitions of `yyparse', `yylval', and so
  2776. on.
  2777.  
  2778.    The easy way to do this is to use the option `-p PREFIX' (*note
  2779. Invoking Bison: Invocation.).  This renames the interface functions and
  2780. variables of the Bison parser to start with PREFIX instead of `yy'.
  2781. You can use this to give each parser distinct names that do not
  2782. conflict.
  2783.  
  2784.    The precise list of symbols renamed is `yyparse', `yylex',
  2785. `yyerror', `yylval', `yychar' and `yydebug'.  For example, if you use
  2786. `-p c', the names become `cparse', `clex', and so on.
  2787.  
  2788.    *All the other variables and macros associated with Bison are not
  2789. renamed.* These others are not global; there is no conflict if the same
  2790. name is used in different parsers.  For example, `YYSTYPE' is not
  2791. renamed, but defining this in different ways in different parsers causes
  2792. no trouble (*note Data Types of Semantic Values: Value Type.).
  2793.  
  2794.    The `-p' option works by adding macro definitions to the beginning
  2795. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  2796. on.  This effectively substitutes one name for the other in the entire
  2797. parser file.
  2798.  
  2799. 
  2800. File: bison,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  2801.  
  2802. Parser C-Language Interface
  2803. ***************************
  2804.  
  2805.    The Bison parser is actually a C function named `yyparse'.  Here we
  2806. describe the interface conventions of `yyparse' and the other functions
  2807. that it needs to use.
  2808.  
  2809.    Keep in mind that the parser uses many C identifiers starting with
  2810. `yy' and `YY' for internal purposes.  If you use such an identifier
  2811. (aside from those in this manual) in an action or in additional C code
  2812. in the grammar file, you are likely to run into trouble.
  2813.  
  2814. * Menu:
  2815.  
  2816. * Parser Function::   How to call `yyparse' and what it returns.
  2817. * Lexical::           You must supply a function `yylex'
  2818.                         which reads tokens.
  2819. * Error Reporting::   You must supply a function `yyerror'.
  2820. * Action Features::   Special features for use in actions.
  2821.  
  2822. 
  2823. File: bison,  Node: Parser Function,  Next: Lexical,  Up: Interface
  2824.  
  2825. The Parser Function `yyparse'
  2826. =============================
  2827.  
  2828.    You call the function `yyparse' to cause parsing to occur.  This
  2829. function reads tokens, executes actions, and ultimately returns when it
  2830. encounters end-of-input or an unrecoverable syntax error.  You can also
  2831. write an action which directs `yyparse' to return immediately without
  2832. reading further.
  2833.  
  2834.    The value returned by `yyparse' is 0 if parsing was successful
  2835. (return is due to end-of-input).
  2836.  
  2837.    The value is 1 if parsing failed (return is due to a syntax error).
  2838.  
  2839.    In an action, you can cause immediate return from `yyparse' by using
  2840. these macros:
  2841.  
  2842. `YYACCEPT'
  2843.      Return immediately with value 0 (to report success).
  2844.  
  2845. `YYABORT'
  2846.      Return immediately with value 1 (to report failure).
  2847.  
  2848. 
  2849. File: bison,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  2850.  
  2851. The Lexical Analyzer Function `yylex'
  2852. =====================================
  2853.  
  2854.    The "lexical analyzer" function, `yylex', recognizes tokens from the
  2855. input stream and returns them to the parser.  Bison does not create
  2856. this function automatically; you must write it so that `yyparse' can
  2857. call it.  The function is sometimes referred to as a lexical scanner.
  2858.  
  2859.    In simple programs, `yylex' is often defined at the end of the Bison
  2860. grammar file.  If `yylex' is defined in a separate source file, you
  2861. need to arrange for the token-type macro definitions to be available
  2862. there.  To do this, use the `-d' option when you run Bison, so that it
  2863. will write these macro definitions into a separate header file
  2864. `NAME.tab.h' which you can include in the other source files that need
  2865. it.  *Note Invoking Bison: Invocation.
  2866.  
  2867. * Menu:
  2868.  
  2869. * Calling Convention::  How `yyparse' calls `yylex'.
  2870. * Token Values::      How `yylex' must return the semantic value
  2871.                         of the token it has read.
  2872. * Token Positions::   How `yylex' must return the text position
  2873.                         (line number, etc.) of the token, if the
  2874.                         actions want that.
  2875. * Pure Calling::      How the calling convention differs
  2876.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  2877.  
  2878. 
  2879. File: bison,  Node: Calling Convention,  Next: Token Values,  Up: Lexical
  2880.  
  2881. Calling Convention for `yylex'
  2882. ------------------------------
  2883.  
  2884.    The value that `yylex' returns must be the numeric code for the type
  2885. of token it has just found, or 0 for end-of-input.
  2886.  
  2887.    When a token is referred to in the grammar rules by a name, that name
  2888. in the parser file becomes a C macro whose definition is the proper
  2889. numeric code for that token type.  So `yylex' can use the name to
  2890. indicate that type.  *Note Symbols::.
  2891.  
  2892.    When a token is referred to in the grammar rules by a character
  2893. literal, the numeric code for that character is also the code for the
  2894. token type.  So `yylex' can simply return that character code.  The
  2895. null character must not be used this way, because its code is zero and
  2896. that is what signifies end-of-input.
  2897.  
  2898.    Here is an example showing these things:
  2899.  
  2900.      yylex ()
  2901.      {
  2902.        ...
  2903.        if (c == EOF)     /* Detect end of file. */
  2904.          return 0;
  2905.        ...
  2906.        if (c == '+' || c == '-')
  2907.          return c;      /* Assume token type for `+' is '+'. */
  2908.        ...
  2909.        return INT;      /* Return the type of the token. */
  2910.        ...
  2911.      }
  2912.  
  2913. This interface has been designed so that the output from the `lex'
  2914. utility can be used without change as the definition of `yylex'.
  2915.  
  2916. 
  2917. File: bison,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  2918.  
  2919. Semantic Values of Tokens
  2920. -------------------------
  2921.  
  2922.    In an ordinary (nonreentrant) parser, the semantic value of the
  2923. token must be stored into the global variable `yylval'.  When you are
  2924. using just one data type for semantic values, `yylval' has that type.
  2925. Thus, if the type is `int' (the default), you might write this in
  2926. `yylex':
  2927.  
  2928.        ...
  2929.        yylval = value;  /* Put value onto Bison stack. */
  2930.        return INT;      /* Return the type of the token. */
  2931.        ...
  2932.  
  2933.    When you are using multiple data types, `yylval''s type is a union
  2934. made from the `%union' declaration (*note The Collection of Value
  2935. Types: Union Decl.).  So when you store a token's value, you must use
  2936. the proper member of the union.  If the `%union' declaration looks like
  2937. this:
  2938.  
  2939.      %union {
  2940.        int intval;
  2941.        double val;
  2942.        symrec *tptr;
  2943.      }
  2944.  
  2945. then the code in `yylex' might look like this:
  2946.  
  2947.        ...
  2948.        yylval.intval = value; /* Put value onto Bison stack. */
  2949.        return INT;          /* Return the type of the token. */
  2950.        ...
  2951.  
  2952. 
  2953. File: bison,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  2954.  
  2955. Textual Positions of Tokens
  2956. ---------------------------
  2957.  
  2958.    If you are using the `@N'-feature (*note Special Features for Use in
  2959. Actions: Action Features.) in actions to keep track of the textual
  2960. locations of tokens and groupings, then you must provide this
  2961. information in `yylex'.  The function `yyparse' expects to find the
  2962. textual location of a token just parsed in the global variable
  2963. `yylloc'.  So `yylex' must store the proper data in that variable.  The
  2964. value of `yylloc' is a structure and you need only initialize the
  2965. members that are going to be used by the actions.  The four members are
  2966. called `first_line', `first_column', `last_line' and `last_column'.
  2967. Note that the use of this feature makes the parser noticeably slower.
  2968.  
  2969.    The data type of `yylloc' has the name `YYLTYPE'.
  2970.  
  2971. 
  2972. File: bison,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  2973.  
  2974. Calling for Pure Parsers
  2975. ------------------------
  2976.  
  2977.    When you use the Bison declaration `%pure_parser' to request a pure,
  2978. reentrant parser, the global communication variables `yylval' and
  2979. `yylloc' cannot be used.  (*Note A Pure (Reentrant) Parser: Pure Decl.)
  2980. In such parsers the two global variables are replaced by pointers
  2981. passed as arguments to `yylex'.  You must declare them as shown here,
  2982. and pass the information back by storing it through those pointers.
  2983.  
  2984.      yylex (lvalp, llocp)
  2985.           YYSTYPE *lvalp;
  2986.           YYLTYPE *llocp;
  2987.      {
  2988.        ...
  2989.        *lvalp = value;  /* Put value onto Bison stack.  */
  2990.        return INT;      /* Return the type of the token.  */
  2991.        ...
  2992.      }
  2993.  
  2994.    If the grammar file does not use the `@' constructs to refer to
  2995. textual positions, then the type `YYLTYPE' will not be defined.  In
  2996. this case, omit the second argument; `yylex' will be called with only
  2997. one argument.
  2998.  
  2999. 
  3000. File: bison,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  3001.  
  3002. The Error Reporting Function `yyerror'
  3003. ======================================
  3004.  
  3005.    The Bison parser detects a "parse error" or "syntax error" whenever
  3006. it reads a token which cannot satisfy any syntax rule.  A action in the
  3007. grammar can also explicitly proclaim an error, using the macro
  3008. `YYERROR' (*note Special Features for Use in Actions: Action Features.).
  3009.  
  3010.    The Bison parser expects to report the error by calling an error
  3011. reporting function named `yyerror', which you must supply.  It is
  3012. called by `yyparse' whenever a syntax error is found, and it receives
  3013. one argument.  For a parse error, the string is normally
  3014. `"parse error"'.
  3015.  
  3016.    If you define the macro `YYERROR_VERBOSE' in the Bison declarations
  3017. section (*note The Bison Declarations Section: Bison Declarations.),
  3018. then Bison provides a more verbose and specific error message string
  3019. instead of just plain `"parse error"'.  It doesn't matter what
  3020. definition you use for `YYERROR_VERBOSE', just whether you define it.
  3021.  
  3022.    The parser can detect one other kind of error: stack overflow.  This
  3023. happens when the input contains constructions that are very deeply
  3024. nested.  It isn't likely you will encounter this, since the Bison
  3025. parser extends its stack automatically up to a very large limit.  But
  3026. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  3027. except that the argument string is `"parser stack overflow"'.
  3028.  
  3029.    The following definition suffices in simple programs:
  3030.  
  3031.      yyerror (s)
  3032.           char *s;
  3033.      {
  3034.        fprintf (stderr, "%s\n", s);
  3035.      }
  3036.  
  3037.    After `yyerror' returns to `yyparse', the latter will attempt error
  3038. recovery if you have written suitable error recovery grammar rules
  3039. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  3040. immediately return 1.
  3041.  
  3042.    The variable `yynerrs' contains the number of syntax errors
  3043. encountered so far.  Normally this variable is global; but if you
  3044. request a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.)
  3045. then it is a local variable which only the actions can access.
  3046.  
  3047. 
  3048. File: bison,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  3049.  
  3050. Special Features for Use in Actions
  3051. ===================================
  3052.  
  3053.    Here is a table of Bison constructs, variables and macros that are
  3054. useful in actions.
  3055.  
  3056. `$$'
  3057.      Acts like a variable that contains the semantic value for the
  3058.      grouping made by the current rule.  *Note Actions::.
  3059.  
  3060. `$N'
  3061.      Acts like a variable that contains the semantic value for the Nth
  3062.      component of the current rule.  *Note Actions::.
  3063.  
  3064. `$<TYPEALT>$'
  3065.      Like `$$' but specifies alternative TYPEALT in the union specified
  3066.      by the `%union' declaration.  *Note Data Types of Values in
  3067.      Actions: Action Types.
  3068.  
  3069. `$<TYPEALT>N'
  3070.      Like `$N' but specifies alternative TYPEALT in the union specified
  3071.      by the `%union' declaration.  *Note Data Types of Values in
  3072.      Actions: Action Types.
  3073.  
  3074. `YYABORT;'
  3075.      Return immediately from `yyparse', indicating failure.  *Note The
  3076.      Parser Function `yyparse': Parser Function.
  3077.  
  3078. `YYACCEPT;'
  3079.      Return immediately from `yyparse', indicating success.  *Note The
  3080.      Parser Function `yyparse': Parser Function.
  3081.  
  3082. `YYBACKUP (TOKEN, VALUE);'
  3083.      Unshift a token.  This macro is allowed only for rules that reduce
  3084.      a single value, and only when there is no look-ahead token.  It
  3085.      installs a look-ahead token with token type TOKEN and semantic
  3086.      value VALUE; then it discards the value that was going to be
  3087.      reduced by this rule.
  3088.  
  3089.      If the macro is used when it is not valid, such as when there is a
  3090.      look-ahead token already, then it reports a syntax error with a
  3091.      message `cannot back up' and performs ordinary error recovery.
  3092.  
  3093.      In either case, the rest of the action is not executed.
  3094.  
  3095. `YYEMPTY'
  3096.      Value stored in `yychar' when there is no look-ahead token.
  3097.  
  3098. `YYERROR;'
  3099.      Cause an immediate syntax error.  This statement initiates error
  3100.      recovery just as if the parser itself had detected an error;
  3101.      however, it does not call `yyerror', and does not print any
  3102.      message.  If you want to print an error message, call `yyerror'
  3103.      explicitly before the `YYERROR;' statement.  *Note Error
  3104.      Recovery::.
  3105.  
  3106. `YYRECOVERING'
  3107.      This macro stands for an expression that has the value 1 when the
  3108.      parser is recovering from a syntax error, and 0 the rest of the
  3109.      time.  *Note Error Recovery::.
  3110.  
  3111. `yychar'
  3112.      Variable containing the current look-ahead token.  (In a pure
  3113.      parser, this is actually a local variable within `yyparse'.)  When
  3114.      there is no look-ahead token, the value `YYEMPTY' is stored in the
  3115.      variable.  *Note Look-Ahead Tokens: Look-Ahead.
  3116.  
  3117. `yyclearin;'
  3118.      Discard the current look-ahead token.  This is useful primarily in
  3119.      error rules.  *Note Error Recovery::.
  3120.  
  3121. `yyerrok;'
  3122.      Resume generating error messages immediately for subsequent syntax
  3123.      errors.  This is useful primarily in error rules.  *Note Error
  3124.      Recovery::.
  3125.  
  3126. `@N'
  3127.      Acts like a structure variable containing information on the line
  3128.      numbers and column numbers of the Nth component of the current
  3129.      rule.  The structure has four members, like this:
  3130.  
  3131.           struct {
  3132.             int first_line, last_line;
  3133.             int first_column, last_column;
  3134.           };
  3135.  
  3136.      Thus, to get the starting line number of the third component, use
  3137.      `@3.first_line'.
  3138.  
  3139.      In order for the members of this structure to contain valid
  3140.      information, you must make `yylex' supply this information about
  3141.      each token.  If you need only certain members, then `yylex' need
  3142.      only fill in those members.
  3143.  
  3144.      The use of this feature makes the parser noticeably slower.
  3145.  
  3146. 
  3147. File: bison,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  3148.  
  3149. The Bison Parser Algorithm
  3150. **************************
  3151.  
  3152.    As Bison reads tokens, it pushes them onto a stack along with their
  3153. semantic values.  The stack is called the "parser stack".  Pushing a
  3154. token is traditionally called "shifting".
  3155.  
  3156.    For example, suppose the infix calculator has read `1 + 5 *', with a
  3157. `3' to come.  The stack will have four elements, one for each token
  3158. that was shifted.
  3159.  
  3160.    But the stack does not always have an element for each token read.
  3161. When the last N tokens and groupings shifted match the components of a
  3162. grammar rule, they can be combined according to that rule.  This is
  3163. called "reduction".  Those tokens and groupings are replaced on the
  3164. stack by a single grouping whose symbol is the result (left hand side)
  3165. of that rule.  Running the rule's action is part of the process of
  3166. reduction, because this is what computes the semantic value of the
  3167. resulting grouping.
  3168.  
  3169.    For example, if the infix calculator's parser stack contains this:
  3170.  
  3171.      1 + 5 * 3
  3172.  
  3173. and the next input token is a newline character, then the last three
  3174. elements can be reduced to 15 via the rule:
  3175.  
  3176.      expr: expr '*' expr;
  3177.  
  3178. Then the stack contains just these three elements:
  3179.  
  3180.      1 + 15
  3181.  
  3182. At this point, another reduction can be made, resulting in the single
  3183. value 16.  Then the newline token can be shifted.
  3184.  
  3185.    The parser tries, by shifts and reductions, to reduce the entire
  3186. input down to a single grouping whose symbol is the grammar's
  3187. start-symbol (*note Languages and Context-Free Grammars: Language and
  3188. Grammar.).
  3189.  
  3190.    This kind of parser is known in the literature as a bottom-up parser.
  3191.  
  3192. * Menu:
  3193.  
  3194. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  3195. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  3196. * Precedence::        Operator precedence works by resolving conflicts.
  3197. * Contextual Precedence::  When an operator's precedence depends on context.
  3198. * Parser States::     The parser is a finite-state-machine with stack.
  3199. * Reduce/Reduce::     When two rules are applicable in the same situation.
  3200. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  3201. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  3202.  
  3203. 
  3204. File: bison,  Node: Look-Ahead,  Next: Shift/Reduce,  Up: Algorithm
  3205.  
  3206. Look-Ahead Tokens
  3207. =================
  3208.  
  3209.    The Bison parser does *not* always reduce immediately as soon as the
  3210. last N tokens and groupings match a rule.  This is because such a
  3211. simple strategy is inadequate to handle most languages.  Instead, when a
  3212. reduction is possible, the parser sometimes "looks ahead" at the next
  3213. token in order to decide what to do.
  3214.  
  3215.    When a token is read, it is not immediately shifted; first it
  3216. becomes the "look-ahead token", which is not on the stack.  Now the
  3217. parser can perform one or more reductions of tokens and groupings on
  3218. the stack, while the look-ahead token remains off to the side.  When no
  3219. more reductions should take place, the look-ahead token is shifted onto
  3220. the stack.  This does not mean that all possible reductions have been
  3221. done; depending on the token type of the look-ahead token, some rules
  3222. may choose to delay their application.
  3223.  
  3224.    Here is a simple case where look-ahead is needed.  These three rules
  3225. define expressions which contain binary addition operators and postfix
  3226. unary factorial operators (`!'), and allow parentheses for grouping.
  3227.  
  3228.      expr:     term '+' expr
  3229.              | term
  3230.              ;
  3231.      
  3232.      term:     '(' expr ')'
  3233.              | term '!'
  3234.              | NUMBER
  3235.              ;
  3236.  
  3237.    Suppose that the tokens `1 + 2' have been read and shifted; what
  3238. should be done?  If the following token is `)', then the first three
  3239. tokens must be reduced to form an `expr'.  This is the only valid
  3240. course, because shifting the `)' would produce a sequence of symbols
  3241. `term ')'', and no rule allows this.
  3242.  
  3243.    If the following token is `!', then it must be shifted immediately so
  3244. that `2 !' can be reduced to make a `term'.  If instead the parser were
  3245. to reduce before shifting, `1 + 2' would become an `expr'.  It would
  3246. then be impossible to shift the `!' because doing so would produce on
  3247. the stack the sequence of symbols `expr '!''.  No rule allows that
  3248. sequence.
  3249.  
  3250.    The current look-ahead token is stored in the variable `yychar'.
  3251. *Note Special Features for Use in Actions: Action Features.
  3252.  
  3253. 
  3254. File: bison,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  3255.  
  3256. Shift/Reduce Conflicts
  3257. ======================
  3258.  
  3259.    Suppose we are parsing a language which has if-then and if-then-else
  3260. statements, with a pair of rules like this:
  3261.  
  3262.      if_stmt:
  3263.                IF expr THEN stmt
  3264.              | IF expr THEN stmt ELSE stmt
  3265.              ;
  3266.  
  3267. Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  3268. specific keyword tokens.
  3269.  
  3270.    When the `ELSE' token is read and becomes the look-ahead token, the
  3271. contents of the stack (assuming the input is valid) are just right for
  3272. reduction by the first rule.  But it is also legitimate to shift the
  3273. `ELSE', because that would lead to eventual reduction by the second
  3274. rule.
  3275.  
  3276.    This situation, where either a shift or a reduction would be valid,
  3277. is called a "shift/reduce conflict".  Bison is designed to resolve
  3278. these conflicts by choosing to shift, unless otherwise directed by
  3279. operator precedence declarations.  To see the reason for this, let's
  3280. contrast it with the other alternative.
  3281.  
  3282.    Since the parser prefers to shift the `ELSE', the result is to attach
  3283. the else-clause to the innermost if-statement, making these two inputs
  3284. equivalent:
  3285.  
  3286.      if x then if y then win (); else lose;
  3287.      
  3288.      if x then do; if y then win (); else lose; end;
  3289.  
  3290.    But if the parser chose to reduce when possible rather than shift,
  3291. the result would be to attach the else-clause to the outermost
  3292. if-statement, making these two inputs equivalent:
  3293.  
  3294.      if x then if y then win (); else lose;
  3295.      
  3296.      if x then do; if y then win (); end; else lose;
  3297.  
  3298.    The conflict exists because the grammar as written is ambiguous:
  3299. either parsing of the simple nested if-statement is legitimate.  The
  3300. established convention is that these ambiguities are resolved by
  3301. attaching the else-clause to the innermost if-statement; this is what
  3302. Bison accomplishes by choosing to shift rather than reduce.  (It would
  3303. ideally be cleaner to write an unambiguous grammar, but that is very
  3304. hard to do in this case.) This particular ambiguity was first
  3305. encountered in the specifications of Algol 60 and is called the
  3306. "dangling `else'" ambiguity.
  3307.  
  3308.    To avoid warnings from Bison about predictable, legitimate
  3309. shift/reduce conflicts, use the `%expect N' declaration.  There will be
  3310. no warning as long as the number of shift/reduce conflicts is exactly N.
  3311. *Note Suppressing Conflict Warnings: Expect Decl.
  3312.  
  3313.    The definition of `if_stmt' above is solely to blame for the
  3314. conflict, but the conflict does not actually appear without additional
  3315. rules.  Here is a complete Bison input file that actually manifests the
  3316. conflict:
  3317.  
  3318.      %token IF THEN ELSE variable
  3319.      %%
  3320.      stmt:     expr
  3321.              | if_stmt
  3322.              ;
  3323.      
  3324.      if_stmt:
  3325.                IF expr THEN stmt
  3326.              | IF expr THEN stmt ELSE stmt
  3327.              ;
  3328.      
  3329.      expr:     variable
  3330.              ;
  3331.  
  3332. 
  3333. File: bison,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  3334.  
  3335. Operator Precedence
  3336. ===================
  3337.  
  3338.    Another situation where shift/reduce conflicts appear is in
  3339. arithmetic expressions.  Here shifting is not always the preferred
  3340. resolution; the Bison declarations for operator precedence allow you to
  3341. specify when to shift and when to reduce.
  3342.  
  3343. * Menu:
  3344.  
  3345. * Why Precedence::    An example showing why precedence is needed.
  3346. * Using Precedence::  How to specify precedence in Bison grammars.
  3347. * Precedence Examples::  How these features are used in the previous example.
  3348. * How Precedence::    How they work.
  3349.  
  3350. 
  3351. File: bison,  Node: Why Precedence,  Next: Using Precedence,  Up: Precedence
  3352.  
  3353. When Precedence is Needed
  3354. -------------------------
  3355.  
  3356.    Consider the following ambiguous grammar fragment (ambiguous because
  3357. the input `1 - 2 * 3' can be parsed in two different ways):
  3358.  
  3359.      expr:     expr '-' expr
  3360.              | expr '*' expr
  3361.              | expr '<' expr
  3362.              | '(' expr ')'
  3363.              ...
  3364.              ;
  3365.  
  3366. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  3367. reduce them via the rule for the addition operator?  It depends on the
  3368. next token.  Of course, if the next token is `)', we must reduce;
  3369. shifting is invalid because no single rule can reduce the token
  3370. sequence `- 2 )' or anything starting with that.  But if the next token
  3371. is `*' or `<', we have a choice: either shifting or reduction would
  3372. allow the parse to complete, but with different results.
  3373.  
  3374.    To decide which one Bison should do, we must consider the results.
  3375. If the next operator token OP is shifted, then it must be reduced first
  3376. in order to permit another opportunity to reduce the sum.  The result
  3377. is (in effect) `1 - (2 OP 3)'.  On the other hand, if the subtraction
  3378. is reduced before shifting OP, the result is `(1 - 2) OP 3'.  Clearly,
  3379. then, the choice of shift or reduce should depend on the relative
  3380. precedence of the operators `-' and OP: `*' should be shifted first,
  3381. but not `<'.
  3382.  
  3383.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  3384. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  3385. former, which is called "left association".  The latter alternative,
  3386. "right association", is desirable for assignment operators.  The choice
  3387. of left or right association is a matter of whether the parser chooses
  3388. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  3389. token is `-': shifting makes right-associativity.
  3390.  
  3391. 
  3392. File: bison,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  3393.  
  3394. Specifying Operator Precedence
  3395. ------------------------------
  3396.  
  3397.    Bison allows you to specify these choices with the operator
  3398. precedence declarations `%left' and `%right'.  Each such declaration
  3399. contains a list of tokens, which are operators whose precedence and
  3400. associativity is being declared.  The `%left' declaration makes all
  3401. those operators left-associative and the `%right' declaration makes
  3402. them right-associative.  A third alternative is `%nonassoc', which
  3403. declares that it is a syntax error to find the same operator twice "in a
  3404. row".
  3405.  
  3406.    The relative precedence of different operators is controlled by the
  3407. order in which they are declared.  The first `%left' or `%right'
  3408. declaration in the file declares the operators whose precedence is
  3409. lowest, the next such declaration declares the operators whose
  3410. precedence is a little higher, and so on.
  3411.  
  3412. 
  3413. File: bison,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  3414.  
  3415. Precedence Examples
  3416. -------------------
  3417.  
  3418.    In our example, we would want the following declarations:
  3419.  
  3420.      %left '<'
  3421.      %left '-'
  3422.      %left '*'
  3423.  
  3424.    In a more complete example, which supports other operators as well,
  3425. we would declare them in groups of equal precedence.  For example,
  3426. `'+'' is declared with `'-'':
  3427.  
  3428.      %left '<' '>' '=' NE LE GE
  3429.      %left '+' '-'
  3430.      %left '*' '/'
  3431.  
  3432. (Here `NE' and so on stand for the operators for "not equal" and so on.
  3433. We assume that these tokens are more than one character long and
  3434. therefore are represented by names, not character literals.)
  3435.  
  3436. 
  3437. File: bison,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  3438.  
  3439. How Precedence Works
  3440. --------------------
  3441.  
  3442.    The first effect of the precedence declarations is to assign
  3443. precedence levels to the terminal symbols declared.  The second effect
  3444. is to assign precedence levels to certain rules: each rule gets its
  3445. precedence from the last terminal symbol mentioned in the components.
  3446. (You can also specify explicitly the precedence of a rule.  *Note
  3447. Context-Dependent Precedence: Contextual Precedence.)
  3448.  
  3449.    Finally, the resolution of conflicts works by comparing the
  3450. precedence of the rule being considered with that of the look-ahead
  3451. token.  If the token's precedence is higher, the choice is to shift.
  3452. If the rule's precedence is higher, the choice is to reduce.  If they
  3453. have equal precedence, the choice is made based on the associativity of
  3454. that precedence level.  The verbose output file made by `-v' (*note
  3455. Invoking Bison: Invocation.) says how each conflict was resolved.
  3456.  
  3457.    Not all rules and not all tokens have precedence.  If either the
  3458. rule or the look-ahead token has no precedence, then the default is to
  3459. shift.
  3460.  
  3461. 
  3462. File: bison,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  3463.  
  3464. Context-Dependent Precedence
  3465. ============================
  3466.  
  3467.    Often the precedence of an operator depends on the context.  This
  3468. sounds outlandish at first, but it is really very common.  For example,
  3469. a minus sign typically has a very high precedence as a unary operator,
  3470. and a somewhat lower precedence (lower than multiplication) as a binary
  3471. operator.
  3472.  
  3473.    The Bison precedence declarations, `%left', `%right' and
  3474. `%nonassoc', can only be used once for a given token; so a token has
  3475. only one precedence declared in this way.  For context-dependent
  3476. precedence, you need to use an additional mechanism: the `%prec'
  3477. modifier for rules.
  3478.  
  3479.    The `%prec' modifier declares the precedence of a particular rule by
  3480. specifying a terminal symbol whose precedence should be used for that
  3481. rule.  It's not necessary for that symbol to appear otherwise in the
  3482. rule.  The modifier's syntax is:
  3483.  
  3484.      %prec TERMINAL-SYMBOL
  3485.  
  3486. and it is written after the components of the rule.  Its effect is to
  3487. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  3488. precedence that would be deduced for it in the ordinary way.  The
  3489. altered rule precedence then affects how conflicts involving that rule
  3490. are resolved (*note Operator Precedence: Precedence.).
  3491.  
  3492.    Here is how `%prec' solves the problem of unary minus.  First,
  3493. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  3494. There are no tokens of this type, but the symbol serves to stand for its
  3495. precedence:
  3496.  
  3497.      ...
  3498.      %left '+' '-'
  3499.      %left '*'
  3500.      %left UMINUS
  3501.  
  3502.    Now the precedence of `UMINUS' can be used in specific rules:
  3503.  
  3504.      exp:    ...
  3505.              | exp '-' exp
  3506.              ...
  3507.              | '-' exp %prec UMINUS
  3508.  
  3509. 
  3510. File: bison,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  3511.  
  3512. Parser States
  3513. =============
  3514.  
  3515.    The function `yyparse' is implemented using a finite-state machine.
  3516. The values pushed on the parser stack are not simply token type codes;
  3517. they represent the entire sequence of terminal and nonterminal symbols
  3518. at or near the top of the stack.  The current state collects all the
  3519. information about previous input which is relevant to deciding what to
  3520. do next.
  3521.  
  3522.    Each time a look-ahead token is read, the current parser state
  3523. together with the type of look-ahead token are looked up in a table.
  3524. This table entry can say, "Shift the look-ahead token."  In this case,
  3525. it also specifies the new parser state, which is pushed onto the top of
  3526. the parser stack.  Or it can say, "Reduce using rule number N." This
  3527. means that a certain number of tokens or groupings are taken off the
  3528. top of the stack, and replaced by one grouping.  In other words, that
  3529. number of states are popped from the stack, and one new state is pushed.
  3530.  
  3531.    There is one other alternative: the table can say that the
  3532. look-ahead token is erroneous in the current state.  This causes error
  3533. processing to begin (*note Error Recovery::.).
  3534.  
  3535. 
  3536. File: bison,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  3537.  
  3538. Reduce/Reduce Conflicts
  3539. =======================
  3540.  
  3541.    A reduce/reduce conflict occurs if there are two or more rules that
  3542. apply to the same sequence of input.  This usually indicates a serious
  3543. error in the grammar.
  3544.  
  3545.    For example, here is an erroneous attempt to define a sequence of
  3546. zero or more `word' groupings.
  3547.  
  3548.      sequence: /* empty */
  3549.                      { printf ("empty sequence\n"); }
  3550.              | maybeword
  3551.              | sequence word
  3552.                      { printf ("added word %s\n", $2); }
  3553.              ;
  3554.      
  3555.      maybeword: /* empty */
  3556.                      { printf ("empty maybeword\n"); }
  3557.              | word
  3558.                      { printf ("single word %s\n", $1); }
  3559.              ;
  3560.  
  3561. The error is an ambiguity: there is more than one way to parse a single
  3562. `word' into a `sequence'.  It could be reduced to a `maybeword' and
  3563. then into a `sequence' via the second rule.  Alternatively,
  3564. nothing-at-all could be reduced into a `sequence' via the first rule,
  3565. and this could be combined with the `word' using the third rule for
  3566. `sequence'.
  3567.  
  3568.    There is also more than one way to reduce nothing-at-all into a
  3569. `sequence'.  This can be done directly via the first rule, or
  3570. indirectly via `maybeword' and then the second rule.
  3571.  
  3572.    You might think that this is a distinction without a difference,
  3573. because it does not change whether any particular input is valid or
  3574. not.  But it does affect which actions are run.  One parsing order runs
  3575. the second rule's action; the other runs the first rule's action and
  3576. the third rule's action.  In this example, the output of the program
  3577. changes.
  3578.  
  3579.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  3580. that appears first in the grammar, but it is very risky to rely on
  3581. this.  Every reduce/reduce conflict must be studied and usually
  3582. eliminated.  Here is the proper way to define `sequence':
  3583.  
  3584.      sequence: /* empty */
  3585.                      { printf ("empty sequence\n"); }
  3586.              | sequence word
  3587.                      { printf ("added word %s\n", $2); }
  3588.              ;
  3589.  
  3590.    Here is another common error that yields a reduce/reduce conflict:
  3591.  
  3592.      sequence: /* empty */
  3593.              | sequence words
  3594.              | sequence redirects
  3595.              ;
  3596.      
  3597.      words:    /* empty */
  3598.              | words word
  3599.              ;
  3600.      
  3601.      redirects:/* empty */
  3602.              | redirects redirect
  3603.              ;
  3604.  
  3605. The intention here is to define a sequence which can contain either
  3606. `word' or `redirect' groupings.  The individual definitions of
  3607. `sequence', `words' and `redirects' are error-free, but the three
  3608. together make a subtle ambiguity: even an empty input can be parsed in
  3609. infinitely many ways!
  3610.  
  3611.    Consider: nothing-at-all could be a `words'.  Or it could be two
  3612. `words' in a row, or three, or any number.  It could equally well be a
  3613. `redirects', or two, or any number.  Or it could be a `words' followed
  3614. by three `redirects' and another `words'.  And so on.
  3615.  
  3616.    Here are two ways to correct these rules.  First, to make it a
  3617. single level of sequence:
  3618.  
  3619.      sequence: /* empty */
  3620.              | sequence word
  3621.              | sequence redirect
  3622.              ;
  3623.  
  3624.    Second, to prevent either a `words' or a `redirects' from being
  3625. empty:
  3626.  
  3627.      sequence: /* empty */
  3628.              | sequence words
  3629.              | sequence redirects
  3630.              ;
  3631.      
  3632.      words:    word
  3633.              | words word
  3634.              ;
  3635.      
  3636.      redirects:redirect
  3637.              | redirects redirect
  3638.              ;
  3639.  
  3640. 
  3641. File: bison,  Node: Mystery Conflicts,  Next: Stack Overflow,  Prev: Reduce/Reduce,  Up: Algorithm
  3642.  
  3643. Mysterious Reduce/Reduce Conflicts
  3644. ==================================
  3645.  
  3646.    Sometimes reduce/reduce conflicts can occur that don't look
  3647. warranted.  Here is an example:
  3648.  
  3649.      %token ID
  3650.      
  3651.      %%
  3652.      def:    param_spec return_spec ','
  3653.              ;
  3654.      param_spec:
  3655.                   type
  3656.              |    name_list ':' type
  3657.              ;
  3658.      return_spec:
  3659.                   type
  3660.              |    name ':' type
  3661.              ;
  3662.      type:        ID
  3663.              ;
  3664.      name:        ID
  3665.              ;
  3666.      name_list:
  3667.                   name
  3668.              |    name ',' name_list
  3669.              ;
  3670.  
  3671.    It would seem that this grammar can be parsed with only a single
  3672. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  3673. `name' if a comma or colon follows, or a `type' if another `ID'
  3674. follows.  In other words, this grammar is LR(1).
  3675.  
  3676.    However, Bison, like most parser generators, cannot actually handle
  3677. all LR(1) grammars.  In this grammar, two contexts, that after an `ID'
  3678. at the beginning of a `param_spec' and likewise at the beginning of a
  3679. `return_spec', are similar enough that Bison assumes they are the same.
  3680. They appear similar because the same set of rules would be active--the
  3681. rule for reducing to a `name' and that for reducing to a `type'.  Bison
  3682. is unable to determine at that stage of processing that the rules would
  3683. require different look-ahead tokens in the two contexts, so it makes a
  3684. single parser state for them both.  Combining the two contexts causes a
  3685. conflict later.  In parser terminology, this occurrence means that the
  3686. grammar is not LALR(1).
  3687.  
  3688.    In general, it is better to fix deficiencies than to document them.
  3689. But this particular deficiency is intrinsically hard to fix; parser
  3690. generators that can handle LR(1) grammars are hard to write and tend to
  3691. produce parsers that are very large.  In practice, Bison is more useful
  3692. as it is now.
  3693.  
  3694.    When the problem arises, you can often fix it by identifying the two
  3695. parser states that are being confused, and adding something to make them
  3696. look distinct.  In the above example, adding one rule to `return_spec'
  3697. as follows makes the problem go away:
  3698.  
  3699.      %token BOGUS
  3700.      ...
  3701.      %%
  3702.      ...
  3703.      return_spec:
  3704.                   type
  3705.              |    name ':' type
  3706.              /* This rule is never used.  */
  3707.              |    ID BOGUS
  3708.              ;
  3709.  
  3710.    This corrects the problem because it introduces the possibility of an
  3711. additional active rule in the context after the `ID' at the beginning of
  3712. `return_spec'.  This rule is not active in the corresponding context in
  3713. a `param_spec', so the two contexts receive distinct parser states.  As
  3714. long as the token `BOGUS' is never generated by `yylex', the added rule
  3715. cannot alter the way actual input is parsed.
  3716.  
  3717.    In this particular example, there is another way to solve the
  3718. problem: rewrite the rule for `return_spec' to use `ID' directly
  3719. instead of via `name'.  This also causes the two confusing contexts to
  3720. have different sets of active rules, because the one for `return_spec'
  3721. activates the altered rule for `return_spec' rather than the one for
  3722. `name'.
  3723.  
  3724.      param_spec:
  3725.                   type
  3726.              |    name_list ':' type
  3727.              ;
  3728.      return_spec:
  3729.                   type
  3730.              |    ID ':' type
  3731.              ;
  3732.  
  3733. 
  3734. File: bison,  Node: Stack Overflow,  Prev: Mystery Conflicts,  Up: Algorithm
  3735.  
  3736. Stack Overflow, and How to Avoid It
  3737. ===================================
  3738.  
  3739.    The Bison parser stack can overflow if too many tokens are shifted
  3740. and not reduced.  When this happens, the parser function `yyparse'
  3741. returns a nonzero value, pausing only to call `yyerror' to report the
  3742. overflow.
  3743.  
  3744.    By defining the macro `YYMAXDEPTH', you can control how deep the
  3745. parser stack can become before a stack overflow occurs.  Define the
  3746. macro with a value that is an integer.  This value is the maximum number
  3747. of tokens that can be shifted (and not reduced) before overflow.  It
  3748. must be a constant expression whose value is known at compile time.
  3749.  
  3750.    The stack space allowed is not necessarily allocated.  If you
  3751. specify a large value for `YYMAXDEPTH', the parser actually allocates a
  3752. small stack at first, and then makes it bigger by stages as needed.
  3753. This increasing allocation happens automatically and silently.
  3754. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  3755. to save space for ordinary inputs that do not need much stack.
  3756.  
  3757.    The default value of `YYMAXDEPTH', if you do not define it, is 10000.
  3758.  
  3759.    You can control how much stack is allocated initially by defining the
  3760. macro `YYINITDEPTH'.  This value too must be a compile-time constant
  3761. integer.  The default is 200.
  3762.  
  3763. 
  3764. File: bison,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  3765.  
  3766. Error Recovery
  3767. **************
  3768.  
  3769.    It is not usually acceptable to have a program terminate on a parse
  3770. error.  For example, a compiler should recover sufficiently to parse the
  3771. rest of the input file and check it for errors; a calculator should
  3772. accept another expression.
  3773.  
  3774.    In a simple interactive command parser where each input is one line,
  3775. it may be sufficient to allow `yyparse' to return 1 on error and have
  3776. the caller ignore the rest of the input line when that happens (and
  3777. then call `yyparse' again).  But this is inadequate for a compiler,
  3778. because it forgets all the syntactic context leading up to the error.
  3779. A syntax error deep within a function in the compiler input should not
  3780. cause the compiler to treat the following line like the beginning of a
  3781. source file.
  3782.  
  3783.    You can define how to recover from a syntax error by writing rules to
  3784. recognize the special token `error'.  This is a terminal symbol that is
  3785. always defined (you need not declare it) and reserved for error
  3786. handling.  The Bison parser generates an `error' token whenever a
  3787. syntax error happens; if you have provided a rule to recognize this
  3788. token in the current context, the parse can continue.
  3789.  
  3790.    For example:
  3791.  
  3792.      stmnts:  /* empty string */
  3793.              | stmnts '\n'
  3794.              | stmnts exp '\n'
  3795.              | stmnts error '\n'
  3796.  
  3797.    The fourth rule in this example says that an error followed by a
  3798. newline makes a valid addition to any `stmnts'.
  3799.  
  3800.    What happens if a syntax error occurs in the middle of an `exp'?  The
  3801. error recovery rule, interpreted strictly, applies to the precise
  3802. sequence of a `stmnts', an `error' and a newline.  If an error occurs in
  3803. the middle of an `exp', there will probably be some additional tokens
  3804. and subexpressions on the stack after the last `stmnts', and there will
  3805. be tokens to read before the next newline.  So the rule is not
  3806. applicable in the ordinary way.
  3807.  
  3808.    But Bison can force the situation to fit the rule, by discarding
  3809. part of the semantic context and part of the input.  First it discards
  3810. states and objects from the stack until it gets back to a state in
  3811. which the `error' token is acceptable.  (This means that the
  3812. subexpressions already parsed are discarded, back to the last complete
  3813. `stmnts'.)  At this point the `error' token can be shifted.  Then, if
  3814. the old look-ahead token is not acceptable to be shifted next, the
  3815. parser reads tokens and discards them until it finds a token which is
  3816. acceptable.  In this example, Bison reads and discards input until the
  3817. next newline so that the fourth rule can apply.
  3818.  
  3819.    The choice of error rules in the grammar is a choice of strategies
  3820. for error recovery.  A simple and useful strategy is simply to skip the
  3821. rest of the current input line or current statement if an error is
  3822. detected:
  3823.  
  3824.      stmnt: error ';'  /* on error, skip until ';' is read */
  3825.  
  3826.    It is also useful to recover to the matching close-delimiter of an
  3827. opening-delimiter that has already been parsed.  Otherwise the
  3828. close-delimiter will probably appear to be unmatched, and generate
  3829. another, spurious error message:
  3830.  
  3831.      primary:  '(' expr ')'
  3832.              | '(' error ')'
  3833.              ...
  3834.              ;
  3835.  
  3836.    Error recovery strategies are necessarily guesses.  When they guess
  3837. wrong, one syntax error often leads to another.  In the above example,
  3838. the error recovery rule guesses that an error is due to bad input
  3839. within one `stmnt'.  Suppose that instead a spurious semicolon is
  3840. inserted in the middle of a valid `stmnt'.  After the error recovery
  3841. rule recovers from the first error, another syntax error will be found
  3842. straightaway, since the text following the spurious semicolon is also
  3843. an invalid `stmnt'.
  3844.  
  3845.    To prevent an outpouring of error messages, the parser will output
  3846. no error message for another syntax error that happens shortly after
  3847. the first; only after three consecutive input tokens have been
  3848. successfully shifted will error messages resume.
  3849.  
  3850.    Note that rules which accept the `error' token may have actions, just
  3851. as any other rules can.
  3852.  
  3853.    You can make error messages resume immediately by using the macro
  3854. `yyerrok' in an action.  If you do this in the error rule's action, no
  3855. error messages will be suppressed.  This macro requires no arguments;
  3856. `yyerrok;' is a valid C statement.
  3857.  
  3858.    The previous look-ahead token is reanalyzed immediately after an
  3859. error.  If this is unacceptable, then the macro `yyclearin' may be used
  3860. to clear this token.  Write the statement `yyclearin;' in the error
  3861. rule's action.
  3862.  
  3863.    For example, suppose that on a parse error, an error handling
  3864. routine is called that advances the input stream to some point where
  3865. parsing should once again commence.  The next symbol returned by the
  3866. lexical scanner is probably correct.  The previous look-ahead token
  3867. ought to be discarded with `yyclearin;'.
  3868.  
  3869.    The macro `YYRECOVERING' stands for an expression that has the value
  3870. 1 when the parser is recovering from a syntax error, and 0 the rest of
  3871. the time.  A value of 1 indicates that error messages are currently
  3872. suppressed for new syntax errors.
  3873.  
  3874. 
  3875. File: bison,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  3876.  
  3877. Handling Context Dependencies
  3878. *****************************
  3879.  
  3880.    The Bison paradigm is to parse tokens first, then group them into
  3881. larger syntactic units.  In many languages, the meaning of a token is
  3882. affected by its context.  Although this violates the Bison paradigm,
  3883. certain techniques (known as "kludges") may enable you to write Bison
  3884. parsers for such languages.
  3885.  
  3886. * Menu:
  3887.  
  3888. * Semantic Tokens::   Token parsing can depend on the semantic context.
  3889. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  3890. * Tie-in Recovery::   Lexical tie-ins have implications for how
  3891.                         error recovery rules must be written.
  3892.  
  3893.    (Actually, "kludge" means any technique that gets its job done but is
  3894. neither clean nor robust.)
  3895.  
  3896. 
  3897. File: bison,  Node: Semantic Tokens,  Next: Lexical Tie-ins,  Up: Context Dependency
  3898.  
  3899. Semantic Info in Token Types
  3900. ============================
  3901.  
  3902.    The C language has a context dependency: the way an identifier is
  3903. used depends on what its current meaning is.  For example, consider
  3904. this:
  3905.  
  3906.      foo (x);
  3907.  
  3908.    This looks like a function call statement, but if `foo' is a typedef
  3909. name, then this is actually a declaration of `x'.  How can a Bison
  3910. parser for C decide how to parse this input?
  3911.  
  3912.    The method used in GNU C is to have two different token types,
  3913. `IDENTIFIER' and `TYPENAME'.  When `yylex' finds an identifier, it
  3914. looks up the current declaration of the identifier in order to decide
  3915. which token type to return: `TYPENAME' if the identifier is declared as
  3916. a typedef, `IDENTIFIER' otherwise.
  3917.  
  3918.    The grammar rules can then express the context dependency by the
  3919. choice of token type to recognize.  `IDENTIFIER' is accepted as an
  3920. expression, but `TYPENAME' is not.  `TYPENAME' can start a declaration,
  3921. but `IDENTIFIER' cannot.  In contexts where the meaning of the
  3922. identifier is *not* significant, such as in declarations that can
  3923. shadow a typedef name, either `TYPENAME' or `IDENTIFIER' is
  3924. accepted--there is one rule for each of the two token types.
  3925.  
  3926.    This technique is simple to use if the decision of which kinds of
  3927. identifiers to allow is made at a place close to where the identifier is
  3928. parsed.  But in C this is not always so: C allows a declaration to
  3929. redeclare a typedef name provided an explicit type has been specified
  3930. earlier:
  3931.  
  3932.      typedef int foo, bar, lose;
  3933.      static foo (bar);        /* redeclare `bar' as static variable */
  3934.      static int foo (lose);   /* redeclare `foo' as function */
  3935.  
  3936.    Unfortunately, the name being declared is separated from the
  3937. declaration construct itself by a complicated syntactic structure--the
  3938. "declarator".
  3939.  
  3940.    As a result, the part of Bison parser for C needs to be duplicated,
  3941. with all the nonterminal names changed: once for parsing a declaration
  3942. in which a typedef name can be redefined, and once for parsing a
  3943. declaration in which that can't be done.  Here is a part of the
  3944. duplication, with actions omitted for brevity:
  3945.  
  3946.      initdcl:
  3947.                declarator maybeasm '='
  3948.                init
  3949.              | declarator maybeasm
  3950.              ;
  3951.      
  3952.      notype_initdcl:
  3953.                notype_declarator maybeasm '='
  3954.                init
  3955.              | notype_declarator maybeasm
  3956.              ;
  3957.  
  3958. Here `initdcl' can redeclare a typedef name, but `notype_initdcl'
  3959. cannot.  The distinction between `declarator' and `notype_declarator'
  3960. is the same sort of thing.
  3961.  
  3962.    There is some similarity between this technique and a lexical tie-in
  3963. (described next), in that information which alters the lexical analysis
  3964. is changed during parsing by other parts of the program.  The
  3965. difference is here the information is global, and is used for other
  3966. purposes in the program.  A true lexical tie-in has a special-purpose
  3967. flag controlled by the syntactic context.
  3968.  
  3969. 
  3970. File: bison,  Node: Lexical Tie-ins,  Next: Tie-in Recovery,  Prev: Semantic Tokens,  Up: Context Dependency
  3971.  
  3972. Lexical Tie-ins
  3973. ===============
  3974.  
  3975.    One way to handle context-dependency is the "lexical tie-in": a flag
  3976. which is set by Bison actions, whose purpose is to alter the way tokens
  3977. are parsed.
  3978.  
  3979.    For example, suppose we have a language vaguely like C, but with a
  3980. special construct `hex (HEX-EXPR)'.  After the keyword `hex' comes an
  3981. expression in parentheses in which all integers are hexadecimal.  In
  3982. particular, the token `a1b' must be treated as an integer rather than
  3983. as an identifier if it appears in that context.  Here is how you can do
  3984. it:
  3985.  
  3986.      %{
  3987.      int hexflag;
  3988.      %}
  3989.      %%
  3990.      ...
  3991.      expr:   IDENTIFIER
  3992.              | constant
  3993.              | HEX '('
  3994.                      { hexflag = 1; }
  3995.                expr ')'
  3996.                      { hexflag = 0;
  3997.                         $$ = $4; }
  3998.              | expr '+' expr
  3999.                      { $$ = make_sum ($1, $3); }
  4000.              ...
  4001.              ;
  4002.      
  4003.      constant:
  4004.                INTEGER
  4005.              | STRING
  4006.              ;
  4007.  
  4008. Here we assume that `yylex' looks at the value of `hexflag'; when it is
  4009. nonzero, all integers are parsed in hexadecimal, and tokens starting
  4010. with letters are parsed as integers if possible.
  4011.  
  4012.    The declaration of `hexflag' shown in the C declarations section of
  4013. the parser file is needed to make it accessible to the actions (*note
  4014. The C Declarations Section: C Declarations.).  You must also write the
  4015. code in `yylex' to obey the flag.
  4016.  
  4017. 
  4018. File: bison,  Node: Tie-in Recovery,  Prev: Lexical Tie-ins,  Up: Context Dependency
  4019.  
  4020. Lexical Tie-ins and Error Recovery
  4021. ==================================
  4022.  
  4023.    Lexical tie-ins make strict demands on any error recovery rules you
  4024. have.  *Note Error Recovery::.
  4025.  
  4026.    The reason for this is that the purpose of an error recovery rule is
  4027. to abort the parsing of one construct and resume in some larger
  4028. construct.  For example, in C-like languages, a typical error recovery
  4029. rule is to skip tokens until the next semicolon, and then start a new
  4030. statement, like this:
  4031.  
  4032.      stmt:   expr ';'
  4033.              | IF '(' expr ')' stmt { ... }
  4034.              ...
  4035.              error ';'
  4036.                      { hexflag = 0; }
  4037.              ;
  4038.  
  4039.    If there is a syntax error in the middle of a `hex (EXPR)'
  4040. construct, this error rule will apply, and then the action for the
  4041. completed `hex (EXPR)' will never run.  So `hexflag' would remain set
  4042. for the entire rest of the input, or until the next `hex' keyword,
  4043. causing identifiers to be misinterpreted as integers.
  4044.  
  4045.    To avoid this problem the error recovery rule itself clears
  4046. `hexflag'.
  4047.  
  4048.    There may also be an error recovery rule that works within
  4049. expressions.  For example, there could be a rule which applies within
  4050. parentheses and skips to the close-parenthesis:
  4051.  
  4052.      expr:   ...
  4053.              | '(' expr ')'
  4054.                      { $$ = $2; }
  4055.              | '(' error ')'
  4056.              ...
  4057.  
  4058.    If this rule acts within the `hex' construct, it is not going to
  4059. abort that construct (since it applies to an inner level of parentheses
  4060. within the construct).  Therefore, it should not clear the flag: the
  4061. rest of the `hex' construct should be parsed with the flag still in
  4062. effect.
  4063.  
  4064.    What if there is an error recovery rule which might abort out of the
  4065. `hex' construct or might not, depending on circumstances?  There is no
  4066. way you can write the action to determine whether a `hex' construct is
  4067. being aborted or not.  So if you are using a lexical tie-in, you had
  4068. better make sure your error recovery rules are not of this kind.  Each
  4069. rule must be such that you can be sure that it always will, or always
  4070. won't, have to clear the flag.
  4071.  
  4072. 
  4073. File: bison,  Node: Debugging,  Next: Invocation,  Prev: Context Dependency,  Up: Top
  4074.  
  4075. Debugging Your Parser
  4076. *********************
  4077.  
  4078.    If a Bison grammar compiles properly but doesn't do what you want
  4079. when it runs, the `yydebug' parser-trace feature can help you figure
  4080. out why.
  4081.  
  4082.    To enable compilation of trace facilities, you must define the macro
  4083. `YYDEBUG' when you compile the parser.  You could use `-DYYDEBUG=1' as
  4084. a compiler option or you could put `#define YYDEBUG 1' in the C
  4085. declarations section of the grammar file (*note The C Declarations
  4086. Section: C Declarations.).  Alternatively, use the `-t' option when you
  4087. run Bison (*note Invoking Bison: Invocation.).  We always define
  4088. `YYDEBUG' so that debugging is always possible.
  4089.  
  4090.    The trace facility uses `stderr', so you must add
  4091. `#include <stdio.h>' to the C declarations section unless it is already
  4092. there.
  4093.  
  4094.    Once you have compiled the program with trace facilities, the way to
  4095. request a trace is to store a nonzero value in the variable `yydebug'.
  4096. You can do this by making the C code do it (in `main', perhaps), or you
  4097. can alter the value with a C debugger.
  4098.  
  4099.    Each step taken by the parser when `yydebug' is nonzero produces a
  4100. line or two of trace information, written on `stderr'.  The trace
  4101. messages tell you these things:
  4102.  
  4103.    * Each time the parser calls `yylex', what kind of token was read.
  4104.  
  4105.    * Each time a token is shifted, the depth and complete contents of
  4106.      the state stack (*note Parser States::.).
  4107.  
  4108.    * Each time a rule is reduced, which rule it is, and the complete
  4109.      contents of the state stack afterward.
  4110.  
  4111.    To make sense of this information, it helps to refer to the listing
  4112. file produced by the Bison `-v' option (*note Invoking Bison:
  4113. Invocation.).  This file shows the meaning of each state in terms of
  4114. positions in various rules, and also what each state will do with each
  4115. possible input token.  As you read the successive trace messages, you
  4116. can see that the parser is functioning according to its specification
  4117. in the listing file.  Eventually you will arrive at the place where
  4118. something undesirable happens, and you will see which parts of the
  4119. grammar are to blame.
  4120.  
  4121.    The parser file is a C program and you can use C debuggers on it,
  4122. but it's not easy to interpret what it is doing.  The parser function
  4123. is a finite-state machine interpreter, and aside from the actions it
  4124. executes the same code over and over.  Only the values of variables
  4125. show where in the grammar it is working.
  4126.  
  4127.    The debugging information normally gives the token type of each token
  4128. read, but not its semantic value.  You can optionally define a macro
  4129. named `YYPRINT' to provide a way to print the value.  If you define
  4130. `YYPRINT', it should take three arguments.  The parser will pass a
  4131. standard I/O stream, the numeric code for the token type, and the token
  4132. value (from `yylval').
  4133.  
  4134.    Here is an example of `YYPRINT' suitable for the multi-function
  4135. calculator (*note Declarations for `mfcalc': Mfcalc Decl.):
  4136.  
  4137.      #define YYPRINT(file, type, value)   yyprint (file, type, value)
  4138.      
  4139.      static void
  4140.      yyprint (file, type, value)
  4141.           FILE *file;
  4142.           int type;
  4143.           YYSTYPE value;
  4144.      {
  4145.        if (type == VAR)
  4146.          fprintf (file, " %s", value.tptr->name);
  4147.        else if (type == NUM)
  4148.          fprintf (file, " %d", value.val);
  4149.      }
  4150.  
  4151. 
  4152. File: bison,  Node: Invocation,  Next: Table of Symbols,  Prev: Debugging,  Up: Top
  4153.  
  4154. Invoking Bison
  4155. **************
  4156.  
  4157.    The usual way to invoke Bison is as follows:
  4158.  
  4159.      bison INFILE
  4160.  
  4161.    Here INFILE is the grammar file name, which usually ends in `.y'.
  4162. The parser file's name is made by replacing the `.y' with `.tab.c'.
  4163. Thus, the `bison foo.y' filename yields `foo.tab.c', and the `bison
  4164. hack/foo.y' filename yields `hack/foo.tab.c'.
  4165.  
  4166. * Menu:
  4167.  
  4168. * Bison Options::     All the options described in detail,
  4169.             in alphabetical order by short options.
  4170. * Option Cross Key::  Alphabetical list of long options.
  4171. * VMS Invocation::    Bison command syntax on VMS.
  4172.  
  4173. 
  4174. File: bison,  Node: Bison Options,  Next: Option Cross Key,  Up: Invocation
  4175.  
  4176. Bison Options
  4177. =============
  4178.  
  4179.    Bison supports both traditional single-letter options and mnemonic
  4180. long option names.  Long option names are indicated with `--' instead of
  4181. `-'.  Abbreviations for option names are allowed as long as they are
  4182. unique.  When a long option takes an argument, like `--file-prefix',
  4183. connect the option name and the argument with `='.
  4184.  
  4185.    Here is a list of options that can be used with Bison, alphabetized
  4186. by short option.  It is followed by a cross key alphabetized by long
  4187. option.
  4188.  
  4189. `-b FILE-PREFIX'
  4190. `--file-prefix=PREFIX'
  4191.      Specify a prefix to use for all Bison output file names.  The
  4192.      names are chosen as if the input file were named `PREFIX.c'.
  4193.  
  4194. `-d'
  4195. `--defines'
  4196.      Write an extra output file containing macro definitions for the
  4197.      token type names defined in the grammar and the semantic value type
  4198.      `YYSTYPE', as well as a few `extern' variable declarations.
  4199.  
  4200.      If the parser output file is named `NAME.c' then this file is
  4201.      named `NAME.h'.
  4202.  
  4203.      This output file is essential if you wish to put the definition of
  4204.      `yylex' in a separate source file, because `yylex' needs to be
  4205.      able to refer to token type codes and the variable `yylval'.
  4206.      *Note Semantic Values of Tokens: Token Values.
  4207.  
  4208. `-l'
  4209. `--no-lines'
  4210.      Don't put any `#line' preprocessor commands in the parser file.
  4211.      Ordinarily Bison puts them in the parser file so that the C
  4212.      compiler and debuggers will associate errors with your source
  4213.      file, the grammar file.  This option causes them to associate
  4214.      errors with the parser file, treating it an independent source
  4215.      file in its own right.
  4216.  
  4217. `-o OUTFILE'
  4218. `--output-file=OUTFILE'
  4219.      Specify the name OUTFILE for the parser file.
  4220.  
  4221.      The other output files' names are constructed from OUTFILE as
  4222.      described under the `-v' and `-d' switches.
  4223.  
  4224. `-p PREFIX'
  4225. `--name-prefix=PREFIX'
  4226.      Rename the external symbols used in the parser so that they start
  4227.      with PREFIX instead of `yy'.  The precise list of symbols renamed
  4228.      is `yyparse', `yylex', `yyerror', `yylval', `yychar' and `yydebug'.
  4229.  
  4230.      For example, if you use `-p c', the names become `cparse', `clex',
  4231.      and so on.
  4232.  
  4233.      *Note Multiple Parsers in the Same Program: Multiple Parsers.
  4234.  
  4235. `-t'
  4236. `--debug'
  4237.      Output a definition of the macro `YYDEBUG' into the parser file,
  4238.      so that the debugging facilities are compiled.  *Note Debugging
  4239.      Your Parser: Debugging.
  4240.  
  4241. `-v'
  4242. `--verbose'
  4243.      Write an extra output file containing verbose descriptions of the
  4244.      parser states and what is done for each type of look-ahead token in
  4245.      that state.
  4246.  
  4247.      This file also describes all the conflicts, both those resolved by
  4248.      operator precedence and the unresolved ones.
  4249.  
  4250.      The file's name is made by removing `.tab.c' or `.c' from the
  4251.      parser output file name, and adding `.output' instead.
  4252.  
  4253.      Therefore, if the input file is `foo.y', then the parser file is
  4254.      called `foo.tab.c' by default.  As a consequence, the verbose
  4255.      output file is called `foo.output'.
  4256.  
  4257. `-V'
  4258. `--version'
  4259.      Print the version number of Bison and exit.
  4260.  
  4261. `-h'
  4262. `--help'
  4263.      Print a summary of the command-line options to Bison and exit.
  4264.  
  4265. `-y'
  4266. `--yacc'
  4267. `--fixed-output-files'
  4268.      Equivalent to `-o y.tab.c'; the parser output file is called
  4269.      `y.tab.c', and the other outputs are called `y.output' and
  4270.      `y.tab.h'.  The purpose of this switch is to imitate Yacc's output
  4271.      file name conventions.  Thus, the following shell script can
  4272.      substitute for Yacc:
  4273.  
  4274.           bison -y $*
  4275.  
  4276. 
  4277. File: bison,  Node: Option Cross Key,  Next: VMS Invocation,  Prev: Bison Options,  Up: Invocation
  4278.  
  4279. Option Cross Key
  4280. ================
  4281.  
  4282.    Here is a list of options, alphabetized by long option, to help you
  4283. find the corresponding short option.
  4284.  
  4285.      --debug                               -t
  4286.      --defines                             -d
  4287.      --file-prefix=PREFIX                  -b FILE-PREFIX
  4288.      --fixed-output-files --yacc           -y
  4289.      --help                                -h
  4290.      --name-prefix                         -p
  4291.      --no-lines                            -l
  4292.      --output-file=OUTFILE                 -o OUTFILE
  4293.      --verbose                             -v
  4294.      --version                             -V
  4295.  
  4296. 
  4297. File: bison,  Node: VMS Invocation,  Prev: Option Cross Key,  Up: Invocation
  4298.  
  4299. Invoking Bison under VMS
  4300. ========================
  4301.  
  4302.    The command line syntax for Bison on VMS is a variant of the usual
  4303. Bison command syntax--adapted to fit VMS conventions.
  4304.  
  4305.    To find the VMS equivalent for any Bison option, start with the long
  4306. option, and substitute a `/' for the leading `--', and substitute a `_'
  4307. for each `-' in the name of the long option.  For example, the
  4308. following invocation under VMS:
  4309.  
  4310.      bison /debug/name_prefix=bar foo.y
  4311.  
  4312. is equivalent to the following command under POSIX.
  4313.  
  4314.      bison --debug --name-prefix=bar foo.y
  4315.  
  4316.    The VMS file system does not permit filenames such as `foo.tab.c'.
  4317. In the above example, the output file would instead be named
  4318. `foo_tab.c'.
  4319.  
  4320. 
  4321. File: bison,  Node: Table of Symbols,  Next: Glossary,  Prev: Invocation,  Up: Top
  4322.  
  4323. Bison Symbols
  4324. *************
  4325.  
  4326. `error'
  4327.      A token name reserved for error recovery.  This token may be used
  4328.      in grammar rules so as to allow the Bison parser to recognize an
  4329.      error in the grammar without halting the process.  In effect, a
  4330.      sentence containing an error may be recognized as valid.  On a
  4331.      parse error, the token `error' becomes the current look-ahead
  4332.      token.  Actions corresponding to `error' are then executed, and
  4333.      the look-ahead token is reset to the token that originally caused
  4334.      the violation.  *Note Error Recovery::.
  4335.  
  4336. `YYABORT'
  4337.      Macro to pretend that an unrecoverable syntax error has occurred,
  4338.      by making `yyparse' return 1 immediately.  The error reporting
  4339.      function `yyerror' is not called.  *Note The Parser Function
  4340.      `yyparse': Parser Function.
  4341.  
  4342. `YYACCEPT'
  4343.      Macro to pretend that a complete utterance of the language has been
  4344.      read, by making `yyparse' return 0 immediately.  *Note The Parser
  4345.      Function `yyparse': Parser Function.
  4346.  
  4347. `YYBACKUP'
  4348.      Macro to discard a value from the parser stack and fake a
  4349.      look-ahead token.  *Note Special Features for Use in Actions:
  4350.      Action Features.
  4351.  
  4352. `YYERROR'
  4353.      Macro to pretend that a syntax error has just been detected: call
  4354.      `yyerror' and then perform normal error recovery if possible
  4355.      (*note Error Recovery::.), or (if recovery is impossible) make
  4356.      `yyparse' return 1.  *Note Error Recovery::.
  4357.  
  4358. `YYERROR_VERBOSE'
  4359.      Macro that you define with `#define' in the Bison declarations
  4360.      section to request verbose, specific error message strings when
  4361.      `yyerror' is called.
  4362.  
  4363. `YYINITDEPTH'
  4364.      Macro for specifying the initial size of the parser stack.  *Note
  4365.      Stack Overflow::.
  4366.  
  4367. `YYLTYPE'
  4368.      Macro for the data type of `yylloc'; a structure with four
  4369.      members.  *Note Textual Positions of Tokens: Token Positions.
  4370.  
  4371. `YYMAXDEPTH'
  4372.      Macro for specifying the maximum size of the parser stack.  *Note
  4373.      Stack Overflow::.
  4374.  
  4375. `YYRECOVERING'
  4376.      Macro whose value indicates whether the parser is recovering from a
  4377.      syntax error.  *Note Special Features for Use in Actions: Action
  4378.      Features.
  4379.  
  4380. `YYSTYPE'
  4381.      Macro for the data type of semantic values; `int' by default.
  4382.      *Note Data Types of Semantic Values: Value Type.
  4383.  
  4384. `yychar'
  4385.      External integer variable that contains the integer value of the
  4386.      current look-ahead token.  (In a pure parser, it is a local
  4387.      variable within `yyparse'.)  Error-recovery rule actions may
  4388.      examine this variable.  *Note Special Features for Use in Actions:
  4389.      Action Features.
  4390.  
  4391. `yyclearin'
  4392.      Macro used in error-recovery rule actions.  It clears the previous
  4393.      look-ahead token.  *Note Error Recovery::.
  4394.  
  4395. `yydebug'
  4396.      External integer variable set to zero by default.  If `yydebug' is
  4397.      given a nonzero value, the parser will output information on input
  4398.      symbols and parser action.  *Note Debugging Your Parser: Debugging.
  4399.  
  4400. `yyerrok'
  4401.      Macro to cause parser to recover immediately to its normal mode
  4402.      after a parse error.  *Note Error Recovery::.
  4403.  
  4404. `yyerror'
  4405.      User-supplied function to be called by `yyparse' on error.  The
  4406.      function receives one argument, a pointer to a character string
  4407.      containing an error message.  *Note The Error Reporting Function
  4408.      `yyerror': Error Reporting.
  4409.  
  4410. `yylex'
  4411.      User-supplied lexical analyzer function, called with no arguments
  4412.      to get the next token.  *Note The Lexical Analyzer Function
  4413.      `yylex': Lexical.
  4414.  
  4415. `yylval'
  4416.      External variable in which `yylex' should place the semantic value
  4417.      associated with a token.  (In a pure parser, it is a local
  4418.      variable within `yyparse', and its address is passed to `yylex'.)
  4419.      *Note Semantic Values of Tokens: Token Values.
  4420.  
  4421. `yylloc'
  4422.      External variable in which `yylex' should place the line and
  4423.      column numbers associated with a token.  (In a pure parser, it is a
  4424.      local variable within `yyparse', and its address is passed to
  4425.      `yylex'.)  You can ignore this variable if you don't use the `@'
  4426.      feature in the grammar actions.  *Note Textual Positions of
  4427.      Tokens: Token Positions.
  4428.  
  4429. `yynerrs'
  4430.      Global variable which Bison increments each time there is a parse
  4431.      error.  (In a pure parser, it is a local variable within
  4432.      `yyparse'.)  *Note The Error Reporting Function `yyerror': Error
  4433.      Reporting.
  4434.  
  4435. `yyparse'
  4436.      The parser function produced by Bison; call this function to start
  4437.      parsing.  *Note The Parser Function `yyparse': Parser Function.
  4438.  
  4439. `%left'
  4440.      Bison declaration to assign left associativity to token(s).  *Note
  4441.      Operator Precedence: Precedence Decl.
  4442.  
  4443. `%nonassoc'
  4444.      Bison declaration to assign nonassociativity to token(s).  *Note
  4445.      Operator Precedence: Precedence Decl.
  4446.  
  4447. `%prec'
  4448.      Bison declaration to assign a precedence to a specific rule.
  4449.      *Note Context-Dependent Precedence: Contextual Precedence.
  4450.  
  4451. `%pure_parser'
  4452.      Bison declaration to request a pure (reentrant) parser.  *Note A
  4453.      Pure (Reentrant) Parser: Pure Decl.
  4454.  
  4455. `%right'
  4456.      Bison declaration to assign right associativity to token(s).
  4457.      *Note Operator Precedence: Precedence Decl.
  4458.  
  4459. `%start'
  4460.      Bison declaration to specify the start symbol.  *Note The
  4461.      Start-Symbol: Start Decl.
  4462.  
  4463. `%token'
  4464.      Bison declaration to declare token(s) without specifying
  4465.      precedence.  *Note Token Type Names: Token Decl.
  4466.  
  4467. `%type'
  4468.      Bison declaration to declare nonterminals.  *Note Nonterminal
  4469.      Symbols: Type Decl.
  4470.  
  4471. `%union'
  4472.      Bison declaration to specify several possible data types for
  4473.      semantic values.  *Note The Collection of Value Types: Union Decl.
  4474.  
  4475.    These are the punctuation and delimiters used in Bison input:
  4476.  
  4477. `%%'
  4478.      Delimiter used to separate the grammar rule section from the Bison
  4479.      declarations section or the additional C code section.  *Note The
  4480.      Overall Layout of a Bison Grammar: Grammar Layout.
  4481.  
  4482. `%{ %}'
  4483.      All code listed between `%{' and `%}' is copied directly to the
  4484.      output file uninterpreted.  Such code forms the "C declarations"
  4485.      section of the input file.  *Note Outline of a Bison Grammar:
  4486.      Grammar Outline.
  4487.  
  4488. `/*...*/'
  4489.      Comment delimiters, as in C.
  4490.  
  4491. `:'
  4492.      Separates a rule's result from its components.  *Note Syntax of
  4493.      Grammar Rules: Rules.
  4494.  
  4495. `;'
  4496.      Terminates a rule.  *Note Syntax of Grammar Rules: Rules.
  4497.  
  4498. `|'
  4499.      Separates alternate rules for the same result nonterminal.  *Note
  4500.      Syntax of Grammar Rules: Rules.
  4501.  
  4502. 
  4503. File: bison,  Node: Glossary,  Next: Index,  Prev: Table of Symbols,  Up: Top
  4504.  
  4505. Glossary
  4506. ********
  4507.  
  4508. Backus-Naur Form (BNF)
  4509.      Formal method of specifying context-free grammars.  BNF was first
  4510.      used in the `ALGOL-60' report, 1963.  *Note Languages and
  4511.      Context-Free Grammars: Language and Grammar.
  4512.  
  4513. Context-free grammars
  4514.      Grammars specified as rules that can be applied regardless of
  4515.      context.  Thus, if there is a rule which says that an integer can
  4516.      be used as an expression, integers are allowed *anywhere* an
  4517.      expression is permitted.  *Note Languages and Context-Free
  4518.      Grammars: Language and Grammar.
  4519.  
  4520. Dynamic allocation
  4521.      Allocation of memory that occurs during execution, rather than at
  4522.      compile time or on entry to a function.
  4523.  
  4524. Empty string
  4525.      Analogous to the empty set in set theory, the empty string is a
  4526.      character string of length zero.
  4527.  
  4528. Finite-state stack machine
  4529.      A "machine" that has discrete states in which it is said to exist
  4530.      at each instant in time.  As input to the machine is processed, the
  4531.      machine moves from state to state as specified by the logic of the
  4532.      machine.  In the case of the parser, the input is the language
  4533.      being parsed, and the states correspond to various stages in the
  4534.      grammar rules.  *Note The Bison Parser Algorithm: Algorithm.
  4535.  
  4536. Grouping
  4537.      A language construct that is (in general) grammatically divisible;
  4538.      for example, `expression' or `declaration' in C.  *Note Languages
  4539.      and Context-Free Grammars: Language and Grammar.
  4540.  
  4541. Infix operator
  4542.      An arithmetic operator that is placed between the operands on
  4543.      which it performs some operation.
  4544.  
  4545. Input stream
  4546.      A continuous flow of data between devices or programs.
  4547.  
  4548. Language construct
  4549.      One of the typical usage schemas of the language.  For example,
  4550.      one of the constructs of the C language is the `if' statement.
  4551.      *Note Languages and Context-Free Grammars: Language and Grammar.
  4552.  
  4553. Left associativity
  4554.      Operators having left associativity are analyzed from left to
  4555.      right: `a+b+c' first computes `a+b' and then combines with `c'.
  4556.      *Note Operator Precedence: Precedence.
  4557.  
  4558. Left recursion
  4559.      A rule whose result symbol is also its first component symbol; for
  4560.      example, `expseq1 : expseq1 ',' exp;'.  *Note Recursive Rules:
  4561.      Recursion.
  4562.  
  4563. Left-to-right parsing
  4564.      Parsing a sentence of a language by analyzing it token by token
  4565.      from left to right.  *Note The Bison Parser Algorithm: Algorithm.
  4566.  
  4567. Lexical analyzer (scanner)
  4568.      A function that reads an input stream and returns tokens one by
  4569.      one.  *Note The Lexical Analyzer Function `yylex': Lexical.
  4570.  
  4571. Lexical tie-in
  4572.      A flag, set by actions in the grammar rules, which alters the way
  4573.      tokens are parsed.  *Note Lexical Tie-ins::.
  4574.  
  4575. Look-ahead token
  4576.      A token already read but not yet shifted.  *Note Look-Ahead
  4577.      Tokens: Look-Ahead.
  4578.  
  4579. LALR(1)
  4580.      The class of context-free grammars that Bison (like most other
  4581.      parser generators) can handle; a subset of LR(1).  *Note
  4582.      Mysterious Reduce/Reduce Conflicts: Mystery Conflicts.
  4583.  
  4584. LR(1)
  4585.      The class of context-free grammars in which at most one token of
  4586.      look-ahead is needed to disambiguate the parsing of any piece of
  4587.      input.
  4588.  
  4589. Nonterminal symbol
  4590.      A grammar symbol standing for a grammatical construct that can be
  4591.      expressed through rules in terms of smaller constructs; in other
  4592.      words, a construct that is not a token.  *Note Symbols::.
  4593.  
  4594. Parse error
  4595.      An error encountered during parsing of an input stream due to
  4596.      invalid syntax.  *Note Error Recovery::.
  4597.  
  4598. Parser
  4599.      A function that recognizes valid sentences of a language by
  4600.      analyzing the syntax structure of a set of tokens passed to it
  4601.      from a lexical analyzer.
  4602.  
  4603. Postfix operator
  4604.      An arithmetic operator that is placed after the operands upon
  4605.      which it performs some operation.
  4606.  
  4607. Reduction
  4608.      Replacing a string of nonterminals and/or terminals with a single
  4609.      nonterminal, according to a grammar rule.  *Note The Bison Parser
  4610.      Algorithm: Algorithm.
  4611.  
  4612. Reentrant
  4613.      A reentrant subprogram is a subprogram which can be in invoked any
  4614.      number of times in parallel, without interference between the
  4615.      various invocations.  *Note A Pure (Reentrant) Parser: Pure Decl.
  4616.  
  4617. Reverse polish notation
  4618.      A language in which all operators are postfix operators.
  4619.  
  4620. Right recursion
  4621.      A rule whose result symbol is also its last component symbol; for
  4622.      example, `expseq1: exp ',' expseq1;'.  *Note Recursive Rules:
  4623.      Recursion.
  4624.  
  4625. Semantics
  4626.      In computer languages, the semantics are specified by the actions
  4627.      taken for each instance of the language, i.e., the meaning of each
  4628.      statement.  *Note Defining Language Semantics: Semantics.
  4629.  
  4630. Shift
  4631.      A parser is said to shift when it makes the choice of analyzing
  4632.      further input from the stream rather than reducing immediately some
  4633.      already-recognized rule.  *Note The Bison Parser Algorithm:
  4634.      Algorithm.
  4635.  
  4636. Single-character literal
  4637.      A single character that is recognized and interpreted as is.
  4638.      *Note From Formal Rules to Bison Input: Grammar in Bison.
  4639.  
  4640. Start symbol
  4641.      The nonterminal symbol that stands for a complete valid utterance
  4642.      in the language being parsed.  The start symbol is usually listed
  4643.      as the first nonterminal symbol in a language specification.
  4644.      *Note The Start-Symbol: Start Decl.
  4645.  
  4646. Symbol table
  4647.      A data structure where symbol names and associated data are stored
  4648.      during parsing to allow for recognition and use of existing
  4649.      information in repeated uses of a symbol.  *Note Multi-function
  4650.      Calc::.
  4651.  
  4652. Token
  4653.      A basic, grammatically indivisible unit of a language.  The symbol
  4654.      that describes a token in the grammar is a terminal symbol.  The
  4655.      input of the Bison parser is a stream of tokens which comes from
  4656.      the lexical analyzer.  *Note Symbols::.
  4657.  
  4658. Terminal symbol
  4659.      A grammar symbol that has no rules in the grammar and therefore is
  4660.      grammatically indivisible.  The piece of text it represents is a
  4661.      token.  *Note Languages and Context-Free Grammars: Language and
  4662.      Grammar.
  4663.  
  4664. 
  4665. File: bison,  Node: Index,  Prev: Glossary,  Up: Top
  4666.  
  4667. Index
  4668. *****
  4669.  
  4670. * Menu:
  4671.  
  4672. * $$:                                   Actions.
  4673. * $N:                                   Actions.
  4674. * %expect:                              Expect Decl.
  4675. * %left:                                Using Precedence.
  4676. * %nonassoc:                            Using Precedence.
  4677. * %prec:                                Contextual Precedence.
  4678. * %pure_parser:                         Pure Decl.
  4679. * %right:                               Using Precedence.
  4680. * %start:                               Start Decl.
  4681. * %token:                               Token Decl.
  4682. * %type:                                Type Decl.
  4683. * %union:                               Union Decl.
  4684. * @N:                                   Action Features.
  4685. * calc:                                 Infix Calc.
  4686. * else, dangling:                       Shift/Reduce.
  4687. * mfcalc:                               Multi-function Calc.
  4688. * rpcalc:                               RPN Calc.
  4689. * action:                               Actions.
  4690. * action data types:                    Action Types.
  4691. * action features summary:              Action Features.
  4692. * actions in mid-rule:                  Mid-Rule Actions.
  4693. * actions, semantic:                    Semantic Actions.
  4694. * additional C code section:            C Code.
  4695. * algorithm of parser:                  Algorithm.
  4696. * associativity:                        Why Precedence.
  4697. * Backus-Naur form:                     Language and Grammar.
  4698. * Bison declaration summary:            Decl Summary.
  4699. * Bison declarations:                   Declarations.
  4700. * Bison declarations (introduction):    Bison Declarations.
  4701. * Bison grammar:                        Grammar in Bison.
  4702. * Bison invocation:                     Invocation.
  4703. * Bison parser:                         Bison Parser.
  4704. * Bison parser algorithm:               Algorithm.
  4705. * Bison symbols, table of:              Table of Symbols.
  4706. * Bison utility:                        Bison Parser.
  4707. * BNF:                                  Language and Grammar.
  4708. * C code, section for additional:       C Code.
  4709. * C declarations section:               C Declarations.
  4710. * C-language interface:                 Interface.
  4711. * calculator, infix notation:           Infix Calc.
  4712. * calculator, multi-function:           Multi-function Calc.
  4713. * calculator, simple:                   RPN Calc.
  4714. * character token:                      Symbols.
  4715. * compiling the parser:                 Rpcalc Compile.
  4716. * conflicts:                            Shift/Reduce.
  4717. * conflicts, reduce/reduce:             Reduce/Reduce.
  4718. * conflicts, suppressing warnings of:   Expect Decl.
  4719. * context-dependent precedence:         Contextual Precedence.
  4720. * context-free grammar:                 Language and Grammar.
  4721. * controlling function:                 Rpcalc Main.
  4722. * dangling else:                        Shift/Reduce.
  4723. * data types in actions:                Action Types.
  4724. * data types of semantic values:        Value Type.
  4725. * debugging:                            Debugging.
  4726. * declaration summary:                  Decl Summary.
  4727. * declarations, Bison:                  Declarations.
  4728. * declarations, Bison (introduction):   Bison Declarations.
  4729. * declarations, C:                      C Declarations.
  4730. * declaring operator precedence:        Precedence Decl.
  4731. * declaring the start symbol:           Start Decl.
  4732. * declaring token type names:           Token Decl.
  4733. * declaring value types:                Union Decl.
  4734. * declaring value types, nonterminals:  Type Decl.
  4735. * default action:                       Actions.
  4736. * default data type:                    Value Type.
  4737. * default stack limit:                  Stack Overflow.
  4738. * default start symbol:                 Start Decl.
  4739. * defining language semantics:          Semantics.
  4740. * error:                                Error Recovery.
  4741. * error recovery:                       Error Recovery.
  4742. * error recovery, simple:               Simple Error Recovery.
  4743. * error reporting function:             Error Reporting.
  4744. * error reporting routine:              Rpcalc Error.
  4745. * examples, simple:                     Examples.
  4746. * exercises:                            Exercises.
  4747. * file format:                          Grammar Layout.
  4748. * finite-state machine:                 Parser States.
  4749. * formal grammar:                       Grammar in Bison.
  4750. * format of grammar file:               Grammar Layout.
  4751. * glossary:                             Glossary.
  4752. * grammar file:                         Grammar Layout.
  4753. * grammar rule syntax:                  Rules.
  4754. * grammar rules section:                Grammar Rules.
  4755. * grammar, Bison:                       Grammar in Bison.
  4756. * grammar, context-free:                Language and Grammar.
  4757. * grouping, syntactic:                  Language and Grammar.
  4758. * infix notation calculator:            Infix Calc.
  4759. * interface:                            Interface.
  4760. * introduction:                         Introduction.
  4761. * invoking Bison:                       Invocation.
  4762. * invoking Bison under VMS:             VMS Invocation.
  4763. * LALR(1):                              Mystery Conflicts.
  4764. * language semantics, defining:         Semantics.
  4765. * layout of Bison grammar:              Grammar Layout.
  4766. * left recursion:                       Recursion.
  4767. * lexical analyzer:                     Lexical.
  4768. * lexical analyzer, purpose:            Bison Parser.
  4769. * lexical analyzer, writing:            Rpcalc Lexer.
  4770. * lexical tie-in:                       Lexical Tie-ins.
  4771. * literal token:                        Symbols.
  4772. * look-ahead token:                     Look-Ahead.
  4773. * LR(1):                                Mystery Conflicts.
  4774. * main function in simple example:      Rpcalc Main.
  4775. * mid-rule actions:                     Mid-Rule Actions.
  4776. * multi-function calculator:            Multi-function Calc.
  4777. * mutual recursion:                     Recursion.
  4778. * nonterminal symbol:                   Symbols.
  4779. * operator precedence:                  Precedence.
  4780. * operator precedence, declaring:       Precedence Decl.
  4781. * options for invoking Bison:           Invocation.
  4782. * overflow of parser stack:             Stack Overflow.
  4783. * parse error:                          Error Reporting.
  4784. * parser:                               Bison Parser.
  4785. * parser stack:                         Algorithm.
  4786. * parser stack overflow:                Stack Overflow.
  4787. * parser state:                         Parser States.
  4788. * polish notation calculator:           RPN Calc.
  4789. * precedence declarations:              Precedence Decl.
  4790. * precedence of operators:              Precedence.
  4791. * precedence, context-dependent:        Contextual Precedence.
  4792. * precedence, unary operator:           Contextual Precedence.
  4793. * preventing warnings about conflicts:  Expect Decl.
  4794. * pure parser:                          Pure Decl.
  4795. * recovery from errors:                 Error Recovery.
  4796. * recursive rule:                       Recursion.
  4797. * reduce/reduce conflict:               Reduce/Reduce.
  4798. * reduction:                            Algorithm.
  4799. * reentrant parser:                     Pure Decl.
  4800. * reverse polish notation:              RPN Calc.
  4801. * right recursion:                      Recursion.
  4802. * rule syntax:                          Rules.
  4803. * rules section for grammar:            Grammar Rules.
  4804. * running Bison (introduction):         Rpcalc Gen.
  4805. * semantic actions:                     Semantic Actions.
  4806. * semantic value:                       Semantic Values.
  4807. * semantic value type:                  Value Type.
  4808. * shift/reduce conflicts:               Shift/Reduce.
  4809. * shifting:                             Algorithm.
  4810. * simple examples:                      Examples.
  4811. * single-character literal:             Symbols.
  4812. * stack overflow:                       Stack Overflow.
  4813. * stack, parser:                        Algorithm.
  4814. * stages in using Bison:                Stages.
  4815. * start symbol:                         Language and Grammar.
  4816. * start symbol, declaring:              Start Decl.
  4817. * state (of parser):                    Parser States.
  4818. * summary, action features:             Action Features.
  4819. * summary, Bison declaration:           Decl Summary.
  4820. * suppressing conflict warnings:        Expect Decl.
  4821. * symbol:                               Symbols.
  4822. * symbol table example:                 Mfcalc Symtab.
  4823. * symbols (abstract):                   Language and Grammar.
  4824. * symbols in Bison, table of:           Table of Symbols.
  4825. * syntactic grouping:                   Language and Grammar.
  4826. * syntax error:                         Error Reporting.
  4827. * syntax of grammar rules:              Rules.
  4828. * terminal symbol:                      Symbols.
  4829. * token:                                Language and Grammar.
  4830. * token type:                           Symbols.
  4831. * token type names, declaring:          Token Decl.
  4832. * tracing the parser:                   Debugging.
  4833. * unary operator precedence:            Contextual Precedence.
  4834. * using Bison:                          Stages.
  4835. * value type, semantic:                 Value Type.
  4836. * value types, declaring:               Union Decl.
  4837. * value types, nonterminals, declaring: Type Decl.
  4838. * value, semantic:                      Semantic Values.
  4839. * VMS:                                  VMS Invocation.
  4840. * warnings, preventing:                 Expect Decl.
  4841. * writing a lexical analyzer:           Rpcalc Lexer.
  4842. * YYABORT:                              Parser Function.
  4843. * YYACCEPT:                             Parser Function.
  4844. * YYBACKUP:                             Action Features.
  4845. * yychar:                               Look-Ahead.
  4846. * yyclearin:                            Error Recovery.
  4847. * YYDEBUG:                              Debugging.
  4848. * yydebug:                              Debugging.
  4849. * YYEMPTY:                              Action Features.
  4850. * yyerrok:                              Error Recovery.
  4851. * YYERROR:                              Action Features.
  4852. * yyerror:                              Error Reporting.
  4853. * YYERROR_VERBOSE:                      Error Reporting.
  4854. * YYINITDEPTH:                          Stack Overflow.
  4855. * yylex:                                Lexical.
  4856. * yylloc:                               Token Positions.
  4857. * YYLTYPE:                              Token Positions.
  4858. * yylval:                               Token Values.
  4859. * YYMAXDEPTH:                           Stack Overflow.
  4860. * yynerrs:                              Error Reporting.
  4861. * yyparse:                              Parser Function.
  4862. * YYPRINT:                              Debugging.
  4863. * YYRECOVERING:                         Error Recovery.
  4864. * |:                                    Rules.
  4865.  
  4866.  
  4867. 
  4868. Tag Table:
  4869. Node: Top1161
  4870. Node: Introduction8389
  4871. Node: Conditions9551
  4872. Node: Copying11418
  4873. Node: Concepts30566
  4874. Node: Language and Grammar31594
  4875. Node: Grammar in Bison36605
  4876. Node: Semantic Values38378
  4877. Node: Semantic Actions40474
  4878. Node: Bison Parser41652
  4879. Node: Stages43957
  4880. Node: Grammar Layout45235
  4881. Node: Examples46487
  4882. Node: RPN Calc47617
  4883. Node: Rpcalc Decls48586
  4884. Node: Rpcalc Rules50168
  4885. Node: Rpcalc Input51963
  4886. Node: Rpcalc Line53419
  4887. Node: Rpcalc Expr54529
  4888. Node: Rpcalc Lexer56469
  4889. Node: Rpcalc Main59023
  4890. Node: Rpcalc Error59396
  4891. Node: Rpcalc Gen60396
  4892. Node: Rpcalc Compile61539
  4893. Node: Infix Calc62409
  4894. Node: Simple Error Recovery65111
  4895. Node: Multi-function Calc66993
  4896. Node: Mfcalc Decl68554
  4897. Node: Mfcalc Rules70572
  4898. Node: Mfcalc Symtab71947
  4899. Node: Exercises78116
  4900. Node: Grammar File78617
  4901. Node: Grammar Outline79380
  4902. Node: C Declarations80109
  4903. Node: Bison Declarations80684
  4904. Node: Grammar Rules81091
  4905. Node: C Code81546
  4906. Node: Symbols82471
  4907. Node: Rules86241
  4908. Node: Recursion87875
  4909. Node: Semantics89581
  4910. Node: Value Type90673
  4911. Node: Multiple Types91340
  4912. Node: Actions92351
  4913. Node: Action Types95131
  4914. Node: Mid-Rule Actions96429
  4915. Node: Declarations101993
  4916. Node: Token Decl103307
  4917. Node: Precedence Decl104625
  4918. Node: Union Decl106171
  4919. Node: Type Decl107010
  4920. Node: Expect Decl107710
  4921. Node: Start Decl109251
  4922. Node: Pure Decl109624
  4923. Node: Decl Summary110921
  4924. Node: Multiple Parsers112320
  4925. Node: Interface113798
  4926. Node: Parser Function114665
  4927. Node: Lexical115495
  4928. Node: Calling Convention116896
  4929. Node: Token Values118198
  4930. Node: Token Positions119341
  4931. Node: Pure Calling120228
  4932. Node: Error Reporting121223
  4933. Node: Action Features123343
  4934. Node: Algorithm126989
  4935. Node: Look-Ahead129277
  4936. Node: Shift/Reduce131404
  4937. Node: Precedence134310
  4938. Node: Why Precedence134956
  4939. Node: Using Precedence136806
  4940. Node: Precedence Examples137769
  4941. Node: How Precedence138465
  4942. Node: Contextual Precedence139609
  4943. Node: Parser States141395
  4944. Node: Reduce/Reduce142633
  4945. Node: Mystery Conflicts146189
  4946. Node: Stack Overflow149570
  4947. Node: Error Recovery150938
  4948. Node: Context Dependency156069
  4949. Node: Semantic Tokens156912
  4950. Node: Lexical Tie-ins159924
  4951. Node: Tie-in Recovery161467
  4952. Node: Debugging163634
  4953. Node: Invocation166980
  4954. Node: Bison Options167638
  4955. Node: Option Cross Key171270
  4956. Node: VMS Invocation171997
  4957. Node: Table of Symbols172776
  4958. Node: Glossary179358
  4959. Node: Index185537
  4960. 
  4961. End Tag Table
  4962.