home *** CD-ROM | disk | FTP | other *** search
/ RISCWORLD 7 / RISCWORLD_VOL7.iso / Software / Issue2 / SDL.ARC / !gcc / docs / bison next >
Encoding:
Text File  |  2004-10-05  |  294.7 KB  |  7,229 lines

  1. This is /home/riscos/gcc33/!gcc/docs/bison, produced by makeinfo
  2. version 4.7 from doc/bison.texinfo.
  3.  
  4.    This manual is for GNU Bison (version 1.875, 28 December 2002), the
  5. GNU parser generator.
  6.  
  7.    Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 1999,
  8. 2000, 2001, 2002 Free Software Foundation, Inc.
  9.  
  10.      Permission is granted to copy, distribute and/or modify this
  11.      document under the terms of the GNU Free Documentation License,
  12.      Version 1.1 or any later version published by the Free Software
  13.      Foundation; with no Invariant Sections, with the Front-Cover texts
  14.      being "A GNU Manual," and with the Back-Cover Texts as in (a)
  15.      below.  A copy of the license is included in the section entitled
  16.      "GNU Free Documentation License."
  17.  
  18.      (a) The FSF's Back-Cover Text is: "You have freedom to copy and
  19.      modify this GNU Manual, like GNU software.  Copies published by
  20.      the Free Software Foundation raise funds for GNU development."
  21.  
  22. INFO-DIR-SECTION GNU programming tools
  23. START-INFO-DIR-ENTRY
  24. * bison: (bison).       GNU parser generator (Yacc replacement).
  25. END-INFO-DIR-ENTRY
  26.  
  27. 
  28. File: bison,  Node: Top,  Next: Introduction,  Up: (dir)
  29.  
  30. Bison
  31. *****
  32.  
  33. This manual is for GNU Bison (version 1.875, 28 December 2002), the GNU
  34. parser generator.
  35.  
  36.    Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 1999,
  37. 2000, 2001, 2002 Free Software Foundation, Inc.
  38.  
  39.      Permission is granted to copy, distribute and/or modify this
  40.      document under the terms of the GNU Free Documentation License,
  41.      Version 1.1 or any later version published by the Free Software
  42.      Foundation; with no Invariant Sections, with the Front-Cover texts
  43.      being "A GNU Manual," and with the Back-Cover Texts as in (a)
  44.      below.  A copy of the license is included in the section entitled
  45.      "GNU Free Documentation License."
  46.  
  47.      (a) The FSF's Back-Cover Text is: "You have freedom to copy and
  48.      modify this GNU Manual, like GNU software.  Copies published by
  49.      the Free Software Foundation raise funds for GNU development."
  50.  
  51. * Menu:
  52.  
  53. * Introduction::
  54. * Conditions::
  55. * Copying::           The GNU General Public License says
  56.                         how you can copy and share Bison
  57.  
  58. Tutorial sections:
  59. * Concepts::          Basic concepts for understanding Bison.
  60. * Examples::          Three simple explained examples of using Bison.
  61.  
  62. Reference sections:
  63. * Grammar File::      Writing Bison declarations and rules.
  64. * Interface::         C-language interface to the parser function `yyparse'.
  65. * Algorithm::         How the Bison parser works at run-time.
  66. * Error Recovery::    Writing rules for error recovery.
  67. * Context Dependency::  What to do if your language syntax is too
  68.                         messy for Bison to handle straightforwardly.
  69. * Debugging::         Understanding or debugging Bison parsers.
  70. * Invocation::        How to run Bison (to produce the parser source file).
  71. * Table of Symbols::  All the keywords of the Bison language are explained.
  72. * Glossary::          Basic concepts are explained.
  73. * FAQ::               Frequently Asked Questions
  74. * Copying This Manual::  License for copying this manual.
  75. * Index::             Cross-references to the text.
  76.  
  77.  --- The Detailed Node Listing ---
  78.  
  79. The Concepts of Bison
  80.  
  81. * Language and Grammar::  Languages and context-free grammars,
  82.                             as mathematical ideas.
  83. * Grammar in Bison::  How we represent grammars for Bison's sake.
  84. * Semantic Values::   Each token or syntactic grouping can have
  85.                         a semantic value (the value of an integer,
  86.                         the name of an identifier, etc.).
  87. * Semantic Actions::  Each rule can have an action containing C code.
  88. * GLR Parsers::       Writing parsers for general context-free languages
  89. * Locations Overview::    Tracking Locations.
  90. * Bison Parser::      What are Bison's input and output,
  91.                         how is the output used?
  92. * Stages::            Stages in writing and running Bison grammars.
  93. * Grammar Layout::    Overall structure of a Bison grammar file.
  94.  
  95. Examples
  96.  
  97. * RPN Calc::          Reverse polish notation calculator;
  98.                         a first example with no operator precedence.
  99. * Infix Calc::        Infix (algebraic) notation calculator.
  100.                         Operator precedence is introduced.
  101. * Simple Error Recovery::  Continuing after syntax errors.
  102. * Location Tracking Calc:: Demonstrating the use of @N and @$.
  103. * Multi-function Calc::  Calculator with memory and trig functions.
  104.                            It uses multiple data-types for semantic values.
  105. * Exercises::         Ideas for improving the multi-function calculator.
  106.  
  107. Reverse Polish Notation Calculator
  108.  
  109. * Decls: Rpcalc Decls.  Prologue (declarations) for rpcalc.
  110. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  111. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  112. * Main: Rpcalc Main.    The controlling function.
  113. * Error: Rpcalc Error.  The error reporting function.
  114. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  115. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  116.  
  117. Grammar Rules for `rpcalc'
  118.  
  119. * Rpcalc Input::
  120. * Rpcalc Line::
  121. * Rpcalc Expr::
  122.  
  123. Location Tracking Calculator: `ltcalc'
  124.  
  125. * Decls: Ltcalc Decls.  Bison and C declarations for ltcalc.
  126. * Rules: Ltcalc Rules.  Grammar rules for ltcalc, with explanations.
  127. * Lexer: Ltcalc Lexer.  The lexical analyzer.
  128.  
  129. Multi-Function Calculator: `mfcalc'
  130.  
  131. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  132. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  133. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  134.  
  135. Bison Grammar Files
  136.  
  137. * Grammar Outline::   Overall layout of the grammar file.
  138. * Symbols::           Terminal and nonterminal symbols.
  139. * Rules::             How to write grammar rules.
  140. * Recursion::         Writing recursive rules.
  141. * Semantics::         Semantic values and actions.
  142. * Locations::         Locations and actions.
  143. * Declarations::      All kinds of Bison declarations are described here.
  144. * Multiple Parsers::  Putting more than one Bison parser in one program.
  145.  
  146. Outline of a Bison Grammar
  147.  
  148. * Prologue::          Syntax and usage of the prologue.
  149. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  150. * Grammar Rules::     Syntax and usage of the grammar rules section.
  151. * Epilogue::          Syntax and usage of the epilogue.
  152.  
  153. Defining Language Semantics
  154.  
  155. * Value Type::        Specifying one data type for all semantic values.
  156. * Multiple Types::    Specifying several alternative data types.
  157. * Actions::           An action is the semantic definition of a grammar rule.
  158. * Action Types::      Specifying data types for actions to operate on.
  159. * Mid-Rule Actions::  Most actions go at the end of a rule.
  160.                       This says when, why and how to use the exceptional
  161.                         action in the middle of a rule.
  162.  
  163. Tracking Locations
  164.  
  165. * Location Type::               Specifying a data type for locations.
  166. * Actions and Locations::       Using locations in actions.
  167. * Location Default Action::     Defining a general way to compute locations.
  168.  
  169. Bison Declarations
  170.  
  171. * Token Decl::        Declaring terminal symbols.
  172. * Precedence Decl::   Declaring terminals with precedence and associativity.
  173. * Union Decl::        Declaring the set of all semantic value types.
  174. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  175. * Destructor Decl::   Declaring how symbols are freed.
  176. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  177. * Start Decl::        Specifying the start symbol.
  178. * Pure Decl::         Requesting a reentrant parser.
  179. * Decl Summary::      Table of all Bison declarations.
  180.  
  181. Parser C-Language Interface
  182.  
  183. * Parser Function::   How to call `yyparse' and what it returns.
  184. * Lexical::           You must supply a function `yylex'
  185.                         which reads tokens.
  186. * Error Reporting::   You must supply a function `yyerror'.
  187. * Action Features::   Special features for use in actions.
  188.  
  189. The Lexical Analyzer Function `yylex'
  190.  
  191. * Calling Convention::  How `yyparse' calls `yylex'.
  192. * Token Values::      How `yylex' must return the semantic value
  193.                         of the token it has read.
  194. * Token Positions::   How `yylex' must return the text position
  195.                         (line number, etc.) of the token, if the
  196.                         actions want that.
  197. * Pure Calling::      How the calling convention differs
  198.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  199.  
  200. The Bison Parser Algorithm
  201.  
  202. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  203. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  204. * Precedence::        Operator precedence works by resolving conflicts.
  205. * Contextual Precedence::  When an operator's precedence depends on context.
  206. * Parser States::     The parser is a finite-state-machine with stack.
  207. * Reduce/Reduce::     When two rules are applicable in the same situation.
  208. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  209. * Generalized LR Parsing::  Parsing arbitrary context-free grammars.
  210. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  211.  
  212. Operator Precedence
  213.  
  214. * Why Precedence::    An example showing why precedence is needed.
  215. * Using Precedence::  How to specify precedence in Bison grammars.
  216. * Precedence Examples::  How these features are used in the previous example.
  217. * How Precedence::    How they work.
  218.  
  219. Handling Context Dependencies
  220.  
  221. * Semantic Tokens::   Token parsing can depend on the semantic context.
  222. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  223. * Tie-in Recovery::   Lexical tie-ins have implications for how
  224.                         error recovery rules must be written.
  225.  
  226. Debugging Your Parser
  227.  
  228. * Understanding::     Understanding the structure of your parser.
  229. * Tracing::           Tracing the execution of your parser.
  230.  
  231. Invoking Bison
  232.  
  233. * Bison Options::     All the options described in detail,
  234.                         in alphabetical order by short options.
  235. * Option Cross Key::  Alphabetical list of long options.
  236. * Yacc Library::      Yacc-compatible `yylex' and `main'.
  237.  
  238. Frequently Asked Questions
  239.  
  240. * Parser Stack Overflow::      Breaking the Stack Limits
  241.  
  242. Copying This Manual
  243.  
  244. * GNU Free Documentation License::  License for copying this manual.
  245.  
  246. 
  247. File: bison,  Node: Introduction,  Next: Conditions,  Prev: Top,  Up: Top
  248.  
  249. Introduction
  250. ************
  251.  
  252. "Bison" is a general-purpose parser generator that converts a grammar
  253. description for an LALR(1) context-free grammar into a C program to
  254. parse that grammar.  Once you are proficient with Bison, you may use it
  255. to develop a wide range of language parsers, from those used in simple
  256. desk calculators to complex programming languages.
  257.  
  258.    Bison is upward compatible with Yacc: all properly-written Yacc
  259. grammars ought to work with Bison with no change.  Anyone familiar with
  260. Yacc should be able to use Bison with little trouble.  You need to be
  261. fluent in C programming in order to use Bison or to understand this
  262. manual.
  263.  
  264.    We begin with tutorial chapters that explain the basic concepts of
  265. using Bison and show three explained examples, each building on the
  266. last.  If you don't know Bison or Yacc, start by reading these
  267. chapters.  Reference chapters follow which describe specific aspects of
  268. Bison in detail.
  269.  
  270.    Bison was written primarily by Robert Corbett; Richard Stallman made
  271. it Yacc-compatible.  Wilfred Hansen of Carnegie Mellon University added
  272. multi-character string literals and other features.
  273.  
  274.    This edition corresponds to version 1.875 of Bison.
  275.  
  276. 
  277. File: bison,  Node: Conditions,  Next: Copying,  Prev: Introduction,  Up: Top
  278.  
  279. Conditions for Using Bison
  280. **************************
  281.  
  282. As of Bison version 1.24, we have changed the distribution terms for
  283. `yyparse' to permit using Bison's output in nonfree programs when Bison
  284. is generating C code for LALR(1) parsers.  Formerly, these parsers
  285. could be used only in programs that were free software.
  286.  
  287.    The other GNU programming tools, such as the GNU C compiler, have
  288. never had such a requirement.  They could always be used for nonfree
  289. software.  The reason Bison was different was not due to a special
  290. policy decision; it resulted from applying the usual General Public
  291. License to all of the Bison source code.
  292.  
  293.    The output of the Bison utility--the Bison parser file--contains a
  294. verbatim copy of a sizable piece of Bison, which is the code for the
  295. `yyparse' function.  (The actions from your grammar are inserted into
  296. this function at one point, but the rest of the function is not
  297. changed.)  When we applied the GPL terms to the code for `yyparse', the
  298. effect was to restrict the use of Bison output to free software.
  299.  
  300.    We didn't change the terms because of sympathy for people who want to
  301. make software proprietary.  *Software should be free.*  But we
  302. concluded that limiting Bison's use to free software was doing little to
  303. encourage people to make other software free.  So we decided to make the
  304. practical conditions for using Bison match the practical conditions for
  305. using the other GNU tools.
  306.  
  307.    This exception applies only when Bison is generating C code for a
  308. LALR(1) parser; otherwise, the GPL terms operate as usual.  You can
  309. tell whether the exception applies to your `.c' output file by
  310. inspecting it to see whether it says "As a special exception, when this
  311. file is copied by Bison into a Bison output file, you may use that
  312. output file without restriction."
  313.  
  314. 
  315. File: bison,  Node: Copying,  Next: Concepts,  Prev: Conditions,  Up: Top
  316.  
  317. GNU GENERAL PUBLIC LICENSE
  318. **************************
  319.  
  320.                          Version 2, June 1991
  321.  
  322.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  323.      59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
  324.  
  325.      Everyone is permitted to copy and distribute verbatim copies
  326.      of this license document, but changing it is not allowed.
  327.  
  328. Preamble
  329. ========
  330.  
  331. The licenses for most software are designed to take away your freedom
  332. to share and change it.  By contrast, the GNU General Public License is
  333. intended to guarantee your freedom to share and change free
  334. software--to make sure the software is free for all its users.  This
  335. General Public License applies to most of the Free Software
  336. Foundation's software and to any other program whose authors commit to
  337. using it.  (Some other Free Software Foundation software is covered by
  338. the GNU Library General Public License instead.)  You can apply it to
  339. your programs, too.
  340.  
  341.    When we speak of free software, we are referring to freedom, not
  342. price.  Our General Public Licenses are designed to make sure that you
  343. have the freedom to distribute copies of free software (and charge for
  344. this service if you wish), that you receive source code or can get it
  345. if you want it, that you can change the software or use pieces of it in
  346. new free programs; and that you know you can do these things.
  347.  
  348.    To protect your rights, we need to make restrictions that forbid
  349. anyone to deny you these rights or to ask you to surrender the rights.
  350. These restrictions translate to certain responsibilities for you if you
  351. distribute copies of the software, or if you modify it.
  352.  
  353.    For example, if you distribute copies of such a program, whether
  354. gratis or for a fee, you must give the recipients all the rights that
  355. you have.  You must make sure that they, too, receive or can get the
  356. source code.  And you must show them these terms so they know their
  357. rights.
  358.  
  359.    We protect your rights with two steps: (1) copyright the software,
  360. and (2) offer you this license which gives you legal permission to copy,
  361. distribute and/or modify the software.
  362.  
  363.    Also, for each author's protection and ours, we want to make certain
  364. that everyone understands that there is no warranty for this free
  365. software.  If the software is modified by someone else and passed on, we
  366. want its recipients to know that what they have is not the original, so
  367. that any problems introduced by others will not reflect on the original
  368. authors' reputations.
  369.  
  370.    Finally, any free program is threatened constantly by software
  371. patents.  We wish to avoid the danger that redistributors of a free
  372. program will individually obtain patent licenses, in effect making the
  373. program proprietary.  To prevent this, we have made it clear that any
  374. patent must be licensed for everyone's free use or not licensed at all.
  375.  
  376.    The precise terms and conditions for copying, distribution and
  377. modification follow.
  378.  
  379.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  380.   0. This License applies to any program or other work which contains a
  381.      notice placed by the copyright holder saying it may be distributed
  382.      under the terms of this General Public License.  The "Program",
  383.      below, refers to any such program or work, and a "work based on
  384.      the Program" means either the Program or any derivative work under
  385.      copyright law: that is to say, a work containing the Program or a
  386.      portion of it, either verbatim or with modifications and/or
  387.      translated into another language.  (Hereinafter, translation is
  388.      included without limitation in the term "modification".)  Each
  389.      licensee is addressed as "you".
  390.  
  391.      Activities other than copying, distribution and modification are
  392.      not covered by this License; they are outside its scope.  The act
  393.      of running the Program is not restricted, and the output from the
  394.      Program is covered only if its contents constitute a work based on
  395.      the Program (independent of having been made by running the
  396.      Program).  Whether that is true depends on what the Program does.
  397.  
  398.   1. You may copy and distribute verbatim copies of the Program's
  399.      source code as you receive it, in any medium, provided that you
  400.      conspicuously and appropriately publish on each copy an appropriate
  401.      copyright notice and disclaimer of warranty; keep intact all the
  402.      notices that refer to this License and to the absence of any
  403.      warranty; and give any other recipients of the Program a copy of
  404.      this License along with the Program.
  405.  
  406.      You may charge a fee for the physical act of transferring a copy,
  407.      and you may at your option offer warranty protection in exchange
  408.      for a fee.
  409.  
  410.   2. You may modify your copy or copies of the Program or any portion
  411.      of it, thus forming a work based on the Program, and copy and
  412.      distribute such modifications or work under the terms of Section 1
  413.      above, provided that you also meet all of these conditions:
  414.  
  415.        a. You must cause the modified files to carry prominent notices
  416.           stating that you changed the files and the date of any change.
  417.  
  418.        b. You must cause any work that you distribute or publish, that
  419.           in whole or in part contains or is derived from the Program
  420.           or any part thereof, to be licensed as a whole at no charge
  421.           to all third parties under the terms of this License.
  422.  
  423.        c. If the modified program normally reads commands interactively
  424.           when run, you must cause it, when started running for such
  425.           interactive use in the most ordinary way, to print or display
  426.           an announcement including an appropriate copyright notice and
  427.           a notice that there is no warranty (or else, saying that you
  428.           provide a warranty) and that users may redistribute the
  429.           program under these conditions, and telling the user how to
  430.           view a copy of this License.  (Exception: if the Program
  431.           itself is interactive but does not normally print such an
  432.           announcement, your work based on the Program is not required
  433.           to print an announcement.)
  434.  
  435.      These requirements apply to the modified work as a whole.  If
  436.      identifiable sections of that work are not derived from the
  437.      Program, and can be reasonably considered independent and separate
  438.      works in themselves, then this License, and its terms, do not
  439.      apply to those sections when you distribute them as separate
  440.      works.  But when you distribute the same sections as part of a
  441.      whole which is a work based on the Program, the distribution of
  442.      the whole must be on the terms of this License, whose permissions
  443.      for other licensees extend to the entire whole, and thus to each
  444.      and every part regardless of who wrote it.
  445.  
  446.      Thus, it is not the intent of this section to claim rights or
  447.      contest your rights to work written entirely by you; rather, the
  448.      intent is to exercise the right to control the distribution of
  449.      derivative or collective works based on the Program.
  450.  
  451.      In addition, mere aggregation of another work not based on the
  452.      Program with the Program (or with a work based on the Program) on
  453.      a volume of a storage or distribution medium does not bring the
  454.      other work under the scope of this License.
  455.  
  456.   3. You may copy and distribute the Program (or a work based on it,
  457.      under Section 2) in object code or executable form under the terms
  458.      of Sections 1 and 2 above provided that you also do one of the
  459.      following:
  460.  
  461.        a. Accompany it with the complete corresponding machine-readable
  462.           source code, which must be distributed under the terms of
  463.           Sections 1 and 2 above on a medium customarily used for
  464.           software interchange; or,
  465.  
  466.        b. Accompany it with a written offer, valid for at least three
  467.           years, to give any third party, for a charge no more than your
  468.           cost of physically performing source distribution, a complete
  469.           machine-readable copy of the corresponding source code, to be
  470.           distributed under the terms of Sections 1 and 2 above on a
  471.           medium customarily used for software interchange; or,
  472.  
  473.        c. Accompany it with the information you received as to the offer
  474.           to distribute corresponding source code.  (This alternative is
  475.           allowed only for noncommercial distribution and only if you
  476.           received the program in object code or executable form with
  477.           such an offer, in accord with Subsection b above.)
  478.  
  479.      The source code for a work means the preferred form of the work for
  480.      making modifications to it.  For an executable work, complete
  481.      source code means all the source code for all modules it contains,
  482.      plus any associated interface definition files, plus the scripts
  483.      used to control compilation and installation of the executable.
  484.      However, as a special exception, the source code distributed need
  485.      not include anything that is normally distributed (in either
  486.      source or binary form) with the major components (compiler,
  487.      kernel, and so on) of the operating system on which the executable
  488.      runs, unless that component itself accompanies the executable.
  489.  
  490.      If distribution of executable or object code is made by offering
  491.      access to copy from a designated place, then offering equivalent
  492.      access to copy the source code from the same place counts as
  493.      distribution of the source code, even though third parties are not
  494.      compelled to copy the source along with the object code.
  495.  
  496.   4. You may not copy, modify, sublicense, or distribute the Program
  497.      except as expressly provided under this License.  Any attempt
  498.      otherwise to copy, modify, sublicense or distribute the Program is
  499.      void, and will automatically terminate your rights under this
  500.      License.  However, parties who have received copies, or rights,
  501.      from you under this License will not have their licenses
  502.      terminated so long as such parties remain in full compliance.
  503.  
  504.   5. You are not required to accept this License, since you have not
  505.      signed it.  However, nothing else grants you permission to modify
  506.      or distribute the Program or its derivative works.  These actions
  507.      are prohibited by law if you do not accept this License.
  508.      Therefore, by modifying or distributing the Program (or any work
  509.      based on the Program), you indicate your acceptance of this
  510.      License to do so, and all its terms and conditions for copying,
  511.      distributing or modifying the Program or works based on it.
  512.  
  513.   6. Each time you redistribute the Program (or any work based on the
  514.      Program), the recipient automatically receives a license from the
  515.      original licensor to copy, distribute or modify the Program
  516.      subject to these terms and conditions.  You may not impose any
  517.      further restrictions on the recipients' exercise of the rights
  518.      granted herein.  You are not responsible for enforcing compliance
  519.      by third parties to this License.
  520.  
  521.   7. If, as a consequence of a court judgment or allegation of patent
  522.      infringement or for any other reason (not limited to patent
  523.      issues), conditions are imposed on you (whether by court order,
  524.      agreement or otherwise) that contradict the conditions of this
  525.      License, they do not excuse you from the conditions of this
  526.      License.  If you cannot distribute so as to satisfy simultaneously
  527.      your obligations under this License and any other pertinent
  528.      obligations, then as a consequence you may not distribute the
  529.      Program at all.  For example, if a patent license would not permit
  530.      royalty-free redistribution of the Program by all those who
  531.      receive copies directly or indirectly through you, then the only
  532.      way you could satisfy both it and this License would be to refrain
  533.      entirely from distribution of the Program.
  534.  
  535.      If any portion of this section is held invalid or unenforceable
  536.      under any particular circumstance, the balance of the section is
  537.      intended to apply and the section as a whole is intended to apply
  538.      in other circumstances.
  539.  
  540.      It is not the purpose of this section to induce you to infringe any
  541.      patents or other property right claims or to contest validity of
  542.      any such claims; this section has the sole purpose of protecting
  543.      the integrity of the free software distribution system, which is
  544.      implemented by public license practices.  Many people have made
  545.      generous contributions to the wide range of software distributed
  546.      through that system in reliance on consistent application of that
  547.      system; it is up to the author/donor to decide if he or she is
  548.      willing to distribute software through any other system and a
  549.      licensee cannot impose that choice.
  550.  
  551.      This section is intended to make thoroughly clear what is believed
  552.      to be a consequence of the rest of this License.
  553.  
  554.   8. If the distribution and/or use of the Program is restricted in
  555.      certain countries either by patents or by copyrighted interfaces,
  556.      the original copyright holder who places the Program under this
  557.      License may add an explicit geographical distribution limitation
  558.      excluding those countries, so that distribution is permitted only
  559.      in or among countries not thus excluded.  In such case, this
  560.      License incorporates the limitation as if written in the body of
  561.      this License.
  562.  
  563.   9. The Free Software Foundation may publish revised and/or new
  564.      versions of the General Public License from time to time.  Such
  565.      new versions will be similar in spirit to the present version, but
  566.      may differ in detail to address new problems or concerns.
  567.  
  568.      Each version is given a distinguishing version number.  If the
  569.      Program specifies a version number of this License which applies
  570.      to it and "any later version", you have the option of following
  571.      the terms and conditions either of that version or of any later
  572.      version published by the Free Software Foundation.  If the Program
  573.      does not specify a version number of this License, you may choose
  574.      any version ever published by the Free Software Foundation.
  575.  
  576.  10. If you wish to incorporate parts of the Program into other free
  577.      programs whose distribution conditions are different, write to the
  578.      author to ask for permission.  For software which is copyrighted
  579.      by the Free Software Foundation, write to the Free Software
  580.      Foundation; we sometimes make exceptions for this.  Our decision
  581.      will be guided by the two goals of preserving the free status of
  582.      all derivatives of our free software and of promoting the sharing
  583.      and reuse of software generally.
  584.  
  585.                                 NO WARRANTY
  586.  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  587.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  588.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  589.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  590.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  591.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  592.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  593.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  594.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  595.      SERVICING, REPAIR OR CORRECTION.
  596.  
  597.  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  598.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  599.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  600.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  601.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  602.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  603.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  604.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  605.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  606.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  607.  
  608.                       END OF TERMS AND CONDITIONS
  609. Appendix: How to Apply These Terms to Your New Programs
  610. =======================================================
  611.  
  612. If you develop a new program, and you want it to be of the greatest
  613. possible use to the public, the best way to achieve this is to make it
  614. free software which everyone can redistribute and change under these
  615. terms.
  616.  
  617.    To do so, attach the following notices to the program.  It is safest
  618. to attach them to the start of each source file to most effectively
  619. convey the exclusion of warranty; and each file should have at least
  620. the "copyright" line and a pointer to where the full notice is found.
  621.  
  622.      ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  623.      Copyright (C) YYYY  NAME OF AUTHOR
  624.  
  625.      This program is free software; you can redistribute it and/or modify
  626.      it under the terms of the GNU General Public License as published by
  627.      the Free Software Foundation; either version 2 of the License, or
  628.      (at your option) any later version.
  629.  
  630.      This program is distributed in the hope that it will be useful,
  631.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  632.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  633.      GNU General Public License for more details.
  634.  
  635.      You should have received a copy of the GNU General Public License
  636.      along with this program; if not, write to the Free Software
  637.      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  638.  
  639.    Also add information on how to contact you by electronic and paper
  640. mail.
  641.  
  642.    If the program is interactive, make it output a short notice like
  643. this when it starts in an interactive mode:
  644.  
  645.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  646.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  647.      This is free software, and you are welcome to redistribute it
  648.      under certain conditions; type `show c' for details.
  649.  
  650.    The hypothetical commands `show w' and `show c' should show the
  651. appropriate parts of the General Public License.  Of course, the
  652. commands you use may be called something other than `show w' and `show
  653. c'; they could even be mouse-clicks or menu items--whatever suits your
  654. program.
  655.  
  656.    You should also get your employer (if you work as a programmer) or
  657. your school, if any, to sign a "copyright disclaimer" for the program,
  658. if necessary.  Here is a sample; alter the names:
  659.  
  660.      Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  661.      `Gnomovision' (which makes passes at compilers) written by James Hacker.
  662.  
  663.      SIGNATURE OF TY COON, 1 April 1989
  664.      Ty Coon, President of Vice
  665.  
  666.    This General Public License does not permit incorporating your
  667. program into proprietary programs.  If your program is a subroutine
  668. library, you may consider it more useful to permit linking proprietary
  669. applications with the library.  If this is what you want to do, use the
  670. GNU Library General Public License instead of this License.
  671.  
  672. 
  673. File: bison,  Node: Concepts,  Next: Examples,  Prev: Copying,  Up: Top
  674.  
  675. 1 The Concepts of Bison
  676. ***********************
  677.  
  678. This chapter introduces many of the basic concepts without which the
  679. details of Bison will not make sense.  If you do not already know how to
  680. use Bison or Yacc, we suggest you start by reading this chapter
  681. carefully.
  682.  
  683. * Menu:
  684.  
  685. * Language and Grammar::  Languages and context-free grammars,
  686.                             as mathematical ideas.
  687. * Grammar in Bison::  How we represent grammars for Bison's sake.
  688. * Semantic Values::   Each token or syntactic grouping can have
  689.                         a semantic value (the value of an integer,
  690.                         the name of an identifier, etc.).
  691. * Semantic Actions::  Each rule can have an action containing C code.
  692. * GLR Parsers::       Writing parsers for general context-free languages
  693. * Locations Overview::    Tracking Locations.
  694. * Bison Parser::      What are Bison's input and output,
  695.                         how is the output used?
  696. * Stages::            Stages in writing and running Bison grammars.
  697. * Grammar Layout::    Overall structure of a Bison grammar file.
  698.  
  699. 
  700. File: bison,  Node: Language and Grammar,  Next: Grammar in Bison,  Up: Concepts
  701.  
  702. 1.1 Languages and Context-Free Grammars
  703. =======================================
  704.  
  705. In order for Bison to parse a language, it must be described by a
  706. "context-free grammar".  This means that you specify one or more
  707. "syntactic groupings" and give rules for constructing them from their
  708. parts.  For example, in the C language, one kind of grouping is called
  709. an `expression'.  One rule for making an expression might be, "An
  710. expression can be made of a minus sign and another expression".
  711. Another would be, "An expression can be an integer".  As you can see,
  712. rules are often recursive, but there must be at least one rule which
  713. leads out of the recursion.
  714.  
  715.    The most common formal system for presenting such rules for humans
  716. to read is "Backus-Naur Form" or "BNF", which was developed in order to
  717. specify the language Algol 60.  Any grammar expressed in BNF is a
  718. context-free grammar.  The input to Bison is essentially
  719. machine-readable BNF.
  720.  
  721.    There are various important subclasses of context-free grammar.
  722. Although it can handle almost all context-free grammars, Bison is
  723. optimized for what are called LALR(1) grammars.  In brief, in these
  724. grammars, it must be possible to tell how to parse any portion of an
  725. input string with just a single token of look-ahead.  Strictly
  726. speaking, that is a description of an LR(1) grammar, and LALR(1)
  727. involves additional restrictions that are hard to explain simply; but
  728. it is rare in actual practice to find an LR(1) grammar that fails to be
  729. LALR(1).  *Note Mysterious Reduce/Reduce Conflicts: Mystery Conflicts,
  730. for more information on this.
  731.  
  732.    Parsers for LALR(1) grammars are "deterministic", meaning roughly
  733. that the next grammar rule to apply at any point in the input is
  734. uniquely determined by the preceding input and a fixed, finite portion
  735. (called a "look-ahead") of the remaining input.  A context-free grammar
  736. can be "ambiguous", meaning that there are multiple ways to apply the
  737. grammar rules to get the some inputs.  Even unambiguous grammars can be
  738. "non-deterministic", meaning that no fixed look-ahead always suffices
  739. to determine the next grammar rule to apply.  With the proper
  740. declarations, Bison is also able to parse these more general
  741. context-free grammars, using a technique known as GLR parsing (for
  742. Generalized LR).  Bison's GLR parsers are able to handle any
  743. context-free grammar for which the number of possible parses of any
  744. given string is finite.
  745.  
  746.    In the formal grammatical rules for a language, each kind of
  747. syntactic unit or grouping is named by a "symbol".  Those which are
  748. built by grouping smaller constructs according to grammatical rules are
  749. called "nonterminal symbols"; those which can't be subdivided are called
  750. "terminal symbols" or "token types".  We call a piece of input
  751. corresponding to a single terminal symbol a "token", and a piece
  752. corresponding to a single nonterminal symbol a "grouping".
  753.  
  754.    We can use the C language as an example of what symbols, terminal and
  755. nonterminal, mean.  The tokens of C are identifiers, constants (numeric
  756. and string), and the various keywords, arithmetic operators and
  757. punctuation marks.  So the terminal symbols of a grammar for C include
  758. `identifier', `number', `string', plus one symbol for each keyword,
  759. operator or punctuation mark: `if', `return', `const', `static', `int',
  760. `char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
  761. (These tokens can be subdivided into characters, but that is a matter of
  762. lexicography, not grammar.)
  763.  
  764.    Here is a simple C function subdivided into tokens:
  765.  
  766.      int             /* keyword `int' */
  767.      square (int x)  /* identifier, open-paren, identifier,
  768.                         identifier, close-paren */
  769.      {               /* open-brace */
  770.        return x * x; /* keyword `return', identifier, asterisk,
  771.                         identifier, semicolon */
  772.      }               /* close-brace */
  773.  
  774.    The syntactic groupings of C include the expression, the statement,
  775. the declaration, and the function definition.  These are represented in
  776. the grammar of C by nonterminal symbols `expression', `statement',
  777. `declaration' and `function definition'.  The full grammar uses dozens
  778. of additional language constructs, each with its own nonterminal
  779. symbol, in order to express the meanings of these four.  The example
  780. above is a function definition; it contains one declaration, and one
  781. statement.  In the statement, each `x' is an expression and so is `x *
  782. x'.
  783.  
  784.    Each nonterminal symbol must have grammatical rules showing how it
  785. is made out of simpler constructs.  For example, one kind of C
  786. statement is the `return' statement; this would be described with a
  787. grammar rule which reads informally as follows:
  788.  
  789.      A `statement' can be made of a `return' keyword, an `expression'
  790.      and a `semicolon'.
  791.  
  792. There would be many other rules for `statement', one for each kind of
  793. statement in C.
  794.  
  795.    One nonterminal symbol must be distinguished as the special one which
  796. defines a complete utterance in the language.  It is called the "start
  797. symbol".  In a compiler, this means a complete input program.  In the C
  798. language, the nonterminal symbol `sequence of definitions and
  799. declarations' plays this role.
  800.  
  801.    For example, `1 + 2' is a valid C expression--a valid part of a C
  802. program--but it is not valid as an _entire_ C program.  In the
  803. context-free grammar of C, this follows from the fact that `expression'
  804. is not the start symbol.
  805.  
  806.    The Bison parser reads a sequence of tokens as its input, and groups
  807. the tokens using the grammar rules.  If the input is valid, the end
  808. result is that the entire token sequence reduces to a single grouping
  809. whose symbol is the grammar's start symbol.  If we use a grammar for C,
  810. the entire input must be a `sequence of definitions and declarations'.
  811. If not, the parser reports a syntax error.
  812.  
  813. 
  814. File: bison,  Node: Grammar in Bison,  Next: Semantic Values,  Prev: Language and Grammar,  Up: Concepts
  815.  
  816. 1.2 From Formal Rules to Bison Input
  817. ====================================
  818.  
  819. A formal grammar is a mathematical construct.  To define the language
  820. for Bison, you must write a file expressing the grammar in Bison syntax:
  821. a "Bison grammar" file.  *Note Bison Grammar Files: Grammar File.
  822.  
  823.    A nonterminal symbol in the formal grammar is represented in Bison
  824. input as an identifier, like an identifier in C.  By convention, it
  825. should be in lower case, such as `expr', `stmt' or `declaration'.
  826.  
  827.    The Bison representation for a terminal symbol is also called a
  828. "token type".  Token types as well can be represented as C-like
  829. identifiers.  By convention, these identifiers should be upper case to
  830. distinguish them from nonterminals: for example, `INTEGER',
  831. `IDENTIFIER', `IF' or `RETURN'.  A terminal symbol that stands for a
  832. particular keyword in the language should be named after that keyword
  833. converted to upper case.  The terminal symbol `error' is reserved for
  834. error recovery.  *Note Symbols::.
  835.  
  836.    A terminal symbol can also be represented as a character literal,
  837. just like a C character constant.  You should do this whenever a token
  838. is just a single character (parenthesis, plus-sign, etc.): use that
  839. same character in a literal as the terminal symbol for that token.
  840.  
  841.    A third way to represent a terminal symbol is with a C string
  842. constant containing several characters.  *Note Symbols::, for more
  843. information.
  844.  
  845.    The grammar rules also have an expression in Bison syntax.  For
  846. example, here is the Bison rule for a C `return' statement.  The
  847. semicolon in quotes is a literal character token, representing part of
  848. the C syntax for the statement; the naked semicolon, and the colon, are
  849. Bison punctuation used in every rule.
  850.  
  851.      stmt:   RETURN expr ';'
  852.              ;
  853.  
  854. *Note Syntax of Grammar Rules: Rules.
  855.  
  856. 
  857. File: bison,  Node: Semantic Values,  Next: Semantic Actions,  Prev: Grammar in Bison,  Up: Concepts
  858.  
  859. 1.3 Semantic Values
  860. ===================
  861.  
  862. A formal grammar selects tokens only by their classifications: for
  863. example, if a rule mentions the terminal symbol `integer constant', it
  864. means that _any_ integer constant is grammatically valid in that
  865. position.  The precise value of the constant is irrelevant to how to
  866. parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
  867. equally grammatical.
  868.  
  869.    But the precise value is very important for what the input means
  870. once it is parsed.  A compiler is useless if it fails to distinguish
  871. between 4, 1 and 3989 as constants in the program!  Therefore, each
  872. token in a Bison grammar has both a token type and a "semantic value".
  873. *Note Defining Language Semantics: Semantics, for details.
  874.  
  875.    The token type is a terminal symbol defined in the grammar, such as
  876. `INTEGER', `IDENTIFIER' or `',''.  It tells everything you need to know
  877. to decide where the token may validly appear and how to group it with
  878. other tokens.  The grammar rules know nothing about tokens except their
  879. types.
  880.  
  881.    The semantic value has all the rest of the information about the
  882. meaning of the token, such as the value of an integer, or the name of an
  883. identifier.  (A token such as `','' which is just punctuation doesn't
  884. need to have any semantic value.)
  885.  
  886.    For example, an input token might be classified as token type
  887. `INTEGER' and have the semantic value 4.  Another input token might
  888. have the same token type `INTEGER' but value 3989.  When a grammar rule
  889. says that `INTEGER' is allowed, either of these tokens is acceptable
  890. because each is an `INTEGER'.  When the parser accepts the token, it
  891. keeps track of the token's semantic value.
  892.  
  893.    Each grouping can also have a semantic value as well as its
  894. nonterminal symbol.  For example, in a calculator, an expression
  895. typically has a semantic value that is a number.  In a compiler for a
  896. programming language, an expression typically has a semantic value that
  897. is a tree structure describing the meaning of the expression.
  898.  
  899. 
  900. File: bison,  Node: Semantic Actions,  Next: GLR Parsers,  Prev: Semantic Values,  Up: Concepts
  901.  
  902. 1.4 Semantic Actions
  903. ====================
  904.  
  905. In order to be useful, a program must do more than parse input; it must
  906. also produce some output based on the input.  In a Bison grammar, a
  907. grammar rule can have an "action" made up of C statements.  Each time
  908. the parser recognizes a match for that rule, the action is executed.
  909. *Note Actions::.
  910.  
  911.    Most of the time, the purpose of an action is to compute the
  912. semantic value of the whole construct from the semantic values of its
  913. parts.  For example, suppose we have a rule which says an expression
  914. can be the sum of two expressions.  When the parser recognizes such a
  915. sum, each of the subexpressions has a semantic value which describes
  916. how it was built up.  The action for this rule should create a similar
  917. sort of value for the newly recognized larger expression.
  918.  
  919.    For example, here is a rule that says an expression can be the sum of
  920. two subexpressions:
  921.  
  922.      expr: expr '+' expr   { $$ = $1 + $3; }
  923.              ;
  924.  
  925. The action says how to produce the semantic value of the sum expression
  926. from the values of the two subexpressions.
  927.  
  928. 
  929. File: bison,  Node: GLR Parsers,  Next: Locations Overview,  Prev: Semantic Actions,  Up: Concepts
  930.  
  931. 1.5 Writing GLR Parsers
  932. =======================
  933.  
  934. In some grammars, there will be cases where Bison's standard LALR(1)
  935. parsing algorithm cannot decide whether to apply a certain grammar rule
  936. at a given point.  That is, it may not be able to decide (on the basis
  937. of the input read so far) which of two possible reductions
  938. (applications of a grammar rule) applies, or whether to apply a
  939. reduction or read more of the input and apply a reduction later in the
  940. input.  These are known respectively as "reduce/reduce" conflicts
  941. (*note Reduce/Reduce::), and "shift/reduce" conflicts (*note
  942. Shift/Reduce::).
  943.  
  944.    To use a grammar that is not easily modified to be LALR(1), a more
  945. general parsing algorithm is sometimes necessary.  If you include
  946. `%glr-parser' among the Bison declarations in your file (*note Grammar
  947. Outline::), the result will be a Generalized LR (GLR) parser.  These
  948. parsers handle Bison grammars that contain no unresolved conflicts
  949. (i.e., after applying precedence declarations) identically to LALR(1)
  950. parsers.  However, when faced with unresolved shift/reduce and
  951. reduce/reduce conflicts, GLR parsers use the simple expedient of doing
  952. both, effectively cloning the parser to follow both possibilities.
  953. Each of the resulting parsers can again split, so that at any given
  954. time, there can be any number of possible parses being explored.  The
  955. parsers proceed in lockstep; that is, all of them consume (shift) a
  956. given input symbol before any of them proceed to the next.  Each of the
  957. cloned parsers eventually meets one of two possible fates: either it
  958. runs into a parsing error, in which case it simply vanishes, or it
  959. merges with another parser, because the two of them have reduced the
  960. input to an identical set of symbols.
  961.  
  962.    During the time that there are multiple parsers, semantic actions are
  963. recorded, but not performed.  When a parser disappears, its recorded
  964. semantic actions disappear as well, and are never performed.  When a
  965. reduction makes two parsers identical, causing them to merge, Bison
  966. records both sets of semantic actions.  Whenever the last two parsers
  967. merge, reverting to the single-parser case, Bison resolves all the
  968. outstanding actions either by precedences given to the grammar rules
  969. involved, or by performing both actions, and then calling a designated
  970. user-defined function on the resulting values to produce an arbitrary
  971. merged result.
  972.  
  973.    Let's consider an example, vastly simplified from a C++ grammar.
  974.  
  975.      %{
  976.        #include <stdio.h>
  977.        #define YYSTYPE char const *
  978.        int yylex (void);
  979.        void yyerror (char const *);
  980.      %}
  981.  
  982.      %token TYPENAME ID
  983.  
  984.      %right '='
  985.      %left '+'
  986.  
  987.      %glr-parser
  988.  
  989.      %%
  990.  
  991.      prog :
  992.           | prog stmt   { printf ("\n"); }
  993.           ;
  994.  
  995.      stmt : expr ';'  %dprec 1
  996.           | decl      %dprec 2
  997.           ;
  998.  
  999.      expr : ID               { printf ("%s ", $$); }
  1000.           | TYPENAME '(' expr ')'
  1001.                              { printf ("%s <cast> ", $1); }
  1002.           | expr '+' expr    { printf ("+ "); }
  1003.           | expr '=' expr    { printf ("= "); }
  1004.           ;
  1005.  
  1006.      decl : TYPENAME declarator ';'
  1007.                              { printf ("%s <declare> ", $1); }
  1008.           | TYPENAME declarator '=' expr ';'
  1009.                              { printf ("%s <init-declare> ", $1); }
  1010.           ;
  1011.  
  1012.      declarator : ID         { printf ("\"%s\" ", $1); }
  1013.           | '(' declarator ')'
  1014.           ;
  1015.  
  1016. This models a problematic part of the C++ grammar--the ambiguity between
  1017. certain declarations and statements.  For example,
  1018.  
  1019.      T (x) = y+z;
  1020.  
  1021. parses as either an `expr' or a `stmt' (assuming that `T' is recognized
  1022. as a `TYPENAME' and `x' as an `ID').  Bison detects this as a
  1023. reduce/reduce conflict between the rules `expr : ID' and `declarator :
  1024. ID', which it cannot resolve at the time it encounters `x' in the
  1025. example above.  The two `%dprec' declarations, however, give precedence
  1026. to interpreting the example as a `decl', which implies that `x' is a
  1027. declarator.  The parser therefore prints
  1028.  
  1029.      "x" y z + T <init-declare>
  1030.  
  1031.    Consider a different input string for this parser:
  1032.  
  1033.      T (x) + y;
  1034.  
  1035. Here, there is no ambiguity (this cannot be parsed as a declaration).
  1036. However, at the time the Bison parser encounters `x', it does not have
  1037. enough information to resolve the reduce/reduce conflict (again,
  1038. between `x' as an `expr' or a `declarator').  In this case, no
  1039. precedence declaration is used.  Instead, the parser splits into two,
  1040. one assuming that `x' is an `expr', and the other assuming `x' is a
  1041. `declarator'.  The second of these parsers then vanishes when it sees
  1042. `+', and the parser prints
  1043.  
  1044.      x T <cast> y +
  1045.  
  1046.    Suppose that instead of resolving the ambiguity, you wanted to see
  1047. all the possibilities.  For this purpose, we must "merge" the semantic
  1048. actions of the two possible parsers, rather than choosing one over the
  1049. other.  To do so, you could change the declaration of `stmt' as follows:
  1050.  
  1051.      stmt : expr ';'  %merge <stmtMerge>
  1052.           | decl      %merge <stmtMerge>
  1053.           ;
  1054.  
  1055. and define the `stmtMerge' function as:
  1056.  
  1057.      static YYSTYPE
  1058.      stmtMerge (YYSTYPE x0, YYSTYPE x1)
  1059.      {
  1060.        printf ("<OR> ");
  1061.        return "";
  1062.      }
  1063.  
  1064. with an accompanying forward declaration in the C declarations at the
  1065. beginning of the file:
  1066.  
  1067.      %{
  1068.        #define YYSTYPE char const *
  1069.        static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
  1070.      %}
  1071.  
  1072. With these declarations, the resulting parser will parse the first
  1073. example as both an `expr' and a `decl', and print
  1074.  
  1075.      "x" y z + T <init-declare> x T <cast> y z + = <OR>
  1076.  
  1077.  
  1078.    The GLR parsers require a compiler for ISO C89 or later.  In
  1079. addition, they use the `inline' keyword, which is not C89, but is C99
  1080. and is a common extension in pre-C99 compilers.  It is up to the user
  1081. of these parsers to handle portability issues.  For instance, if using
  1082. Autoconf and the Autoconf macro `AC_C_INLINE', a mere
  1083.  
  1084.      %{
  1085.        #include <config.h>
  1086.      %}
  1087.  
  1088. will suffice.  Otherwise, we suggest
  1089.  
  1090.      %{
  1091.        #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
  1092.         #define inline
  1093.        #endif
  1094.      %}
  1095.  
  1096. 
  1097. File: bison,  Node: Locations Overview,  Next: Bison Parser,  Prev: GLR Parsers,  Up: Concepts
  1098.  
  1099. 1.6 Locations
  1100. =============
  1101.  
  1102. Many applications, like interpreters or compilers, have to produce
  1103. verbose and useful error messages.  To achieve this, one must be able
  1104. to keep track of the "textual position", or "location", of each
  1105. syntactic construct.  Bison provides a mechanism for handling these
  1106. locations.
  1107.  
  1108.    Each token has a semantic value.  In a similar fashion, each token
  1109. has an associated location, but the type of locations is the same for
  1110. all tokens and groupings.  Moreover, the output parser is equipped with
  1111. a default data structure for storing locations (*note Locations::, for
  1112. more details).
  1113.  
  1114.    Like semantic values, locations can be reached in actions using a
  1115. dedicated set of constructs.  In the example above, the location of the
  1116. whole grouping is `@$', while the locations of the subexpressions are
  1117. `@1' and `@3'.
  1118.  
  1119.    When a rule is matched, a default action is used to compute the
  1120. semantic value of its left hand side (*note Actions::).  In the same
  1121. way, another default action is used for locations.  However, the action
  1122. for locations is general enough for most cases, meaning there is
  1123. usually no need to describe for each rule how `@$' should be formed.
  1124. When building a new location for a given grouping, the default behavior
  1125. of the output parser is to take the beginning of the first symbol, and
  1126. the end of the last symbol.
  1127.  
  1128. 
  1129. File: bison,  Node: Bison Parser,  Next: Stages,  Prev: Locations Overview,  Up: Concepts
  1130.  
  1131. 1.7 Bison Output: the Parser File
  1132. =================================
  1133.  
  1134. When you run Bison, you give it a Bison grammar file as input.  The
  1135. output is a C source file that parses the language described by the
  1136. grammar.  This file is called a "Bison parser".  Keep in mind that the
  1137. Bison utility and the Bison parser are two distinct programs: the Bison
  1138. utility is a program whose output is the Bison parser that becomes part
  1139. of your program.
  1140.  
  1141.    The job of the Bison parser is to group tokens into groupings
  1142. according to the grammar rules--for example, to build identifiers and
  1143. operators into expressions.  As it does this, it runs the actions for
  1144. the grammar rules it uses.
  1145.  
  1146.    The tokens come from a function called the "lexical analyzer" that
  1147. you must supply in some fashion (such as by writing it in C).  The Bison
  1148. parser calls the lexical analyzer each time it wants a new token.  It
  1149. doesn't know what is "inside" the tokens (though their semantic values
  1150. may reflect this).  Typically the lexical analyzer makes the tokens by
  1151. parsing characters of text, but Bison does not depend on this.  *Note
  1152. The Lexical Analyzer Function `yylex': Lexical.
  1153.  
  1154.    The Bison parser file is C code which defines a function named
  1155. `yyparse' which implements that grammar.  This function does not make a
  1156. complete C program: you must supply some additional functions.  One is
  1157. the lexical analyzer.  Another is an error-reporting function which the
  1158. parser calls to report an error.  In addition, a complete C program must
  1159. start with a function called `main'; you have to provide this, and
  1160. arrange for it to call `yyparse' or the parser will never run.  *Note
  1161. Parser C-Language Interface: Interface.
  1162.  
  1163.    Aside from the token type names and the symbols in the actions you
  1164. write, all symbols defined in the Bison parser file itself begin with
  1165. `yy' or `YY'.  This includes interface functions such as the lexical
  1166. analyzer function `yylex', the error reporting function `yyerror' and
  1167. the parser function `yyparse' itself.  This also includes numerous
  1168. identifiers used for internal purposes.  Therefore, you should avoid
  1169. using C identifiers starting with `yy' or `YY' in the Bison grammar
  1170. file except for the ones defined in this manual.
  1171.  
  1172.    In some cases the Bison parser file includes system headers, and in
  1173. those cases your code should respect the identifiers reserved by those
  1174. headers.  On some non-GNU hosts, `<alloca.h>', `<stddef.h>', and
  1175. `<stdlib.h>' are included as needed to declare memory allocators and
  1176. related types.  Other system headers may be included if you define
  1177. `YYDEBUG' to a nonzero value (*note Tracing Your Parser: Tracing.).
  1178.  
  1179. 
  1180. File: bison,  Node: Stages,  Next: Grammar Layout,  Prev: Bison Parser,  Up: Concepts
  1181.  
  1182. 1.8 Stages in Using Bison
  1183. =========================
  1184.  
  1185. The actual language-design process using Bison, from grammar
  1186. specification to a working compiler or interpreter, has these parts:
  1187.  
  1188.   1. Formally specify the grammar in a form recognized by Bison (*note
  1189.      Bison Grammar Files: Grammar File.).  For each grammatical rule in
  1190.      the language, describe the action that is to be taken when an
  1191.      instance of that rule is recognized.  The action is described by a
  1192.      sequence of C statements.
  1193.  
  1194.   2. Write a lexical analyzer to process input and pass tokens to the
  1195.      parser.  The lexical analyzer may be written by hand in C (*note
  1196.      The Lexical Analyzer Function `yylex': Lexical.).  It could also
  1197.      be produced using Lex, but the use of Lex is not discussed in this
  1198.      manual.
  1199.  
  1200.   3. Write a controlling function that calls the Bison-produced parser.
  1201.  
  1202.   4. Write error-reporting routines.
  1203.  
  1204.    To turn this source code as written into a runnable program, you
  1205. must follow these steps:
  1206.  
  1207.   1. Run Bison on the grammar to produce the parser.
  1208.  
  1209.   2. Compile the code output by Bison, as well as any other source
  1210.      files.
  1211.  
  1212.   3. Link the object files to produce the finished product.
  1213.  
  1214. 
  1215. File: bison,  Node: Grammar Layout,  Prev: Stages,  Up: Concepts
  1216.  
  1217. 1.9 The Overall Layout of a Bison Grammar
  1218. =========================================
  1219.  
  1220. The input file for the Bison utility is a "Bison grammar file".  The
  1221. general form of a Bison grammar file is as follows:
  1222.  
  1223.      %{
  1224.      PROLOGUE
  1225.      %}
  1226.  
  1227.      BISON DECLARATIONS
  1228.  
  1229.      %%
  1230.      GRAMMAR RULES
  1231.      %%
  1232.      EPILOGUE
  1233.  
  1234. The `%%', `%{' and `%}' are punctuation that appears in every Bison
  1235. grammar file to separate the sections.
  1236.  
  1237.    The prologue may define types and variables used in the actions.
  1238. You can also use preprocessor commands to define macros used there, and
  1239. use `#include' to include header files that do any of these things.
  1240. You need to declare the lexical analyzer `yylex' and the error printer
  1241. `yyerror' here, along with any other global identifiers used by the
  1242. actions in the grammar rules.
  1243.  
  1244.    The Bison declarations declare the names of the terminal and
  1245. nonterminal symbols, and may also describe operator precedence and the
  1246. data types of semantic values of various symbols.
  1247.  
  1248.    The grammar rules define how to construct each nonterminal symbol
  1249. from its parts.
  1250.  
  1251.    The epilogue can contain any code you want to use.  Often the
  1252. definitions of functions declared in the prologue go here.  In a simple
  1253. program, all the rest of the program can go here.
  1254.  
  1255. 
  1256. File: bison,  Node: Examples,  Next: Grammar File,  Prev: Concepts,  Up: Top
  1257.  
  1258. 2 Examples
  1259. **********
  1260.  
  1261. Now we show and explain three sample programs written using Bison: a
  1262. reverse polish notation calculator, an algebraic (infix) notation
  1263. calculator, and a multi-function calculator.  All three have been tested
  1264. under BSD Unix 4.3; each produces a usable, though limited, interactive
  1265. desk-top calculator.
  1266.  
  1267.    These examples are simple, but Bison grammars for real programming
  1268. languages are written the same way.  You can copy these examples out of
  1269. the Info file and into a source file to try them.
  1270.  
  1271. * Menu:
  1272.  
  1273. * RPN Calc::          Reverse polish notation calculator;
  1274.                         a first example with no operator precedence.
  1275. * Infix Calc::        Infix (algebraic) notation calculator.
  1276.                         Operator precedence is introduced.
  1277. * Simple Error Recovery::  Continuing after syntax errors.
  1278. * Location Tracking Calc:: Demonstrating the use of @N and @$.
  1279. * Multi-function Calc::  Calculator with memory and trig functions.
  1280.                            It uses multiple data-types for semantic values.
  1281. * Exercises::         Ideas for improving the multi-function calculator.
  1282.  
  1283. 
  1284. File: bison,  Node: RPN Calc,  Next: Infix Calc,  Up: Examples
  1285.  
  1286. 2.1 Reverse Polish Notation Calculator
  1287. ======================================
  1288.  
  1289. The first example is that of a simple double-precision "reverse polish
  1290. notation" calculator (a calculator using postfix operators).  This
  1291. example provides a good starting point, since operator precedence is
  1292. not an issue.  The second example will illustrate how operator
  1293. precedence is handled.
  1294.  
  1295.    The source code for this calculator is named `rpcalc.y'.  The `.y'
  1296. extension is a convention used for Bison input files.
  1297.  
  1298. * Menu:
  1299.  
  1300. * Decls: Rpcalc Decls.  Prologue (declarations) for rpcalc.
  1301. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  1302. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  1303. * Main: Rpcalc Main.    The controlling function.
  1304. * Error: Rpcalc Error.  The error reporting function.
  1305. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  1306. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  1307.  
  1308. 
  1309. File: bison,  Node: Rpcalc Decls,  Next: Rpcalc Rules,  Up: RPN Calc
  1310.  
  1311. 2.1.1 Declarations for `rpcalc'
  1312. -------------------------------
  1313.  
  1314. Here are the C and Bison declarations for the reverse polish notation
  1315. calculator.  As in C, comments are placed between `/*...*/'.
  1316.  
  1317.      /* Reverse polish notation calculator.  */
  1318.  
  1319.      %{
  1320.        #define YYSTYPE double
  1321.        #include <math.h>
  1322.        int yylex (void);
  1323.        void yyerror (char const *);
  1324.      %}
  1325.  
  1326.      %token NUM
  1327.  
  1328.      %% /* Grammar rules and actions follow.  */
  1329.  
  1330.    The declarations section (*note The prologue: Prologue.) contains two
  1331. preprocessor directives and two forward declarations.
  1332.  
  1333.    The `#define' directive defines the macro `YYSTYPE', thus specifying
  1334. the C data type for semantic values of both tokens and groupings (*note
  1335. Data Types of Semantic Values: Value Type.).  The Bison parser will use
  1336. whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
  1337. the default.  Because we specify `double', each token and each
  1338. expression has an associated value, which is a floating point number.
  1339.  
  1340.    The `#include' directive is used to declare the exponentiation
  1341. function `pow'.
  1342.  
  1343.    The forward declarations for `yylex' and `yyerror' are needed
  1344. because the C language requires that functions be declared before they
  1345. are used.  These functions will be defined in the epilogue, but the
  1346. parser calls them so they must be declared in the prologue.
  1347.  
  1348.    The second section, Bison declarations, provides information to Bison
  1349. about the token types (*note The Bison Declarations Section: Bison
  1350. Declarations.).  Each terminal symbol that is not a single-character
  1351. literal must be declared here.  (Single-character literals normally
  1352. don't need to be declared.)  In this example, all the arithmetic
  1353. operators are designated by single-character literals, so the only
  1354. terminal symbol that needs to be declared is `NUM', the token type for
  1355. numeric constants.
  1356.  
  1357. 
  1358. File: bison,  Node: Rpcalc Rules,  Next: Rpcalc Lexer,  Prev: Rpcalc Decls,  Up: RPN Calc
  1359.  
  1360. 2.1.2 Grammar Rules for `rpcalc'
  1361. --------------------------------
  1362.  
  1363. Here are the grammar rules for the reverse polish notation calculator.
  1364.  
  1365.      input:    /* empty */
  1366.              | input line
  1367.      ;
  1368.  
  1369.      line:     '\n'
  1370.              | exp '\n'      { printf ("\t%.10g\n", $1); }
  1371.      ;
  1372.  
  1373.      exp:      NUM           { $$ = $1;           }
  1374.              | exp exp '+'   { $$ = $1 + $2;      }
  1375.              | exp exp '-'   { $$ = $1 - $2;      }
  1376.              | exp exp '*'   { $$ = $1 * $2;      }
  1377.              | exp exp '/'   { $$ = $1 / $2;      }
  1378.               /* Exponentiation */
  1379.              | exp exp '^'   { $$ = pow ($1, $2); }
  1380.               /* Unary minus    */
  1381.              | exp 'n'       { $$ = -$1;          }
  1382.      ;
  1383.      %%
  1384.  
  1385.    The groupings of the rpcalc "language" defined here are the
  1386. expression (given the name `exp'), the line of input (`line'), and the
  1387. complete input transcript (`input').  Each of these nonterminal symbols
  1388. has several alternate rules, joined by the `|' punctuator which is read
  1389. as "or".  The following sections explain what these rules mean.
  1390.  
  1391.    The semantics of the language is determined by the actions taken
  1392. when a grouping is recognized.  The actions are the C code that appears
  1393. inside braces.  *Note Actions::.
  1394.  
  1395.    You must specify these actions in C, but Bison provides the means for
  1396. passing semantic values between the rules.  In each action, the
  1397. pseudo-variable `$$' stands for the semantic value for the grouping
  1398. that the rule is going to construct.  Assigning a value to `$$' is the
  1399. main job of most actions.  The semantic values of the components of the
  1400. rule are referred to as `$1', `$2', and so on.
  1401.  
  1402. * Menu:
  1403.  
  1404. * Rpcalc Input::
  1405. * Rpcalc Line::
  1406. * Rpcalc Expr::
  1407.  
  1408. 
  1409. File: bison,  Node: Rpcalc Input,  Next: Rpcalc Line,  Up: Rpcalc Rules
  1410.  
  1411. 2.1.2.1 Explanation of `input'
  1412. ..............................
  1413.  
  1414. Consider the definition of `input':
  1415.  
  1416.      input:    /* empty */
  1417.              | input line
  1418.      ;
  1419.  
  1420.    This definition reads as follows: "A complete input is either an
  1421. empty string, or a complete input followed by an input line".  Notice
  1422. that "complete input" is defined in terms of itself.  This definition
  1423. is said to be "left recursive" since `input' appears always as the
  1424. leftmost symbol in the sequence.  *Note Recursive Rules: Recursion.
  1425.  
  1426.    The first alternative is empty because there are no symbols between
  1427. the colon and the first `|'; this means that `input' can match an empty
  1428. string of input (no tokens).  We write the rules this way because it is
  1429. legitimate to type `Ctrl-d' right after you start the calculator.  It's
  1430. conventional to put an empty alternative first and write the comment
  1431. `/* empty */' in it.
  1432.  
  1433.    The second alternate rule (`input line') handles all nontrivial
  1434. input.  It means, "After reading any number of lines, read one more
  1435. line if possible."  The left recursion makes this rule into a loop.
  1436. Since the first alternative matches empty input, the loop can be
  1437. executed zero or more times.
  1438.  
  1439.    The parser function `yyparse' continues to process input until a
  1440. grammatical error is seen or the lexical analyzer says there are no more
  1441. input tokens; we will arrange for the latter to happen at end-of-input.
  1442.  
  1443. 
  1444. File: bison,  Node: Rpcalc Line,  Next: Rpcalc Expr,  Prev: Rpcalc Input,  Up: Rpcalc Rules
  1445.  
  1446. 2.1.2.2 Explanation of `line'
  1447. .............................
  1448.  
  1449. Now consider the definition of `line':
  1450.  
  1451.      line:     '\n'
  1452.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1453.      ;
  1454.  
  1455.    The first alternative is a token which is a newline character; this
  1456. means that rpcalc accepts a blank line (and ignores it, since there is
  1457. no action).  The second alternative is an expression followed by a
  1458. newline.  This is the alternative that makes rpcalc useful.  The
  1459. semantic value of the `exp' grouping is the value of `$1' because the
  1460. `exp' in question is the first symbol in the alternative.  The action
  1461. prints this value, which is the result of the computation the user
  1462. asked for.
  1463.  
  1464.    This action is unusual because it does not assign a value to `$$'.
  1465. As a consequence, the semantic value associated with the `line' is
  1466. uninitialized (its value will be unpredictable).  This would be a bug if
  1467. that value were ever used, but we don't use it: once rpcalc has printed
  1468. the value of the user's input line, that value is no longer needed.
  1469.  
  1470. 
  1471. File: bison,  Node: Rpcalc Expr,  Prev: Rpcalc Line,  Up: Rpcalc Rules
  1472.  
  1473. 2.1.2.3 Explanation of `expr'
  1474. .............................
  1475.  
  1476. The `exp' grouping has several rules, one for each kind of expression.
  1477. The first rule handles the simplest expressions: those that are just
  1478. numbers.  The second handles an addition-expression, which looks like
  1479. two expressions followed by a plus-sign.  The third handles
  1480. subtraction, and so on.
  1481.  
  1482.      exp:      NUM
  1483.              | exp exp '+'     { $$ = $1 + $2;    }
  1484.              | exp exp '-'     { $$ = $1 - $2;    }
  1485.              ...
  1486.              ;
  1487.  
  1488.    We have used `|' to join all the rules for `exp', but we could
  1489. equally well have written them separately:
  1490.  
  1491.      exp:      NUM ;
  1492.      exp:      exp exp '+'     { $$ = $1 + $2;    } ;
  1493.      exp:      exp exp '-'     { $$ = $1 - $2;    } ;
  1494.              ...
  1495.  
  1496.    Most of the rules have actions that compute the value of the
  1497. expression in terms of the value of its parts.  For example, in the
  1498. rule for addition, `$1' refers to the first component `exp' and `$2'
  1499. refers to the second one.  The third component, `'+'', has no meaningful
  1500. associated semantic value, but if it had one you could refer to it as
  1501. `$3'.  When `yyparse' recognizes a sum expression using this rule, the
  1502. sum of the two subexpressions' values is produced as the value of the
  1503. entire expression.  *Note Actions::.
  1504.  
  1505.    You don't have to give an action for every rule.  When a rule has no
  1506. action, Bison by default copies the value of `$1' into `$$'.  This is
  1507. what happens in the first rule (the one that uses `NUM').
  1508.  
  1509.    The formatting shown here is the recommended convention, but Bison
  1510. does not require it.  You can add or change white space as much as you
  1511. wish.  For example, this:
  1512.  
  1513.      exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  1514.  
  1515. means the same thing as this:
  1516.  
  1517.      exp:      NUM
  1518.              | exp exp '+'    { $$ = $1 + $2; }
  1519.              | ...
  1520.  
  1521. The latter, however, is much more readable.
  1522.  
  1523. 
  1524. File: bison,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Rules,  Up: RPN Calc
  1525.  
  1526. 2.1.3 The `rpcalc' Lexical Analyzer
  1527. -----------------------------------
  1528.  
  1529. The lexical analyzer's job is low-level parsing: converting characters
  1530. or sequences of characters into tokens.  The Bison parser gets its
  1531. tokens by calling the lexical analyzer.  *Note The Lexical Analyzer
  1532. Function `yylex': Lexical.
  1533.  
  1534.    Only a simple lexical analyzer is needed for the RPN calculator.
  1535. This lexical analyzer skips blanks and tabs, then reads in numbers as
  1536. `double' and returns them as `NUM' tokens.  Any other character that
  1537. isn't part of a number is a separate token.  Note that the token-code
  1538. for such a single-character token is the character itself.
  1539.  
  1540.    The return value of the lexical analyzer function is a numeric code
  1541. which represents a token type.  The same text used in Bison rules to
  1542. stand for this token type is also a C expression for the numeric code
  1543. for the type.  This works in two ways.  If the token type is a
  1544. character literal, then its numeric code is that of the character; you
  1545. can use the same character literal in the lexical analyzer to express
  1546. the number.  If the token type is an identifier, that identifier is
  1547. defined by Bison as a C macro whose definition is the appropriate
  1548. number.  In this example, therefore, `NUM' becomes a macro for `yylex'
  1549. to use.
  1550.  
  1551.    The semantic value of the token (if it has one) is stored into the
  1552. global variable `yylval', which is where the Bison parser will look for
  1553. it.  (The C data type of `yylval' is `YYSTYPE', which was defined at
  1554. the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
  1555. Decls.)
  1556.  
  1557.    A token type code of zero is returned if the end-of-input is
  1558. encountered.  (Bison recognizes any nonpositive value as indicating
  1559. end-of-input.)
  1560.  
  1561.    Here is the code for the lexical analyzer:
  1562.  
  1563.      /* The lexical analyzer returns a double floating point
  1564.         number on the stack and the token NUM, or the numeric code
  1565.         of the character read if not a number.  It skips all blanks
  1566.         and tabs, and returns 0 for end-of-input.  */
  1567.  
  1568.      #include <ctype.h>
  1569.  
  1570.      int
  1571.      yylex (void)
  1572.      {
  1573.        int c;
  1574.  
  1575.        /* Skip white space.  */
  1576.        while ((c = getchar ()) == ' ' || c == '\t')
  1577.          ;
  1578.        /* Process numbers.  */
  1579.        if (c == '.' || isdigit (c))
  1580.          {
  1581.            ungetc (c, stdin);
  1582.            scanf ("%lf", &yylval);
  1583.            return NUM;
  1584.          }
  1585.        /* Return end-of-input.  */
  1586.        if (c == EOF)
  1587.          return 0;
  1588.        /* Return a single char.  */
  1589.        return c;
  1590.      }
  1591.  
  1592. 
  1593. File: bison,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  1594.  
  1595. 2.1.4 The Controlling Function
  1596. ------------------------------
  1597.  
  1598. In keeping with the spirit of this example, the controlling function is
  1599. kept to the bare minimum.  The only requirement is that it call
  1600. `yyparse' to start the process of parsing.
  1601.  
  1602.      int
  1603.      main (void)
  1604.      {
  1605.        return yyparse ();
  1606.      }
  1607.  
  1608. 
  1609. File: bison,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  1610.  
  1611. 2.1.5 The Error Reporting Routine
  1612. ---------------------------------
  1613.  
  1614. When `yyparse' detects a syntax error, it calls the error reporting
  1615. function `yyerror' to print an error message (usually but not always
  1616. `"syntax error"').  It is up to the programmer to supply `yyerror'
  1617. (*note Parser C-Language Interface: Interface.), so here is the
  1618. definition we will use:
  1619.  
  1620.      #include <stdio.h>
  1621.  
  1622.      /* Called by yyparse on error.  */
  1623.      void
  1624.      yyerror (char const *s)
  1625.      {
  1626.        printf ("%s\n", s);
  1627.      }
  1628.  
  1629.    After `yyerror' returns, the Bison parser may recover from the error
  1630. and continue parsing if the grammar contains a suitable error rule
  1631. (*note Error Recovery::).  Otherwise, `yyparse' returns nonzero.  We
  1632. have not written any error rules in this example, so any invalid input
  1633. will cause the calculator program to exit.  This is not clean behavior
  1634. for a real calculator, but it is adequate for the first example.
  1635.  
  1636. 
  1637. File: bison,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  1638.  
  1639. 2.1.6 Running Bison to Make the Parser
  1640. --------------------------------------
  1641.  
  1642. Before running Bison to produce a parser, we need to decide how to
  1643. arrange all the source code in one or more source files.  For such a
  1644. simple example, the easiest thing is to put everything in one file.  The
  1645. definitions of `yylex', `yyerror' and `main' go at the end, in the
  1646. epilogue of the file (*note The Overall Layout of a Bison Grammar:
  1647. Grammar Layout.).
  1648.  
  1649.    For a large project, you would probably have several source files,
  1650. and use `make' to arrange to recompile them.
  1651.  
  1652.    With all the source in a single file, you use the following command
  1653. to convert it into a parser file:
  1654.  
  1655.      bison FILE_NAME.y
  1656.  
  1657. In this example the file was called `rpcalc.y' (for "Reverse Polish
  1658. CALCulator").  Bison produces a file named `FILE_NAME.tab.c', removing
  1659. the `.y' from the original file name.  The file output by Bison
  1660. contains the source code for `yyparse'.  The additional functions in
  1661. the input file (`yylex', `yyerror' and `main') are copied verbatim to
  1662. the output.
  1663.  
  1664. 
  1665. File: bison,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  1666.  
  1667. 2.1.7 Compiling the Parser File
  1668. -------------------------------
  1669.  
  1670. Here is how to compile and run the parser file:
  1671.  
  1672.      # List files in current directory.
  1673.      $ ls
  1674.      rpcalc.tab.c  rpcalc.y
  1675.  
  1676.      # Compile the Bison parser.
  1677.      # `-lm' tells compiler to search math library for `pow'.
  1678.      $ cc -lm -o rpcalc rpcalc.tab.c
  1679.  
  1680.      # List files again.
  1681.      $ ls
  1682.      rpcalc  rpcalc.tab.c  rpcalc.y
  1683.  
  1684.    The file `rpcalc' now contains the executable code.  Here is an
  1685. example session using `rpcalc'.
  1686.  
  1687.      $ rpcalc
  1688.      4 9 +
  1689.      13
  1690.      3 7 + 3 4 5 *+-
  1691.      -13
  1692.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  1693.      13
  1694.      5 6 / 4 n +
  1695.      -3.166666667
  1696.      3 4 ^                            Exponentiation
  1697.      81
  1698.      ^D                               End-of-file indicator
  1699.      $
  1700.  
  1701. 
  1702. File: bison,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Examples
  1703.  
  1704. 2.2 Infix Notation Calculator: `calc'
  1705. =====================================
  1706.  
  1707. We now modify rpcalc to handle infix operators instead of postfix.
  1708. Infix notation involves the concept of operator precedence and the need
  1709. for parentheses nested to arbitrary depth.  Here is the Bison code for
  1710. `calc.y', an infix desk-top calculator.
  1711.  
  1712.      /* Infix notation calculator.  */
  1713.  
  1714.      %{
  1715.        #define YYSTYPE double
  1716.        #include <math.h>
  1717.        #include <stdio.h>
  1718.        int yylex (void);
  1719.        void yyerror (char const *);
  1720.      %}
  1721.  
  1722.      /* Bison declarations.  */
  1723.      %token NUM
  1724.      %left '-' '+'
  1725.      %left '*' '/'
  1726.      %left NEG     /* negation--unary minus */
  1727.      %right '^'    /* exponentiation */
  1728.  
  1729.      %% /* The grammar follows.  */
  1730.      input:    /* empty */
  1731.              | input line
  1732.      ;
  1733.  
  1734.      line:     '\n'
  1735.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1736.      ;
  1737.  
  1738.      exp:      NUM                { $$ = $1;         }
  1739.              | exp '+' exp        { $$ = $1 + $3;    }
  1740.              | exp '-' exp        { $$ = $1 - $3;    }
  1741.              | exp '*' exp        { $$ = $1 * $3;    }
  1742.              | exp '/' exp        { $$ = $1 / $3;    }
  1743.              | '-' exp  %prec NEG { $$ = -$2;        }
  1744.              | exp '^' exp        { $$ = pow ($1, $3); }
  1745.              | '(' exp ')'        { $$ = $2;         }
  1746.      ;
  1747.      %%
  1748.  
  1749. The functions `yylex', `yyerror' and `main' can be the same as before.
  1750.  
  1751.    There are two important new features shown in this code.
  1752.  
  1753.    In the second section (Bison declarations), `%left' declares token
  1754. types and says they are left-associative operators.  The declarations
  1755. `%left' and `%right' (right associativity) take the place of `%token'
  1756. which is used to declare a token type name without associativity.
  1757. (These tokens are single-character literals, which ordinarily don't
  1758. need to be declared.  We declare them here to specify the
  1759. associativity.)
  1760.  
  1761.    Operator precedence is determined by the line ordering of the
  1762. declarations; the higher the line number of the declaration (lower on
  1763. the page or screen), the higher the precedence.  Hence, exponentiation
  1764. has the highest precedence, unary minus (`NEG') is next, followed by
  1765. `*' and `/', and so on.  *Note Operator Precedence: Precedence.
  1766.  
  1767.    The other important new feature is the `%prec' in the grammar
  1768. section for the unary minus operator.  The `%prec' simply instructs
  1769. Bison that the rule `| '-' exp' has the same precedence as `NEG'--in
  1770. this case the next-to-highest.  *Note Context-Dependent Precedence:
  1771. Contextual Precedence.
  1772.  
  1773.    Here is a sample run of `calc.y':
  1774.  
  1775.      $ calc
  1776.      4 + 4.5 - (34/(8*3+-3))
  1777.      6.880952381
  1778.      -56 + 2
  1779.      -54
  1780.      3 ^ 2
  1781.      9
  1782.  
  1783. 
  1784. File: bison,  Node: Simple Error Recovery,  Next: Location Tracking Calc,  Prev: Infix Calc,  Up: Examples
  1785.  
  1786. 2.3 Simple Error Recovery
  1787. =========================
  1788.  
  1789. Up to this point, this manual has not addressed the issue of "error
  1790. recovery"--how to continue parsing after the parser detects a syntax
  1791. error.  All we have handled is error reporting with `yyerror'.  Recall
  1792. that by default `yyparse' returns after calling `yyerror'.  This means
  1793. that an erroneous input line causes the calculator program to exit.
  1794. Now we show how to rectify this deficiency.
  1795.  
  1796.    The Bison language itself includes the reserved word `error', which
  1797. may be included in the grammar rules.  In the example below it has been
  1798. added to one of the alternatives for `line':
  1799.  
  1800.      line:     '\n'
  1801.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  1802.              | error '\n' { yyerrok;                  }
  1803.      ;
  1804.  
  1805.    This addition to the grammar allows for simple error recovery in the
  1806. event of a syntax error.  If an expression that cannot be evaluated is
  1807. read, the error will be recognized by the third rule for `line', and
  1808. parsing will continue.  (The `yyerror' function is still called upon to
  1809. print its message as well.)  The action executes the statement
  1810. `yyerrok', a macro defined automatically by Bison; its meaning is that
  1811. error recovery is complete (*note Error Recovery::).  Note the
  1812. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  1813.  
  1814.    This form of error recovery deals with syntax errors.  There are
  1815. other kinds of errors; for example, division by zero, which raises an
  1816. exception signal that is normally fatal.  A real calculator program
  1817. must handle this signal and use `longjmp' to return to `main' and
  1818. resume parsing input lines; it would also have to discard the rest of
  1819. the current line of input.  We won't discuss this issue further because
  1820. it is not specific to Bison programs.
  1821.  
  1822. 
  1823. File: bison,  Node: Location Tracking Calc,  Next: Multi-function Calc,  Prev: Simple Error Recovery,  Up: Examples
  1824.  
  1825. 2.4 Location Tracking Calculator: `ltcalc'
  1826. ==========================================
  1827.  
  1828. This example extends the infix notation calculator with location
  1829. tracking.  This feature will be used to improve the error messages.  For
  1830. the sake of clarity, this example is a simple integer calculator, since
  1831. most of the work needed to use locations will be done in the lexical
  1832. analyzer.
  1833.  
  1834. * Menu:
  1835.  
  1836. * Decls: Ltcalc Decls.  Bison and C declarations for ltcalc.
  1837. * Rules: Ltcalc Rules.  Grammar rules for ltcalc, with explanations.
  1838. * Lexer: Ltcalc Lexer.  The lexical analyzer.
  1839.  
  1840. 
  1841. File: bison,  Node: Ltcalc Decls,  Next: Ltcalc Rules,  Up: Location Tracking Calc
  1842.  
  1843. 2.4.1 Declarations for `ltcalc'
  1844. -------------------------------
  1845.  
  1846. The C and Bison declarations for the location tracking calculator are
  1847. the same as the declarations for the infix notation calculator.
  1848.  
  1849.      /* Location tracking calculator.  */
  1850.  
  1851.      %{
  1852.        #define YYSTYPE int
  1853.        #include <math.h>
  1854.        int yylex (void);
  1855.        void yyerror (char const *);
  1856.      %}
  1857.  
  1858.      /* Bison declarations.  */
  1859.      %token NUM
  1860.  
  1861.      %left '-' '+'
  1862.      %left '*' '/'
  1863.      %left NEG
  1864.      %right '^'
  1865.  
  1866.      %% /* The grammar follows.  */
  1867.  
  1868. Note there are no declarations specific to locations.  Defining a data
  1869. type for storing locations is not needed: we will use the type provided
  1870. by default (*note Data Types of Locations: Location Type.), which is a
  1871. four member structure with the following integer fields: `first_line',
  1872. `first_column', `last_line' and `last_column'.
  1873.  
  1874. 
  1875. File: bison,  Node: Ltcalc Rules,  Next: Ltcalc Lexer,  Prev: Ltcalc Decls,  Up: Location Tracking Calc
  1876.  
  1877. 2.4.2 Grammar Rules for `ltcalc'
  1878. --------------------------------
  1879.  
  1880. Whether handling locations or not has no effect on the syntax of your
  1881. language.  Therefore, grammar rules for this example will be very close
  1882. to those of the previous example: we will only modify them to benefit
  1883. from the new information.
  1884.  
  1885.    Here, we will use locations to report divisions by zero, and locate
  1886. the wrong expressions or subexpressions.
  1887.  
  1888.      input   : /* empty */
  1889.              | input line
  1890.      ;
  1891.  
  1892.      line    : '\n'
  1893.              | exp '\n' { printf ("%d\n", $1); }
  1894.      ;
  1895.  
  1896.      exp     : NUM           { $$ = $1; }
  1897.              | exp '+' exp   { $$ = $1 + $3; }
  1898.              | exp '-' exp   { $$ = $1 - $3; }
  1899.              | exp '*' exp   { $$ = $1 * $3; }
  1900.              | exp '/' exp
  1901.                  {
  1902.                    if ($3)
  1903.                      $$ = $1 / $3;
  1904.                    else
  1905.                      {
  1906.                        $$ = 1;
  1907.                        fprintf (stderr, "%d.%d-%d.%d: division by zero",
  1908.                                 @3.first_line, @3.first_column,
  1909.                                 @3.last_line, @3.last_column);
  1910.                      }
  1911.                  }
  1912.              | '-' exp %preg NEG     { $$ = -$2; }
  1913.              | exp '^' exp           { $$ = pow ($1, $3); }
  1914.              | '(' exp ')'           { $$ = $2; }
  1915.  
  1916.    This code shows how to reach locations inside of semantic actions, by
  1917. using the pseudo-variables `@N' for rule components, and the
  1918. pseudo-variable `@$' for groupings.
  1919.  
  1920.    We don't need to assign a value to `@$': the output parser does it
  1921. automatically.  By default, before executing the C code of each action,
  1922. `@$' is set to range from the beginning of `@1' to the end of `@N', for
  1923. a rule with N components.  This behavior can be redefined (*note
  1924. Default Action for Locations: Location Default Action.), and for very
  1925. specific rules, `@$' can be computed by hand.
  1926.  
  1927. 
  1928. File: bison,  Node: Ltcalc Lexer,  Prev: Ltcalc Rules,  Up: Location Tracking Calc
  1929.  
  1930. 2.4.3 The `ltcalc' Lexical Analyzer.
  1931. ------------------------------------
  1932.  
  1933. Until now, we relied on Bison's defaults to enable location tracking.
  1934. The next step is to rewrite the lexical analyzer, and make it able to
  1935. feed the parser with the token locations, as it already does for
  1936. semantic values.
  1937.  
  1938.    To this end, we must take into account every single character of the
  1939. input text, to avoid the computed locations of being fuzzy or wrong:
  1940.  
  1941.      int
  1942.      yylex (void)
  1943.      {
  1944.        int c;
  1945.  
  1946.        /* Skip white space.  */
  1947.        while ((c = getchar ()) == ' ' || c == '\t')
  1948.          ++yylloc.last_column;
  1949.  
  1950.        /* Step.  */
  1951.        yylloc.first_line = yylloc.last_line;
  1952.        yylloc.first_column = yylloc.last_column;
  1953.  
  1954.        /* Process numbers.  */
  1955.        if (isdigit (c))
  1956.          {
  1957.            yylval = c - '0';
  1958.            ++yylloc.last_column;
  1959.            while (isdigit (c = getchar ()))
  1960.              {
  1961.                ++yylloc.last_column;
  1962.                yylval = yylval * 10 + c - '0';
  1963.              }
  1964.            ungetc (c, stdin);
  1965.            return NUM;
  1966.          }
  1967.  
  1968.        /* Return end-of-input.  */
  1969.        if (c == EOF)
  1970.          return 0;
  1971.  
  1972.        /* Return a single char, and update location.  */
  1973.        if (c == '\n')
  1974.          {
  1975.            ++yylloc.last_line;
  1976.            yylloc.last_column = 0;
  1977.          }
  1978.        else
  1979.          ++yylloc.last_column;
  1980.        return c;
  1981.      }
  1982.  
  1983.    Basically, the lexical analyzer performs the same processing as
  1984. before: it skips blanks and tabs, and reads numbers or single-character
  1985. tokens.  In addition, it updates `yylloc', the global variable (of type
  1986. `YYLTYPE') containing the token's location.
  1987.  
  1988.    Now, each time this function returns a token, the parser has its
  1989. number as well as its semantic value, and its location in the text.
  1990. The last needed change is to initialize `yylloc', for example in the
  1991. controlling function:
  1992.  
  1993.      int
  1994.      main (void)
  1995.      {
  1996.        yylloc.first_line = yylloc.last_line = 1;
  1997.        yylloc.first_column = yylloc.last_column = 0;
  1998.        return yyparse ();
  1999.      }
  2000.  
  2001.    Remember that computing locations is not a matter of syntax.  Every
  2002. character must be associated to a location update, whether it is in
  2003. valid input, in comments, in literal strings, and so on.
  2004.  
  2005. 
  2006. File: bison,  Node: Multi-function Calc,  Next: Exercises,  Prev: Location Tracking Calc,  Up: Examples
  2007.  
  2008. 2.5 Multi-Function Calculator: `mfcalc'
  2009. =======================================
  2010.  
  2011. Now that the basics of Bison have been discussed, it is time to move on
  2012. to a more advanced problem.  The above calculators provided only five
  2013. functions, `+', `-', `*', `/' and `^'.  It would be nice to have a
  2014. calculator that provides other mathematical functions such as `sin',
  2015. `cos', etc.
  2016.  
  2017.    It is easy to add new operators to the infix calculator as long as
  2018. they are only single-character literals.  The lexical analyzer `yylex'
  2019. passes back all nonnumber characters as tokens, so new grammar rules
  2020. suffice for adding a new operator.  But we want something more
  2021. flexible: built-in functions whose syntax has this form:
  2022.  
  2023.      FUNCTION_NAME (ARGUMENT)
  2024.  
  2025. At the same time, we will add memory to the calculator, by allowing you
  2026. to create named variables, store values in them, and use them later.
  2027. Here is a sample session with the multi-function calculator:
  2028.  
  2029.      $ mfcalc
  2030.      pi = 3.141592653589
  2031.      3.1415926536
  2032.      sin(pi)
  2033.      0.0000000000
  2034.      alpha = beta1 = 2.3
  2035.      2.3000000000
  2036.      alpha
  2037.      2.3000000000
  2038.      ln(alpha)
  2039.      0.8329091229
  2040.      exp(ln(beta1))
  2041.      2.3000000000
  2042.      $
  2043.  
  2044.    Note that multiple assignment and nested function calls are
  2045. permitted.
  2046.  
  2047. * Menu:
  2048.  
  2049. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  2050. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  2051. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  2052.  
  2053. 
  2054. File: bison,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Up: Multi-function Calc
  2055.  
  2056. 2.5.1 Declarations for `mfcalc'
  2057. -------------------------------
  2058.  
  2059. Here are the C and Bison declarations for the multi-function calculator.
  2060.  
  2061.      %{
  2062.        #include <math.h>  /* For math functions, cos(), sin(), etc.  */
  2063.        #include "calc.h"  /* Contains definition of `symrec'.  */
  2064.        int yylex (void);
  2065.        void yyerror (char const *);
  2066.      %}
  2067.      %union {
  2068.        double    val;   /* For returning numbers.  */
  2069.        symrec  *tptr;   /* For returning symbol-table pointers.  */
  2070.      }
  2071.      %token <val>  NUM        /* Simple double precision number.  */
  2072.      %token <tptr> VAR FNCT   /* Variable and Function.  */
  2073.      %type  <val>  exp
  2074.  
  2075.      %right '='
  2076.      %left '-' '+'
  2077.      %left '*' '/'
  2078.      %left NEG     /* negation--unary minus */
  2079.      %right '^'    /* exponentiation */
  2080.      %% /* The grammar follows.  */
  2081.  
  2082.    The above grammar introduces only two new features of the Bison
  2083. language.  These features allow semantic values to have various data
  2084. types (*note More Than One Value Type: Multiple Types.).
  2085.  
  2086.    The `%union' declaration specifies the entire list of possible types;
  2087. this is instead of defining `YYSTYPE'.  The allowable types are now
  2088. double-floats (for `exp' and `NUM') and pointers to entries in the
  2089. symbol table.  *Note The Collection of Value Types: Union Decl.
  2090.  
  2091.    Since values can now have various types, it is necessary to
  2092. associate a type with each grammar symbol whose semantic value is used.
  2093. These symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations
  2094. are augmented with information about their data type (placed between
  2095. angle brackets).
  2096.  
  2097.    The Bison construct `%type' is used for declaring nonterminal
  2098. symbols, just as `%token' is used for declaring token types.  We have
  2099. not used `%type' before because nonterminal symbols are normally
  2100. declared implicitly by the rules that define them.  But `exp' must be
  2101. declared explicitly so we can specify its value type.  *Note
  2102. Nonterminal Symbols: Type Decl.
  2103.  
  2104. 
  2105. File: bison,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  2106.  
  2107. 2.5.2 Grammar Rules for `mfcalc'
  2108. --------------------------------
  2109.  
  2110. Here are the grammar rules for the multi-function calculator.  Most of
  2111. them are copied directly from `calc'; three rules, those which mention
  2112. `VAR' or `FNCT', are new.
  2113.  
  2114.      input:   /* empty */
  2115.              | input line
  2116.      ;
  2117.  
  2118.      line:
  2119.                '\n'
  2120.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  2121.              | error '\n' { yyerrok;                  }
  2122.      ;
  2123.  
  2124.      exp:      NUM                { $$ = $1;                         }
  2125.              | VAR                { $$ = $1->value.var;              }
  2126.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  2127.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  2128.              | exp '+' exp        { $$ = $1 + $3;                    }
  2129.              | exp '-' exp        { $$ = $1 - $3;                    }
  2130.              | exp '*' exp        { $$ = $1 * $3;                    }
  2131.              | exp '/' exp        { $$ = $1 / $3;                    }
  2132.              | '-' exp  %prec NEG { $$ = -$2;                        }
  2133.              | exp '^' exp        { $$ = pow ($1, $3);               }
  2134.              | '(' exp ')'        { $$ = $2;                         }
  2135.      ;
  2136.      /* End of grammar.  */
  2137.      %%
  2138.  
  2139. 
  2140. File: bison,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  2141.  
  2142. 2.5.3 The `mfcalc' Symbol Table
  2143. -------------------------------
  2144.  
  2145. The multi-function calculator requires a symbol table to keep track of
  2146. the names and meanings of variables and functions.  This doesn't affect
  2147. the grammar rules (except for the actions) or the Bison declarations,
  2148. but it requires some additional C functions for support.
  2149.  
  2150.    The symbol table itself consists of a linked list of records.  Its
  2151. definition, which is kept in the header `calc.h', is as follows.  It
  2152. provides for either functions or variables to be placed in the table.
  2153.  
  2154.      /* Function type.  */
  2155.      typedef double (*func_t) (double);
  2156.  
  2157.      /* Data type for links in the chain of symbols.  */
  2158.      struct symrec
  2159.      {
  2160.        char *name;  /* name of symbol */
  2161.        int type;    /* type of symbol: either VAR or FNCT */
  2162.        union
  2163.        {
  2164.          double var;      /* value of a VAR */
  2165.          func_t fnctptr;  /* value of a FNCT */
  2166.        } value;
  2167.        struct symrec *next;  /* link field */
  2168.      };
  2169.  
  2170.      typedef struct symrec symrec;
  2171.  
  2172.      /* The symbol table: a chain of `struct symrec'.  */
  2173.      extern symrec *sym_table;
  2174.  
  2175.      symrec *putsym (char const *, func_t);
  2176.      symrec *getsym (char const *);
  2177.  
  2178.    The new version of `main' includes a call to `init_table', a
  2179. function that initializes the symbol table.  Here it is, and
  2180. `init_table' as well:
  2181.  
  2182.      #include <stdio.h>
  2183.  
  2184.      /* Called by yyparse on error.  */
  2185.      void
  2186.      yyerror (char const *s)
  2187.      {
  2188.        printf ("%s\n", s);
  2189.      }
  2190.  
  2191.      struct init
  2192.      {
  2193.        char const *fname;
  2194.        double (*fnct) (double);
  2195.      };
  2196.  
  2197.      struct init const arith_fncts[] =
  2198.      {
  2199.        "sin",  sin,
  2200.        "cos",  cos,
  2201.        "atan", atan,
  2202.        "ln",   log,
  2203.        "exp",  exp,
  2204.        "sqrt", sqrt,
  2205.        0, 0
  2206.      };
  2207.  
  2208.      /* The symbol table: a chain of `struct symrec'.  */
  2209.      symrec *sym_table;
  2210.  
  2211.      /* Put arithmetic functions in table.  */
  2212.      void
  2213.      init_table (void)
  2214.      {
  2215.        int i;
  2216.        symrec *ptr;
  2217.        for (i = 0; arith_fncts[i].fname != 0; i++)
  2218.          {
  2219.            ptr = putsym (arith_fncts[i].fname, FNCT);
  2220.            ptr->value.fnctptr = arith_fncts[i].fnct;
  2221.          }
  2222.      }
  2223.  
  2224.      int
  2225.      main (void)
  2226.      {
  2227.        init_table ();
  2228.        return yyparse ();
  2229.      }
  2230.  
  2231.    By simply editing the initialization list and adding the necessary
  2232. include files, you can add additional functions to the calculator.
  2233.  
  2234.    Two important functions allow look-up and installation of symbols in
  2235. the symbol table.  The function `putsym' is passed a name and the type
  2236. (`VAR' or `FNCT') of the object to be installed.  The object is linked
  2237. to the front of the list, and a pointer to the object is returned.  The
  2238. function `getsym' is passed the name of the symbol to look up.  If
  2239. found, a pointer to that symbol is returned; otherwise zero is returned.
  2240.  
  2241.      symrec *
  2242.      putsym (char const *sym_name, int sym_type)
  2243.      {
  2244.        symrec *ptr;
  2245.        ptr = (symrec *) malloc (sizeof (symrec));
  2246.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  2247.        strcpy (ptr->name,sym_name);
  2248.        ptr->type = sym_type;
  2249.        ptr->value.var = 0; /* Set value to 0 even if fctn.  */
  2250.        ptr->next = (struct symrec *)sym_table;
  2251.        sym_table = ptr;
  2252.        return ptr;
  2253.      }
  2254.  
  2255.      symrec *
  2256.      getsym (char const *sym_name)
  2257.      {
  2258.        symrec *ptr;
  2259.        for (ptr = sym_table; ptr != (symrec *) 0;
  2260.             ptr = (symrec *)ptr->next)
  2261.          if (strcmp (ptr->name,sym_name) == 0)
  2262.            return ptr;
  2263.        return 0;
  2264.      }
  2265.  
  2266.    The function `yylex' must now recognize variables, numeric values,
  2267. and the single-character arithmetic operators.  Strings of alphanumeric
  2268. characters with a leading non-digit are recognized as either variables
  2269. or functions depending on what the symbol table says about them.
  2270.  
  2271.    The string is passed to `getsym' for look up in the symbol table.  If
  2272. the name appears in the table, a pointer to its location and its type
  2273. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  2274. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  2275. pointer and its type (which must be `VAR') is returned to `yyparse'.
  2276.  
  2277.    No change is needed in the handling of numeric values and arithmetic
  2278. operators in `yylex'.
  2279.  
  2280.      #include <ctype.h>
  2281.  
  2282.      int
  2283.      yylex (void)
  2284.      {
  2285.        int c;
  2286.  
  2287.        /* Ignore white space, get first nonwhite character.  */
  2288.        while ((c = getchar ()) == ' ' || c == '\t');
  2289.  
  2290.        if (c == EOF)
  2291.          return 0;
  2292.  
  2293.        /* Char starts a number => parse the number.         */
  2294.        if (c == '.' || isdigit (c))
  2295.          {
  2296.            ungetc (c, stdin);
  2297.            scanf ("%lf", &yylval.val);
  2298.            return NUM;
  2299.          }
  2300.  
  2301.        /* Char starts an identifier => read the name.       */
  2302.        if (isalpha (c))
  2303.          {
  2304.            symrec *s;
  2305.            static char *symbuf = 0;
  2306.            static int length = 0;
  2307.            int i;
  2308.  
  2309.            /* Initially make the buffer long enough
  2310.               for a 40-character symbol name.  */
  2311.            if (length == 0)
  2312.              length = 40, symbuf = (char *)malloc (length + 1);
  2313.  
  2314.            i = 0;
  2315.            do
  2316.              {
  2317.                /* If buffer is full, make it bigger.        */
  2318.                if (i == length)
  2319.                  {
  2320.                    length *= 2;
  2321.                    symbuf = (char *) realloc (symbuf, length + 1);
  2322.                  }
  2323.                /* Add this character to the buffer.         */
  2324.                symbuf[i++] = c;
  2325.                /* Get another character.                    */
  2326.                c = getchar ();
  2327.              }
  2328.            while (isalnum (c));
  2329.  
  2330.            ungetc (c, stdin);
  2331.            symbuf[i] = '\0';
  2332.  
  2333.            s = getsym (symbuf);
  2334.            if (s == 0)
  2335.              s = putsym (symbuf, VAR);
  2336.            yylval.tptr = s;
  2337.            return s->type;
  2338.          }
  2339.  
  2340.        /* Any other character is a token by itself.        */
  2341.        return c;
  2342.      }
  2343.  
  2344.    This program is both powerful and flexible.  You may easily add new
  2345. functions, and it is a simple job to modify this code to install
  2346. predefined variables such as `pi' or `e' as well.
  2347.  
  2348. 
  2349. File: bison,  Node: Exercises,  Prev: Multi-function Calc,  Up: Examples
  2350.  
  2351. 2.6 Exercises
  2352. =============
  2353.  
  2354.   1. Add some new functions from `math.h' to the initialization list.
  2355.  
  2356.   2. Add another array that contains constants and their values.  Then
  2357.      modify `init_table' to add these constants to the symbol table.
  2358.      It will be easiest to give the constants type `VAR'.
  2359.  
  2360.   3. Make the program report an error if the user refers to an
  2361.      uninitialized variable in any way except to store a value in it.
  2362.  
  2363. 
  2364. File: bison,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  2365.  
  2366. 3 Bison Grammar Files
  2367. *********************
  2368.  
  2369. Bison takes as input a context-free grammar specification and produces a
  2370. C-language function that recognizes correct instances of the grammar.
  2371.  
  2372.    The Bison grammar input file conventionally has a name ending in
  2373. `.y'.  *Note Invoking Bison: Invocation.
  2374.  
  2375. * Menu:
  2376.  
  2377. * Grammar Outline::   Overall layout of the grammar file.
  2378. * Symbols::           Terminal and nonterminal symbols.
  2379. * Rules::             How to write grammar rules.
  2380. * Recursion::         Writing recursive rules.
  2381. * Semantics::         Semantic values and actions.
  2382. * Locations::         Locations and actions.
  2383. * Declarations::      All kinds of Bison declarations are described here.
  2384. * Multiple Parsers::  Putting more than one Bison parser in one program.
  2385.  
  2386. 
  2387. File: bison,  Node: Grammar Outline,  Next: Symbols,  Up: Grammar File
  2388.  
  2389. 3.1 Outline of a Bison Grammar
  2390. ==============================
  2391.  
  2392. A Bison grammar file has four main sections, shown here with the
  2393. appropriate delimiters:
  2394.  
  2395.      %{
  2396.        PROLOGUE
  2397.      %}
  2398.  
  2399.      BISON DECLARATIONS
  2400.  
  2401.      %%
  2402.      GRAMMAR RULES
  2403.      %%
  2404.  
  2405.      EPILOGUE
  2406.  
  2407.    Comments enclosed in `/* ... */' may appear in any of the sections.
  2408. As a GNU extension, `//' introduces a comment that continues until end
  2409. of line.
  2410.  
  2411. * Menu:
  2412.  
  2413. * Prologue::          Syntax and usage of the prologue.
  2414. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  2415. * Grammar Rules::     Syntax and usage of the grammar rules section.
  2416. * Epilogue::          Syntax and usage of the epilogue.
  2417.  
  2418. 
  2419. File: bison,  Node: Prologue,  Next: Bison Declarations,  Up: Grammar Outline
  2420.  
  2421. 3.1.1 The prologue
  2422. ------------------
  2423.  
  2424. The PROLOGUE section contains macro definitions and declarations of
  2425. functions and variables that are used in the actions in the grammar
  2426. rules.  These are copied to the beginning of the parser file so that
  2427. they precede the definition of `yyparse'.  You can use `#include' to
  2428. get the declarations from a header file.  If you don't need any C
  2429. declarations, you may omit the `%{' and `%}' delimiters that bracket
  2430. this section.
  2431.  
  2432.    You may have more than one PROLOGUE section, intermixed with the
  2433. BISON DECLARATIONS.  This allows you to have C and Bison declarations
  2434. that refer to each other.  For example, the `%union' declaration may
  2435. use types defined in a header file, and you may wish to prototype
  2436. functions that take arguments of type `YYSTYPE'.  This can be done with
  2437. two PROLOGUE blocks, one before and one after the `%union' declaration.
  2438.  
  2439.      %{
  2440.        #include <stdio.h>
  2441.        #include "ptypes.h"
  2442.      %}
  2443.  
  2444.      %union {
  2445.        long n;
  2446.        tree t;  /* `tree' is defined in `ptypes.h'. */
  2447.      }
  2448.  
  2449.      %{
  2450.        static void print_token_value (FILE *, int, YYSTYPE);
  2451.        #define YYPRINT(F, N, L) print_token_value (F, N, L)
  2452.      %}
  2453.  
  2454.      ...
  2455.  
  2456. 
  2457. File: bison,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: Prologue,  Up: Grammar Outline
  2458.  
  2459. 3.1.2 The Bison Declarations Section
  2460. ------------------------------------
  2461.  
  2462. The BISON DECLARATIONS section contains declarations that define
  2463. terminal and nonterminal symbols, specify precedence, and so on.  In
  2464. some simple grammars you may not need any declarations.  *Note Bison
  2465. Declarations: Declarations.
  2466.  
  2467. 
  2468. File: bison,  Node: Grammar Rules,  Next: Epilogue,  Prev: Bison Declarations,  Up: Grammar Outline
  2469.  
  2470. 3.1.3 The Grammar Rules Section
  2471. -------------------------------
  2472.  
  2473. The "grammar rules" section contains one or more Bison grammar rules,
  2474. and nothing else.  *Note Syntax of Grammar Rules: Rules.
  2475.  
  2476.    There must always be at least one grammar rule, and the first `%%'
  2477. (which precedes the grammar rules) may never be omitted even if it is
  2478. the first thing in the file.
  2479.  
  2480. 
  2481. File: bison,  Node: Epilogue,  Prev: Grammar Rules,  Up: Grammar Outline
  2482.  
  2483. 3.1.4 The epilogue
  2484. ------------------
  2485.  
  2486. The EPILOGUE is copied verbatim to the end of the parser file, just as
  2487. the PROLOGUE is copied to the beginning.  This is the most convenient
  2488. place to put anything that you want to have in the parser file but
  2489. which need not come before the definition of `yyparse'.  For example,
  2490. the definitions of `yylex' and `yyerror' often go here.  Because C
  2491. requires functions to be declared before being used, you often need to
  2492. declare functions like `yylex' and `yyerror' in the Prologue, even if
  2493. you define them int he Epilogue.  *Note Parser C-Language Interface:
  2494. Interface.
  2495.  
  2496.    If the last section is empty, you may omit the `%%' that separates it
  2497. from the grammar rules.
  2498.  
  2499.    The Bison parser itself contains many macros and identifiers whose
  2500. names start with `yy' or `YY', so it is a good idea to avoid using any
  2501. such names (except those documented in this manual) in the epilogue of
  2502. the grammar file.
  2503.  
  2504. 
  2505. File: bison,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  2506.  
  2507. 3.2 Symbols, Terminal and Nonterminal
  2508. =====================================
  2509.  
  2510. "Symbols" in Bison grammars represent the grammatical classifications
  2511. of the language.
  2512.  
  2513.    A "terminal symbol" (also known as a "token type") represents a
  2514. class of syntactically equivalent tokens.  You use the symbol in grammar
  2515. rules to mean that a token in that class is allowed.  The symbol is
  2516. represented in the Bison parser by a numeric code, and the `yylex'
  2517. function returns a token type code to indicate what kind of token has
  2518. been read.  You don't need to know what the code value is; you can use
  2519. the symbol to stand for it.
  2520.  
  2521.    A "nonterminal symbol" stands for a class of syntactically equivalent
  2522. groupings.  The symbol name is used in writing grammar rules.  By
  2523. convention, it should be all lower case.
  2524.  
  2525.    Symbol names can contain letters, digits (not at the beginning),
  2526. underscores and periods.  Periods make sense only in nonterminals.
  2527.  
  2528.    There are three ways of writing terminal symbols in the grammar:
  2529.  
  2530.    * A "named token type" is written with an identifier, like an
  2531.      identifier in C.  By convention, it should be all upper case.  Each
  2532.      such name must be defined with a Bison declaration such as
  2533.      `%token'.  *Note Token Type Names: Token Decl.
  2534.  
  2535.    * A "character token type" (or "literal character token") is written
  2536.      in the grammar using the same syntax used in C for character
  2537.      constants; for example, `'+'' is a character token type.  A
  2538.      character token type doesn't need to be declared unless you need to
  2539.      specify its semantic value data type (*note Data Types of Semantic
  2540.      Values: Value Type.), associativity, or precedence (*note Operator
  2541.      Precedence: Precedence.).
  2542.  
  2543.      By convention, a character token type is used only to represent a
  2544.      token that consists of that particular character.  Thus, the token
  2545.      type `'+'' is used to represent the character `+' as a token.
  2546.      Nothing enforces this convention, but if you depart from it, your
  2547.      program will confuse other readers.
  2548.  
  2549.      All the usual escape sequences used in character literals in C can
  2550.      be used in Bison as well, but you must not use the null character
  2551.      as a character literal because its numeric code, zero, signifies
  2552.      end-of-input (*note Calling Convention for `yylex': Calling
  2553.      Convention.).  Also, unlike standard C, trigraphs have no special
  2554.      meaning in Bison character literals, nor is backslash-newline
  2555.      allowed.
  2556.  
  2557.    * A "literal string token" is written like a C string constant; for
  2558.      example, `"<="' is a literal string token.  A literal string token
  2559.      doesn't need to be declared unless you need to specify its semantic
  2560.      value data type (*note Value Type::), associativity, or precedence
  2561.      (*note Precedence::).
  2562.  
  2563.      You can associate the literal string token with a symbolic name as
  2564.      an alias, using the `%token' declaration (*note Token
  2565.      Declarations: Token Decl.).  If you don't do that, the lexical
  2566.      analyzer has to retrieve the token number for the literal string
  2567.      token from the `yytname' table (*note Calling Convention::).
  2568.  
  2569.      *Warning*: literal string tokens do not work in Yacc.
  2570.  
  2571.      By convention, a literal string token is used only to represent a
  2572.      token that consists of that particular string.  Thus, you should
  2573.      use the token type `"<="' to represent the string `<=' as a token.
  2574.      Bison does not enforce this convention, but if you depart from
  2575.      it, people who read your program will be confused.
  2576.  
  2577.      All the escape sequences used in string literals in C can be used
  2578.      in Bison as well.  However, unlike Standard C, trigraphs have no
  2579.      special meaning in Bison string literals, nor is backslash-newline
  2580.      allowed.  A literal string token must contain two or more
  2581.      characters; for a token containing just one character, use a
  2582.      character token (see above).
  2583.  
  2584.    How you choose to write a terminal symbol has no effect on its
  2585. grammatical meaning.  That depends only on where it appears in rules and
  2586. on when the parser function returns that symbol.
  2587.  
  2588.    The value returned by `yylex' is always one of the terminal symbols,
  2589. except that a zero or negative value signifies end-of-input.  Whichever
  2590. way you write the token type in the grammar rules, you write it the
  2591. same way in the definition of `yylex'.  The numeric code for a
  2592. character token type is simply the positive numeric code of the
  2593. character, so `yylex' can use the identical value to generate the
  2594. requisite code, though you may need to convert it to `unsigned char' to
  2595. avoid sign-extension on hosts where `char' is signed.  Each named token
  2596. type becomes a C macro in the parser file, so `yylex' can use the name
  2597. to stand for the code.  (This is why periods don't make sense in
  2598. terminal symbols.)  *Note Calling Convention for `yylex': Calling
  2599. Convention.
  2600.  
  2601.    If `yylex' is defined in a separate file, you need to arrange for the
  2602. token-type macro definitions to be available there.  Use the `-d'
  2603. option when you run Bison, so that it will write these macro definitions
  2604. into a separate header file `NAME.tab.h' which you can include in the
  2605. other source files that need it.  *Note Invoking Bison: Invocation.
  2606.  
  2607.    If you want to write a grammar that is portable to any Standard C
  2608. host, you must use only non-null character tokens taken from the basic
  2609. execution character set of Standard C.  This set consists of the ten
  2610. digits, the 52 lower- and upper-case English letters, and the
  2611. characters in the following C-language string:
  2612.  
  2613.      "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_{|}~"
  2614.  
  2615.    The `yylex' function and Bison must use a consistent character set
  2616. and encoding for character tokens.  For example, if you run Bison in an
  2617. ASCII environment, but then compile and run the resulting program in an
  2618. environment that uses an incompatible character set like EBCDIC, the
  2619. resulting program may not work because the tables generated by Bison
  2620. will assume ASCII numeric values for character tokens.  It is standard
  2621. practice for software distributions to contain C source files that were
  2622. generated by Bison in an ASCII environment, so installers on platforms
  2623. that are incompatible with ASCII must rebuild those files before
  2624. compiling them.
  2625.  
  2626.    The symbol `error' is a terminal symbol reserved for error recovery
  2627. (*note Error Recovery::); you shouldn't use it for any other purpose.
  2628. In particular, `yylex' should never return this value.  The default
  2629. value of the error token is 256, unless you explicitly assigned 256 to
  2630. one of your tokens with a `%token' declaration.
  2631.  
  2632. 
  2633. File: bison,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  2634.  
  2635. 3.3 Syntax of Grammar Rules
  2636. ===========================
  2637.  
  2638. A Bison grammar rule has the following general form:
  2639.  
  2640.      RESULT: COMPONENTS...
  2641.              ;
  2642.  
  2643. where RESULT is the nonterminal symbol that this rule describes, and
  2644. COMPONENTS are various terminal and nonterminal symbols that are put
  2645. together by this rule (*note Symbols::).
  2646.  
  2647.    For example,
  2648.  
  2649.      exp:      exp '+' exp
  2650.              ;
  2651.  
  2652. says that two groupings of type `exp', with a `+' token in between, can
  2653. be combined into a larger grouping of type `exp'.
  2654.  
  2655.    White space in rules is significant only to separate symbols.  You
  2656. can add extra white space as you wish.
  2657.  
  2658.    Scattered among the components can be ACTIONS that determine the
  2659. semantics of the rule.  An action looks like this:
  2660.  
  2661.      {C STATEMENTS}
  2662.  
  2663. Usually there is only one action and it follows the components.  *Note
  2664. Actions::.
  2665.  
  2666.    Multiple rules for the same RESULT can be written separately or can
  2667. be joined with the vertical-bar character `|' as follows:
  2668.  
  2669.      RESULT:   RULE1-COMPONENTS...
  2670.              | RULE2-COMPONENTS...
  2671.              ...
  2672.              ;
  2673.  
  2674. They are still considered distinct rules even when joined in this way.
  2675.  
  2676.    If COMPONENTS in a rule is empty, it means that RESULT can match the
  2677. empty string.  For example, here is how to define a comma-separated
  2678. sequence of zero or more `exp' groupings:
  2679.  
  2680.      expseq:   /* empty */
  2681.              | expseq1
  2682.              ;
  2683.  
  2684.      expseq1:  exp
  2685.              | expseq1 ',' exp
  2686.              ;
  2687.  
  2688. It is customary to write a comment `/* empty */' in each rule with no
  2689. components.
  2690.  
  2691. 
  2692. File: bison,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  2693.  
  2694. 3.4 Recursive Rules
  2695. ===================
  2696.  
  2697. A rule is called "recursive" when its RESULT nonterminal appears also
  2698. on its right hand side.  Nearly all Bison grammars need to use
  2699. recursion, because that is the only way to define a sequence of any
  2700. number of a particular thing.  Consider this recursive definition of a
  2701. comma-separated sequence of one or more expressions:
  2702.  
  2703.      expseq1:  exp
  2704.              | expseq1 ',' exp
  2705.              ;
  2706.  
  2707. Since the recursive use of `expseq1' is the leftmost symbol in the
  2708. right hand side, we call this "left recursion".  By contrast, here the
  2709. same construct is defined using "right recursion":
  2710.  
  2711.      expseq1:  exp
  2712.              | exp ',' expseq1
  2713.              ;
  2714.  
  2715. Any kind of sequence can be defined using either left recursion or right
  2716. recursion, but you should always use left recursion, because it can
  2717. parse a sequence of any number of elements with bounded stack space.
  2718. Right recursion uses up space on the Bison stack in proportion to the
  2719. number of elements in the sequence, because all the elements must be
  2720. shifted onto the stack before the rule can be applied even once.  *Note
  2721. The Bison Parser Algorithm: Algorithm, for further explanation of this.
  2722.  
  2723.    "Indirect" or "mutual" recursion occurs when the result of the rule
  2724. does not appear directly on its right hand side, but does appear in
  2725. rules for other nonterminals which do appear on its right hand side.
  2726.  
  2727.    For example:
  2728.  
  2729.      expr:     primary
  2730.              | primary '+' primary
  2731.              ;
  2732.  
  2733.      primary:  constant
  2734.              | '(' expr ')'
  2735.              ;
  2736.  
  2737. defines two mutually-recursive nonterminals, since each refers to the
  2738. other.
  2739.  
  2740. 
  2741. File: bison,  Node: Semantics,  Next: Locations,  Prev: Recursion,  Up: Grammar File
  2742.  
  2743. 3.5 Defining Language Semantics
  2744. ===============================
  2745.  
  2746. The grammar rules for a language determine only the syntax.  The
  2747. semantics are determined by the semantic values associated with various
  2748. tokens and groupings, and by the actions taken when various groupings
  2749. are recognized.
  2750.  
  2751.    For example, the calculator calculates properly because the value
  2752. associated with each expression is the proper number; it adds properly
  2753. because the action for the grouping `X + Y' is to add the numbers
  2754. associated with X and Y.
  2755.  
  2756. * Menu:
  2757.  
  2758. * Value Type::        Specifying one data type for all semantic values.
  2759. * Multiple Types::    Specifying several alternative data types.
  2760. * Actions::           An action is the semantic definition of a grammar rule.
  2761. * Action Types::      Specifying data types for actions to operate on.
  2762. * Mid-Rule Actions::  Most actions go at the end of a rule.
  2763.                       This says when, why and how to use the exceptional
  2764.                         action in the middle of a rule.
  2765.  
  2766. 
  2767. File: bison,  Node: Value Type,  Next: Multiple Types,  Up: Semantics
  2768.  
  2769. 3.5.1 Data Types of Semantic Values
  2770. -----------------------------------
  2771.  
  2772. In a simple program it may be sufficient to use the same data type for
  2773. the semantic values of all language constructs.  This was true in the
  2774. RPN and infix calculator examples (*note Reverse Polish Notation
  2775. Calculator: RPN Calc.).
  2776.  
  2777.    Bison's default is to use type `int' for all semantic values.  To
  2778. specify some other type, define `YYSTYPE' as a macro, like this:
  2779.  
  2780.      #define YYSTYPE double
  2781.  
  2782. This macro definition must go in the prologue of the grammar file
  2783. (*note Outline of a Bison Grammar: Grammar Outline.).
  2784.  
  2785. 
  2786. File: bison,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  2787.  
  2788. 3.5.2 More Than One Value Type
  2789. ------------------------------
  2790.  
  2791. In most programs, you will need different data types for different kinds
  2792. of tokens and groupings.  For example, a numeric constant may need type
  2793. `int' or `long', while a string constant needs type `char *', and an
  2794. identifier might need a pointer to an entry in the symbol table.
  2795.  
  2796.    To use more than one data type for semantic values in one parser,
  2797. Bison requires you to do two things:
  2798.  
  2799.    * Specify the entire collection of possible data types, with the
  2800.      `%union' Bison declaration (*note The Collection of Value Types:
  2801.      Union Decl.).
  2802.  
  2803.    * Choose one of those types for each symbol (terminal or
  2804.      nonterminal) for which semantic values are used.  This is done for
  2805.      tokens with the `%token' Bison declaration (*note Token Type
  2806.      Names: Token Decl.)  and for groupings with the `%type' Bison
  2807.      declaration (*note Nonterminal Symbols: Type Decl.).
  2808.  
  2809. 
  2810. File: bison,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  2811.  
  2812. 3.5.3 Actions
  2813. -------------
  2814.  
  2815. An action accompanies a syntactic rule and contains C code to be
  2816. executed each time an instance of that rule is recognized.  The task of
  2817. most actions is to compute a semantic value for the grouping built by
  2818. the rule from the semantic values associated with tokens or smaller
  2819. groupings.
  2820.  
  2821.    An action consists of C statements surrounded by braces, much like a
  2822. compound statement in C.  An action can contain any sequence of C
  2823. statements.  Bison does not look for trigraphs, though, so if your C
  2824. code uses trigraphs you should ensure that they do not affect the
  2825. nesting of braces or the boundaries of comments, strings, or character
  2826. literals.
  2827.  
  2828.    An action can be placed at any position in the rule; it is executed
  2829. at that position.  Most rules have just one action at the end of the
  2830. rule, following all the components.  Actions in the middle of a rule
  2831. are tricky and used only for special purposes (*note Actions in
  2832. Mid-Rule: Mid-Rule Actions.).
  2833.  
  2834.    The C code in an action can refer to the semantic values of the
  2835. components matched by the rule with the construct `$N', which stands for
  2836. the value of the Nth component.  The semantic value for the grouping
  2837. being constructed is `$$'.  (Bison translates both of these constructs
  2838. into array element references when it copies the actions into the parser
  2839. file.)
  2840.  
  2841.    Here is a typical example:
  2842.  
  2843.      exp:    ...
  2844.              | exp '+' exp
  2845.                  { $$ = $1 + $3; }
  2846.  
  2847. This rule constructs an `exp' from two smaller `exp' groupings
  2848. connected by a plus-sign token.  In the action, `$1' and `$3' refer to
  2849. the semantic values of the two component `exp' groupings, which are the
  2850. first and third symbols on the right hand side of the rule.  The sum is
  2851. stored into `$$' so that it becomes the semantic value of the
  2852. addition-expression just recognized by the rule.  If there were a
  2853. useful semantic value associated with the `+' token, it could be
  2854. referred to as `$2'.
  2855.  
  2856.    Note that the vertical-bar character `|' is really a rule separator,
  2857. and actions are attached to a single rule.  This is a difference with
  2858. tools like Flex, for which `|' stands for either "or", or "the same
  2859. action as that of the next rule".  In the following example, the action
  2860. is triggered only when `b' is found:
  2861.  
  2862.      a-or-b: 'a'|'b'   { a_or_b_found = 1; };
  2863.  
  2864.    If you don't specify an action for a rule, Bison supplies a default:
  2865. `$$ = $1'.  Thus, the value of the first symbol in the rule becomes the
  2866. value of the whole rule.  Of course, the default action is valid only
  2867. if the two data types match.  There is no meaningful default action for
  2868. an empty rule; every empty rule must have an explicit action unless the
  2869. rule's value does not matter.
  2870.  
  2871.    `$N' with N zero or negative is allowed for reference to tokens and
  2872. groupings on the stack _before_ those that match the current rule.
  2873. This is a very risky practice, and to use it reliably you must be
  2874. certain of the context in which the rule is applied.  Here is a case in
  2875. which you can use this reliably:
  2876.  
  2877.      foo:      expr bar '+' expr  { ... }
  2878.              | expr bar '-' expr  { ... }
  2879.              ;
  2880.  
  2881.      bar:      /* empty */
  2882.              { previous_expr = $0; }
  2883.              ;
  2884.  
  2885.    As long as `bar' is used only in the fashion shown here, `$0' always
  2886. refers to the `expr' which precedes `bar' in the definition of `foo'.
  2887.  
  2888. 
  2889. File: bison,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  2890.  
  2891. 3.5.4 Data Types of Values in Actions
  2892. -------------------------------------
  2893.  
  2894. If you have chosen a single data type for semantic values, the `$$' and
  2895. `$N' constructs always have that data type.
  2896.  
  2897.    If you have used `%union' to specify a variety of data types, then
  2898. you must declare a choice among these types for each terminal or
  2899. nonterminal symbol that can have a semantic value.  Then each time you
  2900. use `$$' or `$N', its data type is determined by which symbol it refers
  2901. to in the rule.  In this example,
  2902.  
  2903.      exp:    ...
  2904.              | exp '+' exp
  2905.                  { $$ = $1 + $3; }
  2906.  
  2907. `$1' and `$3' refer to instances of `exp', so they all have the data
  2908. type declared for the nonterminal symbol `exp'.  If `$2' were used, it
  2909. would have the data type declared for the terminal symbol `'+'',
  2910. whatever that might be.
  2911.  
  2912.    Alternatively, you can specify the data type when you refer to the
  2913. value, by inserting `<TYPE>' after the `$' at the beginning of the
  2914. reference.  For example, if you have defined types as shown here:
  2915.  
  2916.      %union {
  2917.        int itype;
  2918.        double dtype;
  2919.      }
  2920.  
  2921. then you can write `$<itype>1' to refer to the first subunit of the
  2922. rule as an integer, or `$<dtype>1' to refer to it as a double.
  2923.  
  2924. 
  2925. File: bison,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  2926.  
  2927. 3.5.5 Actions in Mid-Rule
  2928. -------------------------
  2929.  
  2930. Occasionally it is useful to put an action in the middle of a rule.
  2931. These actions are written just like usual end-of-rule actions, but they
  2932. are executed before the parser even recognizes the following components.
  2933.  
  2934.    A mid-rule action may refer to the components preceding it using
  2935. `$N', but it may not refer to subsequent components because it is run
  2936. before they are parsed.
  2937.  
  2938.    The mid-rule action itself counts as one of the components of the
  2939. rule.  This makes a difference when there is another action later in
  2940. the same rule (and usually there is another at the end): you have to
  2941. count the actions along with the symbols when working out which number
  2942. N to use in `$N'.
  2943.  
  2944.    The mid-rule action can also have a semantic value.  The action can
  2945. set its value with an assignment to `$$', and actions later in the rule
  2946. can refer to the value using `$N'.  Since there is no symbol to name
  2947. the action, there is no way to declare a data type for the value in
  2948. advance, so you must use the `$<...>N' construct to specify a data type
  2949. each time you refer to this value.
  2950.  
  2951.    There is no way to set the value of the entire rule with a mid-rule
  2952. action, because assignments to `$$' do not have that effect.  The only
  2953. way to set the value for the entire rule is with an ordinary action at
  2954. the end of the rule.
  2955.  
  2956.    Here is an example from a hypothetical compiler, handling a `let'
  2957. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  2958. create a variable named VARIABLE temporarily for the duration of
  2959. STATEMENT.  To parse this construct, we must put VARIABLE into the
  2960. symbol table while STATEMENT is parsed, then remove it afterward.  Here
  2961. is how it is done:
  2962.  
  2963.      stmt:   LET '(' var ')'
  2964.                      { $<context>$ = push_context ();
  2965.                        declare_variable ($3); }
  2966.              stmt    { $$ = $6;
  2967.                        pop_context ($<context>5); }
  2968.  
  2969. As soon as `let (VARIABLE)' has been recognized, the first action is
  2970. run.  It saves a copy of the current semantic context (the list of
  2971. accessible variables) as its semantic value, using alternative
  2972. `context' in the data-type union.  Then it calls `declare_variable' to
  2973. add the new variable to that list.  Once the first action is finished,
  2974. the embedded statement `stmt' can be parsed.  Note that the mid-rule
  2975. action is component number 5, so the `stmt' is component number 6.
  2976.  
  2977.    After the embedded statement is parsed, its semantic value becomes
  2978. the value of the entire `let'-statement.  Then the semantic value from
  2979. the earlier action is used to restore the prior list of variables.  This
  2980. removes the temporary `let'-variable from the list so that it won't
  2981. appear to exist while the rest of the program is parsed.
  2982.  
  2983.    Taking action before a rule is completely recognized often leads to
  2984. conflicts since the parser must commit to a parse in order to execute
  2985. the action.  For example, the following two rules, without mid-rule
  2986. actions, can coexist in a working parser because the parser can shift
  2987. the open-brace token and look at what follows before deciding whether
  2988. there is a declaration or not:
  2989.  
  2990.      compound: '{' declarations statements '}'
  2991.              | '{' statements '}'
  2992.              ;
  2993.  
  2994. But when we add a mid-rule action as follows, the rules become
  2995. nonfunctional:
  2996.  
  2997.      compound: { prepare_for_local_variables (); }
  2998.                '{' declarations statements '}'
  2999.              | '{' statements '}'
  3000.              ;
  3001.  
  3002. Now the parser is forced to decide whether to run the mid-rule action
  3003. when it has read no farther than the open-brace.  In other words, it
  3004. must commit to using one rule or the other, without sufficient
  3005. information to do it correctly.  (The open-brace token is what is called
  3006. the "look-ahead" token at this time, since the parser is still deciding
  3007. what to do about it.  *Note Look-Ahead Tokens: Look-Ahead.)
  3008.  
  3009.    You might think that you could correct the problem by putting
  3010. identical actions into the two rules, like this:
  3011.  
  3012.      compound: { prepare_for_local_variables (); }
  3013.                '{' declarations statements '}'
  3014.              | { prepare_for_local_variables (); }
  3015.                '{' statements '}'
  3016.              ;
  3017.  
  3018. But this does not help, because Bison does not realize that the two
  3019. actions are identical.  (Bison never tries to understand the C code in
  3020. an action.)
  3021.  
  3022.    If the grammar is such that a declaration can be distinguished from a
  3023. statement by the first token (which is true in C), then one solution
  3024. which does work is to put the action after the open-brace, like this:
  3025.  
  3026.      compound: '{' { prepare_for_local_variables (); }
  3027.                declarations statements '}'
  3028.              | '{' statements '}'
  3029.              ;
  3030.  
  3031. Now the first token of the following declaration or statement, which
  3032. would in any case tell Bison which rule to use, can still do so.
  3033.  
  3034.    Another solution is to bury the action inside a nonterminal symbol
  3035. which serves as a subroutine:
  3036.  
  3037.      subroutine: /* empty */
  3038.                { prepare_for_local_variables (); }
  3039.              ;
  3040.  
  3041.      compound: subroutine
  3042.                '{' declarations statements '}'
  3043.              | subroutine
  3044.                '{' statements '}'
  3045.              ;
  3046.  
  3047. Now Bison can execute the action in the rule for `subroutine' without
  3048. deciding which rule for `compound' it will eventually use.  Note that
  3049. the action is now at the end of its rule.  Any mid-rule action can be
  3050. converted to an end-of-rule action in this way, and this is what Bison
  3051. actually does to implement mid-rule actions.
  3052.  
  3053. 
  3054. File: bison,  Node: Locations,  Next: Declarations,  Prev: Semantics,  Up: Grammar File
  3055.  
  3056. 3.6 Tracking Locations
  3057. ======================
  3058.  
  3059. Though grammar rules and semantic actions are enough to write a fully
  3060. functional parser, it can be useful to process some additional
  3061. information, especially symbol locations.
  3062.  
  3063.    The way locations are handled is defined by providing a data type,
  3064. and actions to take when rules are matched.
  3065.  
  3066. * Menu:
  3067.  
  3068. * Location Type::               Specifying a data type for locations.
  3069. * Actions and Locations::       Using locations in actions.
  3070. * Location Default Action::     Defining a general way to compute locations.
  3071.  
  3072. 
  3073. File: bison,  Node: Location Type,  Next: Actions and Locations,  Up: Locations
  3074.  
  3075. 3.6.1 Data Type of Locations
  3076. ----------------------------
  3077.  
  3078. Defining a data type for locations is much simpler than for semantic
  3079. values, since all tokens and groupings always use the same type.
  3080.  
  3081.    The type of locations is specified by defining a macro called
  3082. `YYLTYPE'.  When `YYLTYPE' is not defined, Bison uses a default
  3083. structure type with four members:
  3084.  
  3085.      typedef struct YYLTYPE
  3086.      {
  3087.        int first_line;
  3088.        int first_column;
  3089.        int last_line;
  3090.        int last_column;
  3091.      } YYLTYPE;
  3092.  
  3093. 
  3094. File: bison,  Node: Actions and Locations,  Next: Location Default Action,  Prev: Location Type,  Up: Locations
  3095.  
  3096. 3.6.2 Actions and Locations
  3097. ---------------------------
  3098.  
  3099. Actions are not only useful for defining language semantics, but also
  3100. for describing the behavior of the output parser with locations.
  3101.  
  3102.    The most obvious way for building locations of syntactic groupings
  3103. is very similar to the way semantic values are computed.  In a given
  3104. rule, several constructs can be used to access the locations of the
  3105. elements being matched.  The location of the Nth component of the right
  3106. hand side is `@N', while the location of the left hand side grouping is
  3107. `@$'.
  3108.  
  3109.    Here is a basic example using the default data type for locations:
  3110.  
  3111.      exp:    ...
  3112.              | exp '/' exp
  3113.                  {
  3114.                    @$.first_column = @1.first_column;
  3115.                    @$.first_line = @1.first_line;
  3116.                    @$.last_column = @3.last_column;
  3117.                    @$.last_line = @3.last_line;
  3118.                    if ($3)
  3119.                      $$ = $1 / $3;
  3120.                    else
  3121.                      {
  3122.                        $$ = 1;
  3123.                        printf("Division by zero, l%d,c%d-l%d,c%d",
  3124.                               @3.first_line, @3.first_column,
  3125.                               @3.last_line, @3.last_column);
  3126.                      }
  3127.                  }
  3128.  
  3129.    As for semantic values, there is a default action for locations that
  3130. is run each time a rule is matched.  It sets the beginning of `@$' to
  3131. the beginning of the first symbol, and the end of `@$' to the end of the
  3132. last symbol.
  3133.  
  3134.    With this default action, the location tracking can be fully
  3135. automatic.  The example above simply rewrites this way:
  3136.  
  3137.      exp:    ...
  3138.              | exp '/' exp
  3139.                  {
  3140.                    if ($3)
  3141.                      $$ = $1 / $3;
  3142.                    else
  3143.                      {
  3144.                        $$ = 1;
  3145.                        printf("Division by zero, l%d,c%d-l%d,c%d",
  3146.                               @3.first_line, @3.first_column,
  3147.                               @3.last_line, @3.last_column);
  3148.                      }
  3149.                  }
  3150.  
  3151. 
  3152. File: bison,  Node: Location Default Action,  Prev: Actions and Locations,  Up: Locations
  3153.  
  3154. 3.6.3 Default Action for Locations
  3155. ----------------------------------
  3156.  
  3157. Actually, actions are not the best place to compute locations.  Since
  3158. locations are much more general than semantic values, there is room in
  3159. the output parser to redefine the default action to take for each rule.
  3160. The `YYLLOC_DEFAULT' macro is invoked each time a rule is matched,
  3161. before the associated action is run.  It is also invoked while
  3162. processing a syntax error, to compute the error's location.
  3163.  
  3164.    Most of the time, this macro is general enough to suppress location
  3165. dedicated code from semantic actions.
  3166.  
  3167.    The `YYLLOC_DEFAULT' macro takes three parameters.  The first one is
  3168. the location of the grouping (the result of the computation).  When a
  3169. rule is matched, the second parameter is an array holding locations of
  3170. all right hand side elements of the rule being matched, and the third
  3171. parameter is the size of the rule's right hand side.  When processing a
  3172. syntax error, the second parameter is an array holding locations of the
  3173. symbols that were discarded during error processing, and the third
  3174. parameter is the number of discarded symbols.
  3175.  
  3176.    By default, `YYLLOC_DEFAULT' is defined this way for simple LALR(1)
  3177. parsers:
  3178.  
  3179.      #define YYLLOC_DEFAULT(Current, Rhs, N)          \
  3180.        Current.first_line   = Rhs[1].first_line;      \
  3181.        Current.first_column = Rhs[1].first_column;    \
  3182.        Current.last_line    = Rhs[N].last_line;       \
  3183.        Current.last_column  = Rhs[N].last_column;
  3184.  
  3185. and like this for GLR parsers:
  3186.  
  3187.      #define YYLLOC_DEFAULT(Current, Rhs, N)          \
  3188.        Current.first_line   = YYRHSLOC(Rhs,1).first_line;      \
  3189.        Current.first_column = YYRHSLOC(Rhs,1).first_column;    \
  3190.        Current.last_line    = YYRHSLOC(Rhs,N).last_line;       \
  3191.        Current.last_column  = YYRHSLOC(Rhs,N).last_column;
  3192.  
  3193.    When defining `YYLLOC_DEFAULT', you should consider that:
  3194.  
  3195.    * All arguments are free of side-effects.  However, only the first
  3196.      one (the result) should be modified by `YYLLOC_DEFAULT'.
  3197.  
  3198.    * For consistency with semantic actions, valid indexes for the
  3199.      location array range from 1 to N.
  3200.  
  3201. 
  3202. File: bison,  Node: Declarations,  Next: Multiple Parsers,  Prev: Locations,  Up: Grammar File
  3203.  
  3204. 3.7 Bison Declarations
  3205. ======================
  3206.  
  3207. The "Bison declarations" section of a Bison grammar defines the symbols
  3208. used in formulating the grammar and the data types of semantic values.
  3209. *Note Symbols::.
  3210.  
  3211.    All token type names (but not single-character literal tokens such as
  3212. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  3213. declared if you need to specify which data type to use for the semantic
  3214. value (*note More Than One Value Type: Multiple Types.).
  3215.  
  3216.    The first rule in the file also specifies the start symbol, by
  3217. default.  If you want some other symbol to be the start symbol, you
  3218. must declare it explicitly (*note Languages and Context-Free Grammars:
  3219. Language and Grammar.).
  3220.  
  3221. * Menu:
  3222.  
  3223. * Token Decl::        Declaring terminal symbols.
  3224. * Precedence Decl::   Declaring terminals with precedence and associativity.
  3225. * Union Decl::        Declaring the set of all semantic value types.
  3226. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  3227. * Destructor Decl::   Declaring how symbols are freed.
  3228. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  3229. * Start Decl::        Specifying the start symbol.
  3230. * Pure Decl::         Requesting a reentrant parser.
  3231. * Decl Summary::      Table of all Bison declarations.
  3232.  
  3233. 
  3234. File: bison,  Node: Token Decl,  Next: Precedence Decl,  Up: Declarations
  3235.  
  3236. 3.7.1 Token Type Names
  3237. ----------------------
  3238.  
  3239. The basic way to declare a token type name (terminal symbol) is as
  3240. follows:
  3241.  
  3242.      %token NAME
  3243.  
  3244.    Bison will convert this into a `#define' directive in the parser, so
  3245. that the function `yylex' (if it is in this file) can use the name NAME
  3246. to stand for this token type's code.
  3247.  
  3248.    Alternatively, you can use `%left', `%right', or `%nonassoc' instead
  3249. of `%token', if you wish to specify associativity and precedence.
  3250. *Note Operator Precedence: Precedence Decl.
  3251.  
  3252.    You can explicitly specify the numeric code for a token type by
  3253. appending an integer value in the field immediately following the token
  3254. name:
  3255.  
  3256.      %token NUM 300
  3257.  
  3258. It is generally best, however, to let Bison choose the numeric codes for
  3259. all token types.  Bison will automatically select codes that don't
  3260. conflict with each other or with normal characters.
  3261.  
  3262.    In the event that the stack type is a union, you must augment the
  3263. `%token' or other token declaration to include the data type
  3264. alternative delimited by angle-brackets (*note More Than One Value
  3265. Type: Multiple Types.).
  3266.  
  3267.    For example:
  3268.  
  3269.      %union {              /* define stack type */
  3270.        double val;
  3271.        symrec *tptr;
  3272.      }
  3273.      %token <val> NUM      /* define token NUM and its type */
  3274.  
  3275.    You can associate a literal string token with a token type name by
  3276. writing the literal string at the end of a `%token' declaration which
  3277. declares the name.  For example:
  3278.  
  3279.      %token arrow "=>"
  3280.  
  3281. For example, a grammar for the C language might specify these names with
  3282. equivalent literal string tokens:
  3283.  
  3284.      %token  <operator>  OR      "||"
  3285.      %token  <operator>  LE 134  "<="
  3286.      %left  OR  "<="
  3287.  
  3288. Once you equate the literal string and the token name, you can use them
  3289. interchangeably in further declarations or the grammar rules.  The
  3290. `yylex' function can use the token name or the literal string to obtain
  3291. the token type code number (*note Calling Convention::).
  3292.  
  3293. 
  3294. File: bison,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  3295.  
  3296. 3.7.2 Operator Precedence
  3297. -------------------------
  3298.  
  3299. Use the `%left', `%right' or `%nonassoc' declaration to declare a token
  3300. and specify its precedence and associativity, all at once.  These are
  3301. called "precedence declarations".  *Note Operator Precedence:
  3302. Precedence, for general information on operator precedence.
  3303.  
  3304.    The syntax of a precedence declaration is the same as that of
  3305. `%token': either
  3306.  
  3307.      %left SYMBOLS...
  3308.  
  3309. or
  3310.  
  3311.      %left <TYPE> SYMBOLS...
  3312.  
  3313.    And indeed any of these declarations serves the purposes of `%token'.
  3314. But in addition, they specify the associativity and relative precedence
  3315. for all the SYMBOLS:
  3316.  
  3317.    * The associativity of an operator OP determines how repeated uses
  3318.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  3319.      X with Y first or by grouping Y with Z first.  `%left' specifies
  3320.      left-associativity (grouping X with Y first) and `%right'
  3321.      specifies right-associativity (grouping Y with Z first).
  3322.      `%nonassoc' specifies no associativity, which means that `X OP Y
  3323.      OP Z' is considered a syntax error.
  3324.  
  3325.    * The precedence of an operator determines how it nests with other
  3326.      operators.  All the tokens declared in a single precedence
  3327.      declaration have equal precedence and nest together according to
  3328.      their associativity.  When two tokens declared in different
  3329.      precedence declarations associate, the one declared later has the
  3330.      higher precedence and is grouped first.
  3331.  
  3332. 
  3333. File: bison,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  3334.  
  3335. 3.7.3 The Collection of Value Types
  3336. -----------------------------------
  3337.  
  3338. The `%union' declaration specifies the entire collection of possible
  3339. data types for semantic values.  The keyword `%union' is followed by a
  3340. pair of braces containing the same thing that goes inside a `union' in
  3341. C.
  3342.  
  3343.    For example:
  3344.  
  3345.      %union {
  3346.        double val;
  3347.        symrec *tptr;
  3348.      }
  3349.  
  3350. This says that the two alternative types are `double' and `symrec *'.
  3351. They are given names `val' and `tptr'; these names are used in the
  3352. `%token' and `%type' declarations to pick one of the types for a
  3353. terminal or nonterminal symbol (*note Nonterminal Symbols: Type Decl.).
  3354.  
  3355.    As an extension to POSIX, a tag is allowed after the `union'.  For
  3356. example:
  3357.  
  3358.      %union value {
  3359.        double val;
  3360.        symrec *tptr;
  3361.      }
  3362.  
  3363.    specifies the union tag `value', so the corresponding C type is
  3364. `union value'.  If you do not specify a tag, it defaults to `YYSTYPE'.
  3365.  
  3366.    Note that, unlike making a `union' declaration in C, you need not
  3367. write a semicolon after the closing brace.
  3368.  
  3369. 
  3370. File: bison,  Node: Type Decl,  Next: Destructor Decl,  Prev: Union Decl,  Up: Declarations
  3371.  
  3372. 3.7.4 Nonterminal Symbols
  3373. -------------------------
  3374.  
  3375. When you use `%union' to specify multiple value types, you must declare
  3376. the value type of each nonterminal symbol for which values are used.
  3377. This is done with a `%type' declaration, like this:
  3378.  
  3379.      %type <TYPE> NONTERMINAL...
  3380.  
  3381. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  3382. name given in the `%union' to the alternative that you want (*note The
  3383. Collection of Value Types: Union Decl.).  You can give any number of
  3384. nonterminal symbols in the same `%type' declaration, if they have the
  3385. same value type.  Use spaces to separate the symbol names.
  3386.  
  3387.    You can also declare the value type of a terminal symbol.  To do
  3388. this, use the same `<TYPE>' construction in a declaration for the
  3389. terminal symbol.  All kinds of token declarations allow `<TYPE>'.
  3390.  
  3391. 
  3392. File: bison,  Node: Destructor Decl,  Next: Expect Decl,  Prev: Type Decl,  Up: Declarations
  3393.  
  3394. 3.7.5 Freeing Discarded Symbols
  3395. -------------------------------
  3396.  
  3397. Some symbols can be discarded by the parser, typically during error
  3398. recovery (*note Error Recovery::).  Basically, during error recovery,
  3399. embarrassing symbols already pushed on the stack, and embarrassing
  3400. tokens coming from the rest of the file are thrown away until the parser
  3401. falls on its feet.  If these symbols convey heap based information, this
  3402. memory is lost.  While this behavior is tolerable for batch parsers,
  3403. such as in compilers, it is unacceptable for parsers that can
  3404. possibility "never end" such as shells, or implementations of
  3405. communication protocols.
  3406.  
  3407.    The `%destructor' directive allows for the definition of code that
  3408. is called when a symbol is thrown away.
  3409.  
  3410.  -- Directive: %destructor { CODE } SYMBOLS
  3411.      Declare that the CODE must be invoked for each of the SYMBOLS that
  3412.      will be discarded by the parser.  The CODE should use `$$' to
  3413.      designate the semantic value associated to the SYMBOLS.  The
  3414.      additional parser parameters are also avaible (*note The Parser
  3415.      Function `yyparse': Parser Function.).
  3416.  
  3417.      *Warning:* as of Bison 1.875, this feature is still considered as
  3418.      experimental, as there was not enough user feedback.  In
  3419.      particular, the syntax might still change.
  3420.  
  3421.    For instance:
  3422.  
  3423.      %union
  3424.      {
  3425.        char *string;
  3426.      }
  3427.      %token <string> STRING
  3428.      %type  <string> string
  3429.      %destructor { free ($$); } STRING string
  3430.  
  3431. guarantees that when a `STRING' or a `string' will be discarded, its
  3432. associated memory will be freed.
  3433.  
  3434.    Note that in the future, Bison might also consider that right hand
  3435. side members that are not mentioned in the action can be destroyed.  For
  3436. instance, in:
  3437.  
  3438.      comment: "/*" STRING "*/";
  3439.  
  3440. the parser is entitled to destroy the semantic value of the `string'.
  3441. Of course, this will not apply to the default action; compare:
  3442.  
  3443.      typeless: string;  // $$ = $1 does not apply; $1 is destroyed.
  3444.      typefull: string;  // $$ = $1 applies, $1 is not destroyed.
  3445.  
  3446. 
  3447. File: bison,  Node: Expect Decl,  Next: Start Decl,  Prev: Destructor Decl,  Up: Declarations
  3448.  
  3449. 3.7.6 Suppressing Conflict Warnings
  3450. -----------------------------------
  3451.  
  3452. Bison normally warns if there are any conflicts in the grammar (*note
  3453. Shift/Reduce Conflicts: Shift/Reduce.), but most real grammars have
  3454. harmless shift/reduce conflicts which are resolved in a predictable way
  3455. and would be difficult to eliminate.  It is desirable to suppress the
  3456. warning about these conflicts unless the number of conflicts changes.
  3457. You can do this with the `%expect' declaration.
  3458.  
  3459.    The declaration looks like this:
  3460.  
  3461.      %expect N
  3462.  
  3463.    Here N is a decimal integer.  The declaration says there should be
  3464. no warning if there are N shift/reduce conflicts and no reduce/reduce
  3465. conflicts.  An error, instead of the usual warning, is given if there
  3466. are either more or fewer conflicts, or if there are any reduce/reduce
  3467. conflicts.
  3468.  
  3469.    In general, using `%expect' involves these steps:
  3470.  
  3471.    * Compile your grammar without `%expect'.  Use the `-v' option to
  3472.      get a verbose list of where the conflicts occur.  Bison will also
  3473.      print the number of conflicts.
  3474.  
  3475.    * Check each of the conflicts to make sure that Bison's default
  3476.      resolution is what you really want.  If not, rewrite the grammar
  3477.      and go back to the beginning.
  3478.  
  3479.    * Add an `%expect' declaration, copying the number N from the number
  3480.      which Bison printed.
  3481.  
  3482.    Now Bison will stop annoying you about the conflicts you have
  3483. checked, but it will warn you again if changes in the grammar result in
  3484. additional conflicts.
  3485.  
  3486. 
  3487. File: bison,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  3488.  
  3489. 3.7.7 The Start-Symbol
  3490. ----------------------
  3491.  
  3492. Bison assumes by default that the start symbol for the grammar is the
  3493. first nonterminal specified in the grammar specification section.  The
  3494. programmer may override this restriction with the `%start' declaration
  3495. as follows:
  3496.  
  3497.      %start SYMBOL
  3498.  
  3499. 
  3500. File: bison,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  3501.  
  3502. 3.7.8 A Pure (Reentrant) Parser
  3503. -------------------------------
  3504.  
  3505. A "reentrant" program is one which does not alter in the course of
  3506. execution; in other words, it consists entirely of "pure" (read-only)
  3507. code.  Reentrancy is important whenever asynchronous execution is
  3508. possible; for example, a non-reentrant program may not be safe to call
  3509. from a signal handler.  In systems with multiple threads of control, a
  3510. non-reentrant program must be called only within interlocks.
  3511.  
  3512.    Normally, Bison generates a parser which is not reentrant.  This is
  3513. suitable for most uses, and it permits compatibility with Yacc.  (The
  3514. standard Yacc interfaces are inherently nonreentrant, because they use
  3515. statically allocated variables for communication with `yylex',
  3516. including `yylval' and `yylloc'.)
  3517.  
  3518.    Alternatively, you can generate a pure, reentrant parser.  The Bison
  3519. declaration `%pure-parser' says that you want the parser to be
  3520. reentrant.  It looks like this:
  3521.  
  3522.      %pure-parser
  3523.  
  3524.    The result is that the communication variables `yylval' and `yylloc'
  3525. become local variables in `yyparse', and a different calling convention
  3526. is used for the lexical analyzer function `yylex'.  *Note Calling
  3527. Conventions for Pure Parsers: Pure Calling, for the details of this.
  3528. The variable `yynerrs' also becomes local in `yyparse' (*note The Error
  3529. Reporting Function `yyerror': Error Reporting.).  The convention for
  3530. calling `yyparse' itself is unchanged.
  3531.  
  3532.    Whether the parser is pure has nothing to do with the grammar rules.
  3533. You can generate either a pure parser or a nonreentrant parser from any
  3534. valid grammar.
  3535.  
  3536. 
  3537. File: bison,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  3538.  
  3539. 3.7.9 Bison Declaration Summary
  3540. -------------------------------
  3541.  
  3542. Here is a summary of the declarations used to define a grammar:
  3543.  
  3544.  -- Directive: %union
  3545.      Declare the collection of data types that semantic values may have
  3546.      (*note The Collection of Value Types: Union Decl.).
  3547.  
  3548.  -- Directive: %token
  3549.      Declare a terminal symbol (token type name) with no precedence or
  3550.      associativity specified (*note Token Type Names: Token Decl.).
  3551.  
  3552.  -- Directive: %right
  3553.      Declare a terminal symbol (token type name) that is
  3554.      right-associative (*note Operator Precedence: Precedence Decl.).
  3555.  
  3556.  -- Directive: %left
  3557.      Declare a terminal symbol (token type name) that is
  3558.      left-associative (*note Operator Precedence: Precedence Decl.).
  3559.  
  3560.  -- Directive: %nonassoc
  3561.      Declare a terminal symbol (token type name) that is nonassociative
  3562.      (using it in a way that would be associative is a syntax error)
  3563.    (*note Operator Precedence: Precedence Decl.).
  3564.  
  3565.  -- Directive: %type
  3566.      Declare the type of semantic values for a nonterminal symbol
  3567.      (*note Nonterminal Symbols: Type Decl.).
  3568.  
  3569.  -- Directive: %start
  3570.      Specify the grammar's start symbol (*note The Start-Symbol: Start
  3571.      Decl.).
  3572.  
  3573.  -- Directive: %expect
  3574.      Declare the expected number of shift-reduce conflicts (*note
  3575.      Suppressing Conflict Warnings: Expect Decl.).
  3576.  
  3577.  
  3578. In order to change the behavior of `bison', use the following
  3579. directives:
  3580.  
  3581.  -- Directive: %debug
  3582.      In the parser file, define the macro `YYDEBUG' to 1 if it is not
  3583.      already defined, so that the debugging facilities are compiled.
  3584.    *Note Tracing Your Parser: Tracing.
  3585.  
  3586.  -- Directive: %defines
  3587.      Write an extra output file containing macro definitions for the
  3588.      token type names defined in the grammar and the semantic value type
  3589.      `YYSTYPE', as well as a few `extern' variable declarations.
  3590.  
  3591.      If the parser output file is named `NAME.c' then this file is
  3592.      named `NAME.h'.
  3593.  
  3594.      This output file is essential if you wish to put the definition of
  3595.      `yylex' in a separate source file, because `yylex' needs to be
  3596.      able to refer to token type codes and the variable `yylval'.
  3597.      *Note Semantic Values of Tokens: Token Values.
  3598.  
  3599.  -- Directive: %destructor
  3600.      Specifying how the parser should reclaim the memory associated to
  3601.      discarded symbols. *Note Freeing Discarded Symbols: Destructor
  3602.      Decl.
  3603.  
  3604.  -- Directive: %file-prefix="PREFIX"
  3605.      Specify a prefix to use for all Bison output file names.  The
  3606.      names are chosen as if the input file were named `PREFIX.y'.
  3607.  
  3608.  -- Directive: %locations
  3609.      Generate the code processing the locations (*note Special Features
  3610.      for Use in Actions: Action Features.).  This mode is enabled as
  3611.      soon as the grammar uses the special `@N' tokens, but if your
  3612.      grammar does not use it, using `%locations' allows for more
  3613.      accurate syntax error messages.
  3614.  
  3615.  -- Directive: %name-prefix="PREFIX"
  3616.      Rename the external symbols used in the parser so that they start
  3617.      with PREFIX instead of `yy'.  The precise list of symbols renamed
  3618.      is `yyparse', `yylex', `yyerror', `yynerrs', `yylval', `yylloc',
  3619.      `yychar', `yydebug', and possible `yylloc'.  For example, if you
  3620.      use `%name-prefix="c_"', the names become `c_parse', `c_lex', and
  3621.      so on.  *Note Multiple Parsers in the Same Program: Multiple
  3622.      Parsers.
  3623.  
  3624.  -- Directive: %no-parser
  3625.      Do not include any C code in the parser file; generate tables
  3626.      only.  The parser file contains just `#define' directives and
  3627.      static variable declarations.
  3628.  
  3629.      This option also tells Bison to write the C code for the grammar
  3630.      actions into a file named `FILENAME.act', in the form of a
  3631.      brace-surrounded body fit for a `switch' statement.
  3632.  
  3633.  -- Directive: %no-lines
  3634.      Don't generate any `#line' preprocessor commands in the parser
  3635.      file.  Ordinarily Bison writes these commands in the parser file
  3636.      so that the C compiler and debuggers will associate errors and
  3637.      object code with your source file (the grammar file).  This
  3638.      directive causes them to associate errors with the parser file,
  3639.      treating it an independent source file in its own right.
  3640.  
  3641.  -- Directive: %output="FILENAME"
  3642.      Specify the FILENAME for the parser file.
  3643.  
  3644.  -- Directive: %pure-parser
  3645.      Request a pure (reentrant) parser program (*note A Pure
  3646.      (Reentrant) Parser: Pure Decl.).
  3647.  
  3648.  -- Directive: %token-table
  3649.      Generate an array of token names in the parser file.  The name of
  3650.      the array is `yytname'; `yytname[I]' is the name of the token
  3651.      whose internal Bison token code number is I.  The first three
  3652.      elements of `yytname' correspond to the predefined tokens `"$end"',
  3653.      `"error"', and `"$undefined"'; after these come the symbols
  3654.      defined in the grammar file.
  3655.  
  3656.      For single-character literal tokens and literal string tokens, the
  3657.      name in the table includes the single-quote or double-quote
  3658.      characters: for example, `"'+'"' is a single-character literal and
  3659.      `"\"<=\""' is a literal string token.  All the characters of the
  3660.      literal string token appear verbatim in the string found in the
  3661.      table; even double-quote characters are not escaped.  For example,
  3662.      if the token consists of three characters `*"*', its string in
  3663.      `yytname' contains `"*"*"'.  (In C, that would be written as
  3664.      `"\"*\"*\""').
  3665.  
  3666.      When you specify `%token-table', Bison also generates macro
  3667.      definitions for macros `YYNTOKENS', `YYNNTS', and `YYNRULES', and
  3668.      `YYNSTATES':
  3669.  
  3670.     `YYNTOKENS'
  3671.           The highest token number, plus one.
  3672.  
  3673.     `YYNNTS'
  3674.           The number of nonterminal symbols.
  3675.  
  3676.     `YYNRULES'
  3677.           The number of grammar rules,
  3678.  
  3679.     `YYNSTATES'
  3680.           The number of parser states (*note Parser States::).
  3681.  
  3682.  -- Directive: %verbose
  3683.      Write an extra output file containing verbose descriptions of the
  3684.      parser states and what is done for each type of look-ahead token in
  3685.      that state.  *Note Understanding Your Parser: Understanding, for
  3686.      more information.
  3687.  
  3688.  -- Directive: %yacc
  3689.      Pretend the option `--yacc' was given, i.e., imitate Yacc,
  3690.      including its naming conventions.  *Note Bison Options::, for more.
  3691.  
  3692. 
  3693. File: bison,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  3694.  
  3695. 3.8 Multiple Parsers in the Same Program
  3696. ========================================
  3697.  
  3698. Most programs that use Bison parse only one language and therefore
  3699. contain only one Bison parser.  But what if you want to parse more than
  3700. one language with the same program?  Then you need to avoid a name
  3701. conflict between different definitions of `yyparse', `yylval', and so
  3702. on.
  3703.  
  3704.    The easy way to do this is to use the option `-p PREFIX' (*note
  3705. Invoking Bison: Invocation.).  This renames the interface functions and
  3706. variables of the Bison parser to start with PREFIX instead of `yy'.
  3707. You can use this to give each parser distinct names that do not
  3708. conflict.
  3709.  
  3710.    The precise list of symbols renamed is `yyparse', `yylex',
  3711. `yyerror', `yynerrs', `yylval', `yylloc', `yychar' and `yydebug'.  For
  3712. example, if you use `-p c', the names become `cparse', `clex', and so
  3713. on.
  3714.  
  3715.    *All the other variables and macros associated with Bison are not
  3716. renamed.* These others are not global; there is no conflict if the same
  3717. name is used in different parsers.  For example, `YYSTYPE' is not
  3718. renamed, but defining this in different ways in different parsers causes
  3719. no trouble (*note Data Types of Semantic Values: Value Type.).
  3720.  
  3721.    The `-p' option works by adding macro definitions to the beginning
  3722. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  3723. on.  This effectively substitutes one name for the other in the entire
  3724. parser file.
  3725.  
  3726. 
  3727. File: bison,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  3728.  
  3729. 4 Parser C-Language Interface
  3730. *****************************
  3731.  
  3732. The Bison parser is actually a C function named `yyparse'.  Here we
  3733. describe the interface conventions of `yyparse' and the other functions
  3734. that it needs to use.
  3735.  
  3736.    Keep in mind that the parser uses many C identifiers starting with
  3737. `yy' and `YY' for internal purposes.  If you use such an identifier
  3738. (aside from those in this manual) in an action or in epilogue in the
  3739. grammar file, you are likely to run into trouble.
  3740.  
  3741. * Menu:
  3742.  
  3743. * Parser Function::   How to call `yyparse' and what it returns.
  3744. * Lexical::           You must supply a function `yylex'
  3745.                         which reads tokens.
  3746. * Error Reporting::   You must supply a function `yyerror'.
  3747. * Action Features::   Special features for use in actions.
  3748.  
  3749. 
  3750. File: bison,  Node: Parser Function,  Next: Lexical,  Up: Interface
  3751.  
  3752. 4.1 The Parser Function `yyparse'
  3753. =================================
  3754.  
  3755. You call the function `yyparse' to cause parsing to occur.  This
  3756. function reads tokens, executes actions, and ultimately returns when it
  3757. encounters end-of-input or an unrecoverable syntax error.  You can also
  3758. write an action which directs `yyparse' to return immediately without
  3759. reading further.
  3760.  
  3761.  -- Function: int yyparse (void)
  3762.      The value returned by `yyparse' is 0 if parsing was successful
  3763.      (return is due to end-of-input).
  3764.  
  3765.      The value is 1 if parsing failed (return is due to a syntax error).
  3766.  
  3767.    In an action, you can cause immediate return from `yyparse' by using
  3768. these macros:
  3769.  
  3770.  -- Macro: YYACCEPT
  3771.      Return immediately with value 0 (to report success).
  3772.  
  3773.  -- Macro: YYABORT
  3774.      Return immediately with value 1 (to report failure).
  3775.  
  3776. 
  3777. File: bison,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  3778.  
  3779. 4.2 The Lexical Analyzer Function `yylex'
  3780. =========================================
  3781.  
  3782. The "lexical analyzer" function, `yylex', recognizes tokens from the
  3783. input stream and returns them to the parser.  Bison does not create
  3784. this function automatically; you must write it so that `yyparse' can
  3785. call it.  The function is sometimes referred to as a lexical scanner.
  3786.  
  3787.    In simple programs, `yylex' is often defined at the end of the Bison
  3788. grammar file.  If `yylex' is defined in a separate source file, you
  3789. need to arrange for the token-type macro definitions to be available
  3790. there.  To do this, use the `-d' option when you run Bison, so that it
  3791. will write these macro definitions into a separate header file
  3792. `NAME.tab.h' which you can include in the other source files that need
  3793. it.  *Note Invoking Bison: Invocation.
  3794.  
  3795. * Menu:
  3796.  
  3797. * Calling Convention::  How `yyparse' calls `yylex'.
  3798. * Token Values::      How `yylex' must return the semantic value
  3799.                         of the token it has read.
  3800. * Token Positions::   How `yylex' must return the text position
  3801.                         (line number, etc.) of the token, if the
  3802.                         actions want that.
  3803. * Pure Calling::      How the calling convention differs
  3804.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  3805.  
  3806. 
  3807. File: bison,  Node: Calling Convention,  Next: Token Values,  Up: Lexical
  3808.  
  3809. 4.2.1 Calling Convention for `yylex'
  3810. ------------------------------------
  3811.  
  3812. The value that `yylex' returns must be the positive numeric code for
  3813. the type of token it has just found; a zero or negative value signifies
  3814. end-of-input.
  3815.  
  3816.    When a token is referred to in the grammar rules by a name, that name
  3817. in the parser file becomes a C macro whose definition is the proper
  3818. numeric code for that token type.  So `yylex' can use the name to
  3819. indicate that type.  *Note Symbols::.
  3820.  
  3821.    When a token is referred to in the grammar rules by a character
  3822. literal, the numeric code for that character is also the code for the
  3823. token type.  So `yylex' can simply return that character code, possibly
  3824. converted to `unsigned char' to avoid sign-extension.  The null
  3825. character must not be used this way, because its code is zero and that
  3826. signifies end-of-input.
  3827.  
  3828.    Here is an example showing these things:
  3829.  
  3830.      int
  3831.      yylex (void)
  3832.      {
  3833.        ...
  3834.        if (c == EOF)    /* Detect end-of-input.  */
  3835.          return 0;
  3836.        ...
  3837.        if (c == '+' || c == '-')
  3838.          return c;      /* Assume token type for `+' is '+'.  */
  3839.        ...
  3840.        return INT;      /* Return the type of the token.  */
  3841.        ...
  3842.      }
  3843.  
  3844. This interface has been designed so that the output from the `lex'
  3845. utility can be used without change as the definition of `yylex'.
  3846.  
  3847.    If the grammar uses literal string tokens, there are two ways that
  3848. `yylex' can determine the token type codes for them:
  3849.  
  3850.    * If the grammar defines symbolic token names as aliases for the
  3851.      literal string tokens, `yylex' can use these symbolic names like
  3852.      all others.  In this case, the use of the literal string tokens in
  3853.      the grammar file has no effect on `yylex'.
  3854.  
  3855.    * `yylex' can find the multicharacter token in the `yytname' table.
  3856.      The index of the token in the table is the token type's code.  The
  3857.      name of a multicharacter token is recorded in `yytname' with a
  3858.      double-quote, the token's characters, and another double-quote.
  3859.      The token's characters are not escaped in any way; they appear
  3860.      verbatim in the contents of the string in the table.
  3861.  
  3862.      Here's code for looking up a token in `yytname', assuming that the
  3863.      characters of the token are stored in `token_buffer'.
  3864.  
  3865.           for (i = 0; i < YYNTOKENS; i++)
  3866.             {
  3867.               if (yytname[i] != 0
  3868.                   && yytname[i][0] == '"'
  3869.                   && ! strncmp (yytname[i] + 1, token_buffer,
  3870.                                 strlen (token_buffer))
  3871.                   && yytname[i][strlen (token_buffer) + 1] == '"'
  3872.                   && yytname[i][strlen (token_buffer) + 2] == 0)
  3873.                 break;
  3874.             }
  3875.  
  3876.      The `yytname' table is generated only if you use the
  3877.      `%token-table' declaration.  *Note Decl Summary::.
  3878.  
  3879. 
  3880. File: bison,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  3881.  
  3882. 4.2.2 Semantic Values of Tokens
  3883. -------------------------------
  3884.  
  3885. In an ordinary (non-reentrant) parser, the semantic value of the token
  3886. must be stored into the global variable `yylval'.  When you are using
  3887. just one data type for semantic values, `yylval' has that type.  Thus,
  3888. if the type is `int' (the default), you might write this in `yylex':
  3889.  
  3890.        ...
  3891.        yylval = value;  /* Put value onto Bison stack.  */
  3892.        return INT;      /* Return the type of the token.  */
  3893.        ...
  3894.  
  3895.    When you are using multiple data types, `yylval''s type is a union
  3896. made from the `%union' declaration (*note The Collection of Value
  3897. Types: Union Decl.).  So when you store a token's value, you must use
  3898. the proper member of the union.  If the `%union' declaration looks like
  3899. this:
  3900.  
  3901.      %union {
  3902.        int intval;
  3903.        double val;
  3904.        symrec *tptr;
  3905.      }
  3906.  
  3907. then the code in `yylex' might look like this:
  3908.  
  3909.        ...
  3910.        yylval.intval = value; /* Put value onto Bison stack.  */
  3911.        return INT;            /* Return the type of the token.  */
  3912.        ...
  3913.  
  3914. 
  3915. File: bison,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  3916.  
  3917. 4.2.3 Textual Positions of Tokens
  3918. ---------------------------------
  3919.  
  3920. If you are using the `@N'-feature (*note Tracking Locations:
  3921. Locations.) in actions to keep track of the textual locations of tokens
  3922. and groupings, then you must provide this information in `yylex'.  The
  3923. function `yyparse' expects to find the textual location of a token just
  3924. parsed in the global variable `yylloc'.  So `yylex' must store the
  3925. proper data in that variable.
  3926.  
  3927.    By default, the value of `yylloc' is a structure and you need only
  3928. initialize the members that are going to be used by the actions.  The
  3929. four members are called `first_line', `first_column', `last_line' and
  3930. `last_column'.  Note that the use of this feature makes the parser
  3931. noticeably slower.
  3932.  
  3933.    The data type of `yylloc' has the name `YYLTYPE'.
  3934.  
  3935. 
  3936. File: bison,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  3937.  
  3938. 4.2.4 Calling Conventions for Pure Parsers
  3939. ------------------------------------------
  3940.  
  3941. When you use the Bison declaration `%pure-parser' to request a pure,
  3942. reentrant parser, the global communication variables `yylval' and
  3943. `yylloc' cannot be used.  (*Note A Pure (Reentrant) Parser: Pure Decl.)
  3944. In such parsers the two global variables are replaced by pointers
  3945. passed as arguments to `yylex'.  You must declare them as shown here,
  3946. and pass the information back by storing it through those pointers.
  3947.  
  3948.      int
  3949.      yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
  3950.      {
  3951.        ...
  3952.        *lvalp = value;  /* Put value onto Bison stack.  */
  3953.        return INT;      /* Return the type of the token.  */
  3954.        ...
  3955.      }
  3956.  
  3957.    If the grammar file does not use the `@' constructs to refer to
  3958. textual positions, then the type `YYLTYPE' will not be defined.  In
  3959. this case, omit the second argument; `yylex' will be called with only
  3960. one argument.
  3961.  
  3962. 
  3963. File: bison,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  3964.  
  3965. 4.3 The Error Reporting Function `yyerror'
  3966. ==========================================
  3967.  
  3968. The Bison parser detects a "syntax error" or "parse error" whenever it
  3969. reads a token which cannot satisfy any syntax rule.  An action in the
  3970. grammar can also explicitly proclaim an error, using the macro
  3971. `YYERROR' (*note Special Features for Use in Actions: Action Features.).
  3972.  
  3973.    The Bison parser expects to report the error by calling an error
  3974. reporting function named `yyerror', which you must supply.  It is
  3975. called by `yyparse' whenever a syntax error is found, and it receives
  3976. one argument.  For a syntax error, the string is normally
  3977. `"syntax error"'.
  3978.  
  3979.    If you invoke the directive `%error-verbose' in the Bison
  3980. declarations section (*note The Bison Declarations Section: Bison
  3981. Declarations.), then Bison provides a more verbose and specific error
  3982. message string instead of just plain `"syntax error"'.
  3983.  
  3984.    The parser can detect one other kind of error: stack overflow.  This
  3985. happens when the input contains constructions that are very deeply
  3986. nested.  It isn't likely you will encounter this, since the Bison
  3987. parser extends its stack automatically up to a very large limit.  But
  3988. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  3989. except that the argument string is `"parser stack overflow"'.
  3990.  
  3991.    The following definition suffices in simple programs:
  3992.  
  3993.      void
  3994.      yyerror (char const *s)
  3995.      {
  3996.        fprintf (stderr, "%s\n", s);
  3997.      }
  3998.  
  3999.    After `yyerror' returns to `yyparse', the latter will attempt error
  4000. recovery if you have written suitable error recovery grammar rules
  4001. (*note Error Recovery::).  If recovery is impossible, `yyparse' will
  4002. immediately return 1.
  4003.  
  4004.    Obviously, in location tracking pure parsers, `yyerror' should have
  4005. an access to the current location.  This is indeed the case for the GLR
  4006. parsers, but not for the Yacc parser, for historical reasons.  I.e., if
  4007. `%locations %pure-parser' is passed then the prototypes for `yyerror'
  4008. are:
  4009.  
  4010.      void yyerror (char const *msg);                 /* Yacc parsers.  */
  4011.      void yyerror (YYLTYPE *locp, char const *msg);  /* GLR parsers.   */
  4012.  
  4013. The prototypes are only indications of how the code produced by Bison
  4014. uses `yyerror'.  Bison-generated code always ignores the returned
  4015. value, so `yyerror' can return any type, including `void'.  Also,
  4016. `yyerror' can be a variadic function; that is why the message is always
  4017. passed last.
  4018.  
  4019.    Traditionally `yyerror' returns an `int' that is always ignored, but
  4020. this is purely for historical reasons, and `void' is preferable since
  4021. it more accurately describes the return type for `yyerror'.
  4022.  
  4023.    The variable `yynerrs' contains the number of syntax errors
  4024. encountered so far.  Normally this variable is global; but if you
  4025. request a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.)
  4026. then it is a local variable which only the actions can access.
  4027.  
  4028. 
  4029. File: bison,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  4030.  
  4031. 4.4 Special Features for Use in Actions
  4032. =======================================
  4033.  
  4034. Here is a table of Bison constructs, variables and macros that are
  4035. useful in actions.
  4036.  
  4037.  -- Variable: $$
  4038.      Acts like a variable that contains the semantic value for the
  4039.      grouping made by the current rule.  *Note Actions::.
  4040.  
  4041.  -- Variable: $N
  4042.      Acts like a variable that contains the semantic value for the Nth
  4043.      component of the current rule.  *Note Actions::.
  4044.  
  4045.  -- Variable: $<TYPEALT>$
  4046.      Like `$$' but specifies alternative TYPEALT in the union specified
  4047.      by the `%union' declaration.  *Note Data Types of Values in
  4048.      Actions: Action Types.
  4049.  
  4050.  -- Variable: $<TYPEALT>N
  4051.      Like `$N' but specifies alternative TYPEALT in the union specified
  4052.      by the `%union' declaration.  *Note Data Types of Values in
  4053.      Actions: Action Types.
  4054.  
  4055.  -- Macro: YYABORT;
  4056.      Return immediately from `yyparse', indicating failure.  *Note The
  4057.      Parser Function `yyparse': Parser Function.
  4058.  
  4059.  -- Macro: YYACCEPT;
  4060.      Return immediately from `yyparse', indicating success.  *Note The
  4061.      Parser Function `yyparse': Parser Function.
  4062.  
  4063.  -- Macro: YYBACKUP (TOKEN, VALUE);
  4064.      Unshift a token.  This macro is allowed only for rules that reduce
  4065.      a single value, and only when there is no look-ahead token.  It is
  4066.      also disallowed in GLR parsers.  It installs a look-ahead token
  4067.      with token type TOKEN and semantic value VALUE; then it discards
  4068.      the value that was going to be reduced by this rule.
  4069.  
  4070.      If the macro is used when it is not valid, such as when there is a
  4071.      look-ahead token already, then it reports a syntax error with a
  4072.      message `cannot back up' and performs ordinary error recovery.
  4073.  
  4074.      In either case, the rest of the action is not executed.
  4075.  
  4076.  -- Macro: YYEMPTY
  4077.      Value stored in `yychar' when there is no look-ahead token.
  4078.  
  4079.  -- Macro: YYERROR;
  4080.      Cause an immediate syntax error.  This statement initiates error
  4081.      recovery just as if the parser itself had detected an error;
  4082.      however, it does not call `yyerror', and does not print any
  4083.      message.  If you want to print an error message, call `yyerror'
  4084.      explicitly before the `YYERROR;' statement.  *Note Error
  4085.      Recovery::.
  4086.  
  4087.  -- Macro: YYRECOVERING
  4088.      This macro stands for an expression that has the value 1 when the
  4089.      parser is recovering from a syntax error, and 0 the rest of the
  4090.      time.  *Note Error Recovery::.
  4091.  
  4092.  -- Variable: yychar
  4093.      Variable containing the current look-ahead token.  (In a pure
  4094.      parser, this is actually a local variable within `yyparse'.)  When
  4095.      there is no look-ahead token, the value `YYEMPTY' is stored in the
  4096.      variable.  *Note Look-Ahead Tokens: Look-Ahead.
  4097.  
  4098.  -- Macro: yyclearin;
  4099.      Discard the current look-ahead token.  This is useful primarily in
  4100.      error rules.  *Note Error Recovery::.
  4101.  
  4102.  -- Macro: yyerrok;
  4103.      Resume generating error messages immediately for subsequent syntax
  4104.      errors.  This is useful primarily in error rules.  *Note Error
  4105.      Recovery::.
  4106.  
  4107.  -- Value: @$
  4108.      Acts like a structure variable containing information on the
  4109.      textual position of the grouping made by the current rule.  *Note
  4110.      Tracking Locations: Locations.
  4111.  
  4112.  
  4113.  -- Value: @N
  4114.      Acts like a structure variable containing information on the
  4115.      textual position of the Nth component of the current rule.  *Note
  4116.      Tracking Locations: Locations.
  4117.  
  4118. 
  4119. File: bison,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  4120.  
  4121. 5 The Bison Parser Algorithm
  4122. ****************************
  4123.  
  4124. As Bison reads tokens, it pushes them onto a stack along with their
  4125. semantic values.  The stack is called the "parser stack".  Pushing a
  4126. token is traditionally called "shifting".
  4127.  
  4128.    For example, suppose the infix calculator has read `1 + 5 *', with a
  4129. `3' to come.  The stack will have four elements, one for each token
  4130. that was shifted.
  4131.  
  4132.    But the stack does not always have an element for each token read.
  4133. When the last N tokens and groupings shifted match the components of a
  4134. grammar rule, they can be combined according to that rule.  This is
  4135. called "reduction".  Those tokens and groupings are replaced on the
  4136. stack by a single grouping whose symbol is the result (left hand side)
  4137. of that rule.  Running the rule's action is part of the process of
  4138. reduction, because this is what computes the semantic value of the
  4139. resulting grouping.
  4140.  
  4141.    For example, if the infix calculator's parser stack contains this:
  4142.  
  4143.      1 + 5 * 3
  4144.  
  4145. and the next input token is a newline character, then the last three
  4146. elements can be reduced to 15 via the rule:
  4147.  
  4148.      expr: expr '*' expr;
  4149.  
  4150. Then the stack contains just these three elements:
  4151.  
  4152.      1 + 15
  4153.  
  4154. At this point, another reduction can be made, resulting in the single
  4155. value 16.  Then the newline token can be shifted.
  4156.  
  4157.    The parser tries, by shifts and reductions, to reduce the entire
  4158. input down to a single grouping whose symbol is the grammar's
  4159. start-symbol (*note Languages and Context-Free Grammars: Language and
  4160. Grammar.).
  4161.  
  4162.    This kind of parser is known in the literature as a bottom-up parser.
  4163.  
  4164. * Menu:
  4165.  
  4166. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  4167. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  4168. * Precedence::        Operator precedence works by resolving conflicts.
  4169. * Contextual Precedence::  When an operator's precedence depends on context.
  4170. * Parser States::     The parser is a finite-state-machine with stack.
  4171. * Reduce/Reduce::     When two rules are applicable in the same situation.
  4172. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  4173. * Generalized LR Parsing::  Parsing arbitrary context-free grammars.
  4174. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  4175.  
  4176. 
  4177. File: bison,  Node: Look-Ahead,  Next: Shift/Reduce,  Up: Algorithm
  4178.  
  4179. 5.1 Look-Ahead Tokens
  4180. =====================
  4181.  
  4182. The Bison parser does _not_ always reduce immediately as soon as the
  4183. last N tokens and groupings match a rule.  This is because such a
  4184. simple strategy is inadequate to handle most languages.  Instead, when a
  4185. reduction is possible, the parser sometimes "looks ahead" at the next
  4186. token in order to decide what to do.
  4187.  
  4188.    When a token is read, it is not immediately shifted; first it
  4189. becomes the "look-ahead token", which is not on the stack.  Now the
  4190. parser can perform one or more reductions of tokens and groupings on
  4191. the stack, while the look-ahead token remains off to the side.  When no
  4192. more reductions should take place, the look-ahead token is shifted onto
  4193. the stack.  This does not mean that all possible reductions have been
  4194. done; depending on the token type of the look-ahead token, some rules
  4195. may choose to delay their application.
  4196.  
  4197.    Here is a simple case where look-ahead is needed.  These three rules
  4198. define expressions which contain binary addition operators and postfix
  4199. unary factorial operators (`!'), and allow parentheses for grouping.
  4200.  
  4201.      expr:     term '+' expr
  4202.              | term
  4203.              ;
  4204.  
  4205.      term:     '(' expr ')'
  4206.              | term '!'
  4207.              | NUMBER
  4208.              ;
  4209.  
  4210.    Suppose that the tokens `1 + 2' have been read and shifted; what
  4211. should be done?  If the following token is `)', then the first three
  4212. tokens must be reduced to form an `expr'.  This is the only valid
  4213. course, because shifting the `)' would produce a sequence of symbols
  4214. `term ')'', and no rule allows this.
  4215.  
  4216.    If the following token is `!', then it must be shifted immediately so
  4217. that `2 !' can be reduced to make a `term'.  If instead the parser were
  4218. to reduce before shifting, `1 + 2' would become an `expr'.  It would
  4219. then be impossible to shift the `!' because doing so would produce on
  4220. the stack the sequence of symbols `expr '!''.  No rule allows that
  4221. sequence.
  4222.  
  4223.    The current look-ahead token is stored in the variable `yychar'.
  4224. *Note Special Features for Use in Actions: Action Features.
  4225.  
  4226. 
  4227. File: bison,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  4228.  
  4229. 5.2 Shift/Reduce Conflicts
  4230. ==========================
  4231.  
  4232. Suppose we are parsing a language which has if-then and if-then-else
  4233. statements, with a pair of rules like this:
  4234.  
  4235.      if_stmt:
  4236.                IF expr THEN stmt
  4237.              | IF expr THEN stmt ELSE stmt
  4238.              ;
  4239.  
  4240. Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  4241. specific keyword tokens.
  4242.  
  4243.    When the `ELSE' token is read and becomes the look-ahead token, the
  4244. contents of the stack (assuming the input is valid) are just right for
  4245. reduction by the first rule.  But it is also legitimate to shift the
  4246. `ELSE', because that would lead to eventual reduction by the second
  4247. rule.
  4248.  
  4249.    This situation, where either a shift or a reduction would be valid,
  4250. is called a "shift/reduce conflict".  Bison is designed to resolve
  4251. these conflicts by choosing to shift, unless otherwise directed by
  4252. operator precedence declarations.  To see the reason for this, let's
  4253. contrast it with the other alternative.
  4254.  
  4255.    Since the parser prefers to shift the `ELSE', the result is to attach
  4256. the else-clause to the innermost if-statement, making these two inputs
  4257. equivalent:
  4258.  
  4259.      if x then if y then win (); else lose;
  4260.  
  4261.      if x then do; if y then win (); else lose; end;
  4262.  
  4263.    But if the parser chose to reduce when possible rather than shift,
  4264. the result would be to attach the else-clause to the outermost
  4265. if-statement, making these two inputs equivalent:
  4266.  
  4267.      if x then if y then win (); else lose;
  4268.  
  4269.      if x then do; if y then win (); end; else lose;
  4270.  
  4271.    The conflict exists because the grammar as written is ambiguous:
  4272. either parsing of the simple nested if-statement is legitimate.  The
  4273. established convention is that these ambiguities are resolved by
  4274. attaching the else-clause to the innermost if-statement; this is what
  4275. Bison accomplishes by choosing to shift rather than reduce.  (It would
  4276. ideally be cleaner to write an unambiguous grammar, but that is very
  4277. hard to do in this case.)  This particular ambiguity was first
  4278. encountered in the specifications of Algol 60 and is called the
  4279. "dangling `else'" ambiguity.
  4280.  
  4281.    To avoid warnings from Bison about predictable, legitimate
  4282. shift/reduce conflicts, use the `%expect N' declaration.  There will be
  4283. no warning as long as the number of shift/reduce conflicts is exactly N.
  4284. *Note Suppressing Conflict Warnings: Expect Decl.
  4285.  
  4286.    The definition of `if_stmt' above is solely to blame for the
  4287. conflict, but the conflict does not actually appear without additional
  4288. rules.  Here is a complete Bison input file that actually manifests the
  4289. conflict:
  4290.  
  4291.      %token IF THEN ELSE variable
  4292.      %%
  4293.      stmt:     expr
  4294.              | if_stmt
  4295.              ;
  4296.  
  4297.      if_stmt:
  4298.                IF expr THEN stmt
  4299.              | IF expr THEN stmt ELSE stmt
  4300.              ;
  4301.  
  4302.      expr:     variable
  4303.              ;
  4304.  
  4305. 
  4306. File: bison,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  4307.  
  4308. 5.3 Operator Precedence
  4309. =======================
  4310.  
  4311. Another situation where shift/reduce conflicts appear is in arithmetic
  4312. expressions.  Here shifting is not always the preferred resolution; the
  4313. Bison declarations for operator precedence allow you to specify when to
  4314. shift and when to reduce.
  4315.  
  4316. * Menu:
  4317.  
  4318. * Why Precedence::    An example showing why precedence is needed.
  4319. * Using Precedence::  How to specify precedence in Bison grammars.
  4320. * Precedence Examples::  How these features are used in the previous example.
  4321. * How Precedence::    How they work.
  4322.  
  4323. 
  4324. File: bison,  Node: Why Precedence,  Next: Using Precedence,  Up: Precedence
  4325.  
  4326. 5.3.1 When Precedence is Needed
  4327. -------------------------------
  4328.  
  4329. Consider the following ambiguous grammar fragment (ambiguous because the
  4330. input `1 - 2 * 3' can be parsed in two different ways):
  4331.  
  4332.      expr:     expr '-' expr
  4333.              | expr '*' expr
  4334.              | expr '<' expr
  4335.              | '(' expr ')'
  4336.              ...
  4337.              ;
  4338.  
  4339. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  4340. reduce them via the rule for the subtraction operator?  It depends on
  4341. the next token.  Of course, if the next token is `)', we must reduce;
  4342. shifting is invalid because no single rule can reduce the token
  4343. sequence `- 2 )' or anything starting with that.  But if the next token
  4344. is `*' or `<', we have a choice: either shifting or reduction would
  4345. allow the parse to complete, but with different results.
  4346.  
  4347.    To decide which one Bison should do, we must consider the results.
  4348. If the next operator token OP is shifted, then it must be reduced first
  4349. in order to permit another opportunity to reduce the difference.  The
  4350. result is (in effect) `1 - (2 OP 3)'.  On the other hand, if the
  4351. subtraction is reduced before shifting OP, the result is
  4352. `(1 - 2) OP 3'.  Clearly, then, the choice of shift or reduce should
  4353. depend on the relative precedence of the operators `-' and OP: `*'
  4354. should be shifted first, but not `<'.
  4355.  
  4356.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  4357. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  4358. former, which is called "left association".  The latter alternative,
  4359. "right association", is desirable for assignment operators.  The choice
  4360. of left or right association is a matter of whether the parser chooses
  4361. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  4362. token is `-': shifting makes right-associativity.
  4363.  
  4364. 
  4365. File: bison,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  4366.  
  4367. 5.3.2 Specifying Operator Precedence
  4368. ------------------------------------
  4369.  
  4370. Bison allows you to specify these choices with the operator precedence
  4371. declarations `%left' and `%right'.  Each such declaration contains a
  4372. list of tokens, which are operators whose precedence and associativity
  4373. is being declared.  The `%left' declaration makes all those operators
  4374. left-associative and the `%right' declaration makes them
  4375. right-associative.  A third alternative is `%nonassoc', which declares
  4376. that it is a syntax error to find the same operator twice "in a row".
  4377.  
  4378.    The relative precedence of different operators is controlled by the
  4379. order in which they are declared.  The first `%left' or `%right'
  4380. declaration in the file declares the operators whose precedence is
  4381. lowest, the next such declaration declares the operators whose
  4382. precedence is a little higher, and so on.
  4383.  
  4384. 
  4385. File: bison,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  4386.  
  4387. 5.3.3 Precedence Examples
  4388. -------------------------
  4389.  
  4390. In our example, we would want the following declarations:
  4391.  
  4392.      %left '<'
  4393.      %left '-'
  4394.      %left '*'
  4395.  
  4396.    In a more complete example, which supports other operators as well,
  4397. we would declare them in groups of equal precedence.  For example,
  4398. `'+'' is declared with `'-'':
  4399.  
  4400.      %left '<' '>' '=' NE LE GE
  4401.      %left '+' '-'
  4402.      %left '*' '/'
  4403.  
  4404. (Here `NE' and so on stand for the operators for "not equal" and so on.
  4405. We assume that these tokens are more than one character long and
  4406. therefore are represented by names, not character literals.)
  4407.  
  4408. 
  4409. File: bison,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  4410.  
  4411. 5.3.4 How Precedence Works
  4412. --------------------------
  4413.  
  4414. The first effect of the precedence declarations is to assign precedence
  4415. levels to the terminal symbols declared.  The second effect is to assign
  4416. precedence levels to certain rules: each rule gets its precedence from
  4417. the last terminal symbol mentioned in the components.  (You can also
  4418. specify explicitly the precedence of a rule.  *Note Context-Dependent
  4419. Precedence: Contextual Precedence.)
  4420.  
  4421.    Finally, the resolution of conflicts works by comparing the
  4422. precedence of the rule being considered with that of the look-ahead
  4423. token.  If the token's precedence is higher, the choice is to shift.
  4424. If the rule's precedence is higher, the choice is to reduce.  If they
  4425. have equal precedence, the choice is made based on the associativity of
  4426. that precedence level.  The verbose output file made by `-v' (*note
  4427. Invoking Bison: Invocation.) says how each conflict was resolved.
  4428.  
  4429.    Not all rules and not all tokens have precedence.  If either the
  4430. rule or the look-ahead token has no precedence, then the default is to
  4431. shift.
  4432.  
  4433. 
  4434. File: bison,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  4435.  
  4436. 5.4 Context-Dependent Precedence
  4437. ================================
  4438.  
  4439. Often the precedence of an operator depends on the context.  This sounds
  4440. outlandish at first, but it is really very common.  For example, a minus
  4441. sign typically has a very high precedence as a unary operator, and a
  4442. somewhat lower precedence (lower than multiplication) as a binary
  4443. operator.
  4444.  
  4445.    The Bison precedence declarations, `%left', `%right' and
  4446. `%nonassoc', can only be used once for a given token; so a token has
  4447. only one precedence declared in this way.  For context-dependent
  4448. precedence, you need to use an additional mechanism: the `%prec'
  4449. modifier for rules.
  4450.  
  4451.    The `%prec' modifier declares the precedence of a particular rule by
  4452. specifying a terminal symbol whose precedence should be used for that
  4453. rule.  It's not necessary for that symbol to appear otherwise in the
  4454. rule.  The modifier's syntax is:
  4455.  
  4456.      %prec TERMINAL-SYMBOL
  4457.  
  4458. and it is written after the components of the rule.  Its effect is to
  4459. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  4460. precedence that would be deduced for it in the ordinary way.  The
  4461. altered rule precedence then affects how conflicts involving that rule
  4462. are resolved (*note Operator Precedence: Precedence.).
  4463.  
  4464.    Here is how `%prec' solves the problem of unary minus.  First,
  4465. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  4466. There are no tokens of this type, but the symbol serves to stand for its
  4467. precedence:
  4468.  
  4469.      ...
  4470.      %left '+' '-'
  4471.      %left '*'
  4472.      %left UMINUS
  4473.  
  4474.    Now the precedence of `UMINUS' can be used in specific rules:
  4475.  
  4476.      exp:    ...
  4477.              | exp '-' exp
  4478.              ...
  4479.              | '-' exp %prec UMINUS
  4480.  
  4481. 
  4482. File: bison,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  4483.  
  4484. 5.5 Parser States
  4485. =================
  4486.  
  4487. The function `yyparse' is implemented using a finite-state machine.
  4488. The values pushed on the parser stack are not simply token type codes;
  4489. they represent the entire sequence of terminal and nonterminal symbols
  4490. at or near the top of the stack.  The current state collects all the
  4491. information about previous input which is relevant to deciding what to
  4492. do next.
  4493.  
  4494.    Each time a look-ahead token is read, the current parser state
  4495. together with the type of look-ahead token are looked up in a table.
  4496. This table entry can say, "Shift the look-ahead token."  In this case,
  4497. it also specifies the new parser state, which is pushed onto the top of
  4498. the parser stack.  Or it can say, "Reduce using rule number N."  This
  4499. means that a certain number of tokens or groupings are taken off the
  4500. top of the stack, and replaced by one grouping.  In other words, that
  4501. number of states are popped from the stack, and one new state is pushed.
  4502.  
  4503.    There is one other alternative: the table can say that the
  4504. look-ahead token is erroneous in the current state.  This causes error
  4505. processing to begin (*note Error Recovery::).
  4506.  
  4507. 
  4508. File: bison,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  4509.  
  4510. 5.6 Reduce/Reduce Conflicts
  4511. ===========================
  4512.  
  4513. A reduce/reduce conflict occurs if there are two or more rules that
  4514. apply to the same sequence of input.  This usually indicates a serious
  4515. error in the grammar.
  4516.  
  4517.    For example, here is an erroneous attempt to define a sequence of
  4518. zero or more `word' groupings.
  4519.  
  4520.      sequence: /* empty */
  4521.                      { printf ("empty sequence\n"); }
  4522.              | maybeword
  4523.              | sequence word
  4524.                      { printf ("added word %s\n", $2); }
  4525.              ;
  4526.  
  4527.      maybeword: /* empty */
  4528.                      { printf ("empty maybeword\n"); }
  4529.              | word
  4530.                      { printf ("single word %s\n", $1); }
  4531.              ;
  4532.  
  4533. The error is an ambiguity: there is more than one way to parse a single
  4534. `word' into a `sequence'.  It could be reduced to a `maybeword' and
  4535. then into a `sequence' via the second rule.  Alternatively,
  4536. nothing-at-all could be reduced into a `sequence' via the first rule,
  4537. and this could be combined with the `word' using the third rule for
  4538. `sequence'.
  4539.  
  4540.    There is also more than one way to reduce nothing-at-all into a
  4541. `sequence'.  This can be done directly via the first rule, or
  4542. indirectly via `maybeword' and then the second rule.
  4543.  
  4544.    You might think that this is a distinction without a difference,
  4545. because it does not change whether any particular input is valid or
  4546. not.  But it does affect which actions are run.  One parsing order runs
  4547. the second rule's action; the other runs the first rule's action and
  4548. the third rule's action.  In this example, the output of the program
  4549. changes.
  4550.  
  4551.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  4552. that appears first in the grammar, but it is very risky to rely on
  4553. this.  Every reduce/reduce conflict must be studied and usually
  4554. eliminated.  Here is the proper way to define `sequence':
  4555.  
  4556.      sequence: /* empty */
  4557.                      { printf ("empty sequence\n"); }
  4558.              | sequence word
  4559.                      { printf ("added word %s\n", $2); }
  4560.              ;
  4561.  
  4562.    Here is another common error that yields a reduce/reduce conflict:
  4563.  
  4564.      sequence: /* empty */
  4565.              | sequence words
  4566.              | sequence redirects
  4567.              ;
  4568.  
  4569.      words:    /* empty */
  4570.              | words word
  4571.              ;
  4572.  
  4573.      redirects:/* empty */
  4574.              | redirects redirect
  4575.              ;
  4576.  
  4577. The intention here is to define a sequence which can contain either
  4578. `word' or `redirect' groupings.  The individual definitions of
  4579. `sequence', `words' and `redirects' are error-free, but the three
  4580. together make a subtle ambiguity: even an empty input can be parsed in
  4581. infinitely many ways!
  4582.  
  4583.    Consider: nothing-at-all could be a `words'.  Or it could be two
  4584. `words' in a row, or three, or any number.  It could equally well be a
  4585. `redirects', or two, or any number.  Or it could be a `words' followed
  4586. by three `redirects' and another `words'.  And so on.
  4587.  
  4588.    Here are two ways to correct these rules.  First, to make it a
  4589. single level of sequence:
  4590.  
  4591.      sequence: /* empty */
  4592.              | sequence word
  4593.              | sequence redirect
  4594.              ;
  4595.  
  4596.    Second, to prevent either a `words' or a `redirects' from being
  4597. empty:
  4598.  
  4599.      sequence: /* empty */
  4600.              | sequence words
  4601.              | sequence redirects
  4602.              ;
  4603.  
  4604.      words:    word
  4605.              | words word
  4606.              ;
  4607.  
  4608.      redirects:redirect
  4609.              | redirects redirect
  4610.              ;
  4611.  
  4612. 
  4613. File: bison,  Node: Mystery Conflicts,  Next: Generalized LR Parsing,  Prev: Reduce/Reduce,  Up: Algorithm
  4614.  
  4615. 5.7 Mysterious Reduce/Reduce Conflicts
  4616. ======================================
  4617.  
  4618. Sometimes reduce/reduce conflicts can occur that don't look warranted.
  4619. Here is an example:
  4620.  
  4621.      %token ID
  4622.  
  4623.      %%
  4624.      def:    param_spec return_spec ','
  4625.              ;
  4626.      param_spec:
  4627.                   type
  4628.              |    name_list ':' type
  4629.              ;
  4630.      return_spec:
  4631.                   type
  4632.              |    name ':' type
  4633.              ;
  4634.      type:        ID
  4635.              ;
  4636.      name:        ID
  4637.              ;
  4638.      name_list:
  4639.                   name
  4640.              |    name ',' name_list
  4641.              ;
  4642.  
  4643.    It would seem that this grammar can be parsed with only a single
  4644. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  4645. `name' if a comma or colon follows, or a `type' if another `ID'
  4646. follows.  In other words, this grammar is LR(1).
  4647.  
  4648.    However, Bison, like most parser generators, cannot actually handle
  4649. all LR(1) grammars.  In this grammar, two contexts, that after an `ID'
  4650. at the beginning of a `param_spec' and likewise at the beginning of a
  4651. `return_spec', are similar enough that Bison assumes they are the same.
  4652. They appear similar because the same set of rules would be active--the
  4653. rule for reducing to a `name' and that for reducing to a `type'.  Bison
  4654. is unable to determine at that stage of processing that the rules would
  4655. require different look-ahead tokens in the two contexts, so it makes a
  4656. single parser state for them both.  Combining the two contexts causes a
  4657. conflict later.  In parser terminology, this occurrence means that the
  4658. grammar is not LALR(1).
  4659.  
  4660.    In general, it is better to fix deficiencies than to document them.
  4661. But this particular deficiency is intrinsically hard to fix; parser
  4662. generators that can handle LR(1) grammars are hard to write and tend to
  4663. produce parsers that are very large.  In practice, Bison is more useful
  4664. as it is now.
  4665.  
  4666.    When the problem arises, you can often fix it by identifying the two
  4667. parser states that are being confused, and adding something to make them
  4668. look distinct.  In the above example, adding one rule to `return_spec'
  4669. as follows makes the problem go away:
  4670.  
  4671.      %token BOGUS
  4672.      ...
  4673.      %%
  4674.      ...
  4675.      return_spec:
  4676.                   type
  4677.              |    name ':' type
  4678.              /* This rule is never used.  */
  4679.              |    ID BOGUS
  4680.              ;
  4681.  
  4682.    This corrects the problem because it introduces the possibility of an
  4683. additional active rule in the context after the `ID' at the beginning of
  4684. `return_spec'.  This rule is not active in the corresponding context in
  4685. a `param_spec', so the two contexts receive distinct parser states.  As
  4686. long as the token `BOGUS' is never generated by `yylex', the added rule
  4687. cannot alter the way actual input is parsed.
  4688.  
  4689.    In this particular example, there is another way to solve the
  4690. problem: rewrite the rule for `return_spec' to use `ID' directly
  4691. instead of via `name'.  This also causes the two confusing contexts to
  4692. have different sets of active rules, because the one for `return_spec'
  4693. activates the altered rule for `return_spec' rather than the one for
  4694. `name'.
  4695.  
  4696.      param_spec:
  4697.                   type
  4698.              |    name_list ':' type
  4699.              ;
  4700.      return_spec:
  4701.                   type
  4702.              |    ID ':' type
  4703.              ;
  4704.  
  4705. 
  4706. File: bison,  Node: Generalized LR Parsing,  Next: Stack Overflow,  Prev: Mystery Conflicts,  Up: Algorithm
  4707.  
  4708. 5.8 Generalized LR (GLR) Parsing
  4709. ================================
  4710.  
  4711. Bison produces _deterministic_ parsers that choose uniquely when to
  4712. reduce and which reduction to apply based on a summary of the preceding
  4713. input and on one extra token of lookahead.  As a result, normal Bison
  4714. handles a proper subset of the family of context-free languages.
  4715. Ambiguous grammars, since they have strings with more than one possible
  4716. sequence of reductions cannot have deterministic parsers in this sense.
  4717. The same is true of languages that require more than one symbol of
  4718. lookahead, since the parser lacks the information necessary to make a
  4719. decision at the point it must be made in a shift-reduce parser.
  4720. Finally, as previously mentioned (*note Mystery Conflicts::), there are
  4721. languages where Bison's particular choice of how to summarize the input
  4722. seen so far loses necessary information.
  4723.  
  4724.    When you use the `%glr-parser' declaration in your grammar file,
  4725. Bison generates a parser that uses a different algorithm, called
  4726. Generalized LR (or GLR).  A Bison GLR parser uses the same basic
  4727. algorithm for parsing as an ordinary Bison parser, but behaves
  4728. differently in cases where there is a shift-reduce conflict that has not
  4729. been resolved by precedence rules (*note Precedence::) or a
  4730. reduce-reduce conflict.  When a GLR parser encounters such a situation,
  4731. it effectively _splits_ into a several parsers, one for each possible
  4732. shift or reduction.  These parsers then proceed as usual, consuming
  4733. tokens in lock-step.  Some of the stacks may encounter other conflicts
  4734. and split further, with the result that instead of a sequence of states,
  4735. a Bison GLR parsing stack is what is in effect a tree of states.
  4736.  
  4737.    In effect, each stack represents a guess as to what the proper parse
  4738. is.  Additional input may indicate that a guess was wrong, in which case
  4739. the appropriate stack silently disappears.  Otherwise, the semantics
  4740. actions generated in each stack are saved, rather than being executed
  4741. immediately.  When a stack disappears, its saved semantic actions never
  4742. get executed.  When a reduction causes two stacks to become equivalent,
  4743. their sets of semantic actions are both saved with the state that
  4744. results from the reduction.  We say that two stacks are equivalent when
  4745. they both represent the same sequence of states, and each pair of
  4746. corresponding states represents a grammar symbol that produces the same
  4747. segment of the input token stream.
  4748.  
  4749.    Whenever the parser makes a transition from having multiple states
  4750. to having one, it reverts to the normal LALR(1) parsing algorithm,
  4751. after resolving and executing the saved-up actions.  At this
  4752. transition, some of the states on the stack will have semantic values
  4753. that are sets (actually multisets) of possible actions.  The parser
  4754. tries to pick one of the actions by first finding one whose rule has
  4755. the highest dynamic precedence, as set by the `%dprec' declaration.
  4756. Otherwise, if the alternative actions are not ordered by precedence,
  4757. but there the same merging function is declared for both rules by the
  4758. `%merge' declaration, Bison resolves and evaluates both and then calls
  4759. the merge function on the result.  Otherwise, it reports an ambiguity.
  4760.  
  4761.    It is possible to use a data structure for the GLR parsing tree that
  4762. permits the processing of any LALR(1) grammar in linear time (in the
  4763. size of the input), any unambiguous (not necessarily LALR(1)) grammar in
  4764. quadratic worst-case time, and any general (possibly ambiguous)
  4765. context-free grammar in cubic worst-case time.  However, Bison currently
  4766. uses a simpler data structure that requires time proportional to the
  4767. length of the input times the maximum number of stacks required for any
  4768. prefix of the input.  Thus, really ambiguous or non-deterministic
  4769. grammars can require exponential time and space to process.  Such badly
  4770. behaving examples, however, are not generally of practical interest.
  4771. Usually, non-determinism in a grammar is local--the parser is "in
  4772. doubt" only for a few tokens at a time.  Therefore, the current data
  4773. structure should generally be adequate.  On LALR(1) portions of a
  4774. grammar, in particular, it is only slightly slower than with the default
  4775. Bison parser.
  4776.  
  4777. 
  4778. File: bison,  Node: Stack Overflow,  Prev: Generalized LR Parsing,  Up: Algorithm
  4779.  
  4780. 5.9 Stack Overflow, and How to Avoid It
  4781. =======================================
  4782.  
  4783. The Bison parser stack can overflow if too many tokens are shifted and
  4784. not reduced.  When this happens, the parser function `yyparse' returns
  4785. a nonzero value, pausing only to call `yyerror' to report the overflow.
  4786.  
  4787.    Because Bison parsers have growing stacks, hitting the upper limit
  4788. usually results from using a right recursion instead of a left
  4789. recursion, *Note Recursive Rules: Recursion.
  4790.  
  4791.    By defining the macro `YYMAXDEPTH', you can control how deep the
  4792. parser stack can become before a stack overflow occurs.  Define the
  4793. macro with a value that is an integer.  This value is the maximum number
  4794. of tokens that can be shifted (and not reduced) before overflow.  It
  4795. must be a constant expression whose value is known at compile time.
  4796.  
  4797.    The stack space allowed is not necessarily allocated.  If you
  4798. specify a large value for `YYMAXDEPTH', the parser actually allocates a
  4799. small stack at first, and then makes it bigger by stages as needed.
  4800. This increasing allocation happens automatically and silently.
  4801. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  4802. to save space for ordinary inputs that do not need much stack.
  4803.  
  4804.    The default value of `YYMAXDEPTH', if you do not define it, is 10000.
  4805.  
  4806.    You can control how much stack is allocated initially by defining the
  4807. macro `YYINITDEPTH'.  This value too must be a compile-time constant
  4808. integer.  The default is 200.
  4809.  
  4810.    Because of semantical differences between C and C++, the LALR(1)
  4811. parsers in C produced by Bison by compiled as C++ cannot grow.  In this
  4812. precise case (compiling a C parser as C++) you are suggested to grow
  4813. `YYINITDEPTH'.  In the near future, a C++ output output will be
  4814. provided which addresses this issue.
  4815.  
  4816. 
  4817. File: bison,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  4818.  
  4819. 6 Error Recovery
  4820. ****************
  4821.  
  4822. It is not usually acceptable to have a program terminate on a syntax
  4823. error.  For example, a compiler should recover sufficiently to parse the
  4824. rest of the input file and check it for errors; a calculator should
  4825. accept another expression.
  4826.  
  4827.    In a simple interactive command parser where each input is one line,
  4828. it may be sufficient to allow `yyparse' to return 1 on error and have
  4829. the caller ignore the rest of the input line when that happens (and
  4830. then call `yyparse' again).  But this is inadequate for a compiler,
  4831. because it forgets all the syntactic context leading up to the error.
  4832. A syntax error deep within a function in the compiler input should not
  4833. cause the compiler to treat the following line like the beginning of a
  4834. source file.
  4835.  
  4836.    You can define how to recover from a syntax error by writing rules to
  4837. recognize the special token `error'.  This is a terminal symbol that is
  4838. always defined (you need not declare it) and reserved for error
  4839. handling.  The Bison parser generates an `error' token whenever a
  4840. syntax error happens; if you have provided a rule to recognize this
  4841. token in the current context, the parse can continue.
  4842.  
  4843.    For example:
  4844.  
  4845.      stmnts:  /* empty string */
  4846.              | stmnts '\n'
  4847.              | stmnts exp '\n'
  4848.              | stmnts error '\n'
  4849.  
  4850.    The fourth rule in this example says that an error followed by a
  4851. newline makes a valid addition to any `stmnts'.
  4852.  
  4853.    What happens if a syntax error occurs in the middle of an `exp'?  The
  4854. error recovery rule, interpreted strictly, applies to the precise
  4855. sequence of a `stmnts', an `error' and a newline.  If an error occurs in
  4856. the middle of an `exp', there will probably be some additional tokens
  4857. and subexpressions on the stack after the last `stmnts', and there will
  4858. be tokens to read before the next newline.  So the rule is not
  4859. applicable in the ordinary way.
  4860.  
  4861.    But Bison can force the situation to fit the rule, by discarding
  4862. part of the semantic context and part of the input.  First it discards
  4863. states and objects from the stack until it gets back to a state in
  4864. which the `error' token is acceptable.  (This means that the
  4865. subexpressions already parsed are discarded, back to the last complete
  4866. `stmnts'.)  At this point the `error' token can be shifted.  Then, if
  4867. the old look-ahead token is not acceptable to be shifted next, the
  4868. parser reads tokens and discards them until it finds a token which is
  4869. acceptable.  In this example, Bison reads and discards input until the
  4870. next newline so that the fourth rule can apply.  Note that discarded
  4871. symbols are possible sources of memory leaks, see *Note Freeing
  4872. Discarded Symbols: Destructor Decl, for a means to reclaim this memory.
  4873.  
  4874.    The choice of error rules in the grammar is a choice of strategies
  4875. for error recovery.  A simple and useful strategy is simply to skip the
  4876. rest of the current input line or current statement if an error is
  4877. detected:
  4878.  
  4879.      stmnt: error ';'  /* On error, skip until ';' is read.  */
  4880.  
  4881.    It is also useful to recover to the matching close-delimiter of an
  4882. opening-delimiter that has already been parsed.  Otherwise the
  4883. close-delimiter will probably appear to be unmatched, and generate
  4884. another, spurious error message:
  4885.  
  4886.      primary:  '(' expr ')'
  4887.              | '(' error ')'
  4888.              ...
  4889.              ;
  4890.  
  4891.    Error recovery strategies are necessarily guesses.  When they guess
  4892. wrong, one syntax error often leads to another.  In the above example,
  4893. the error recovery rule guesses that an error is due to bad input
  4894. within one `stmnt'.  Suppose that instead a spurious semicolon is
  4895. inserted in the middle of a valid `stmnt'.  After the error recovery
  4896. rule recovers from the first error, another syntax error will be found
  4897. straightaway, since the text following the spurious semicolon is also
  4898. an invalid `stmnt'.
  4899.  
  4900.    To prevent an outpouring of error messages, the parser will output
  4901. no error message for another syntax error that happens shortly after
  4902. the first; only after three consecutive input tokens have been
  4903. successfully shifted will error messages resume.
  4904.  
  4905.    Note that rules which accept the `error' token may have actions, just
  4906. as any other rules can.
  4907.  
  4908.    You can make error messages resume immediately by using the macro
  4909. `yyerrok' in an action.  If you do this in the error rule's action, no
  4910. error messages will be suppressed.  This macro requires no arguments;
  4911. `yyerrok;' is a valid C statement.
  4912.  
  4913.    The previous look-ahead token is reanalyzed immediately after an
  4914. error.  If this is unacceptable, then the macro `yyclearin' may be used
  4915. to clear this token.  Write the statement `yyclearin;' in the error
  4916. rule's action.
  4917.  
  4918.    For example, suppose that on a syntax error, an error handling
  4919. routine is called that advances the input stream to some point where
  4920. parsing should once again commence.  The next symbol returned by the
  4921. lexical scanner is probably correct.  The previous look-ahead token
  4922. ought to be discarded with `yyclearin;'.
  4923.  
  4924.    The macro `YYRECOVERING' stands for an expression that has the value
  4925. 1 when the parser is recovering from a syntax error, and 0 the rest of
  4926. the time.  A value of 1 indicates that error messages are currently
  4927. suppressed for new syntax errors.
  4928.  
  4929. 
  4930. File: bison,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  4931.  
  4932. 7 Handling Context Dependencies
  4933. *******************************
  4934.  
  4935. The Bison paradigm is to parse tokens first, then group them into larger
  4936. syntactic units.  In many languages, the meaning of a token is affected
  4937. by its context.  Although this violates the Bison paradigm, certain
  4938. techniques (known as "kludges") may enable you to write Bison parsers
  4939. for such languages.
  4940.  
  4941. * Menu:
  4942.  
  4943. * Semantic Tokens::   Token parsing can depend on the semantic context.
  4944. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  4945. * Tie-in Recovery::   Lexical tie-ins have implications for how
  4946.                         error recovery rules must be written.
  4947.  
  4948.    (Actually, "kludge" means any technique that gets its job done but is
  4949. neither clean nor robust.)
  4950.  
  4951. 
  4952. File: bison,  Node: Semantic Tokens,  Next: Lexical Tie-ins,  Up: Context Dependency
  4953.  
  4954. 7.1 Semantic Info in Token Types
  4955. ================================
  4956.  
  4957. The C language has a context dependency: the way an identifier is used
  4958. depends on what its current meaning is.  For example, consider this:
  4959.  
  4960.      foo (x);
  4961.  
  4962.    This looks like a function call statement, but if `foo' is a typedef
  4963. name, then this is actually a declaration of `x'.  How can a Bison
  4964. parser for C decide how to parse this input?
  4965.  
  4966.    The method used in GNU C is to have two different token types,
  4967. `IDENTIFIER' and `TYPENAME'.  When `yylex' finds an identifier, it
  4968. looks up the current declaration of the identifier in order to decide
  4969. which token type to return: `TYPENAME' if the identifier is declared as
  4970. a typedef, `IDENTIFIER' otherwise.
  4971.  
  4972.    The grammar rules can then express the context dependency by the
  4973. choice of token type to recognize.  `IDENTIFIER' is accepted as an
  4974. expression, but `TYPENAME' is not.  `TYPENAME' can start a declaration,
  4975. but `IDENTIFIER' cannot.  In contexts where the meaning of the
  4976. identifier is _not_ significant, such as in declarations that can
  4977. shadow a typedef name, either `TYPENAME' or `IDENTIFIER' is
  4978. accepted--there is one rule for each of the two token types.
  4979.  
  4980.    This technique is simple to use if the decision of which kinds of
  4981. identifiers to allow is made at a place close to where the identifier is
  4982. parsed.  But in C this is not always so: C allows a declaration to
  4983. redeclare a typedef name provided an explicit type has been specified
  4984. earlier:
  4985.  
  4986.      typedef int foo, bar, lose;
  4987.      static foo (bar);        /* redeclare `bar' as static variable */
  4988.      static int foo (lose);   /* redeclare `foo' as function */
  4989.  
  4990.    Unfortunately, the name being declared is separated from the
  4991. declaration construct itself by a complicated syntactic structure--the
  4992. "declarator".
  4993.  
  4994.    As a result, part of the Bison parser for C needs to be duplicated,
  4995. with all the nonterminal names changed: once for parsing a declaration
  4996. in which a typedef name can be redefined, and once for parsing a
  4997. declaration in which that can't be done.  Here is a part of the
  4998. duplication, with actions omitted for brevity:
  4999.  
  5000.      initdcl:
  5001.                declarator maybeasm '='
  5002.                init
  5003.              | declarator maybeasm
  5004.              ;
  5005.  
  5006.      notype_initdcl:
  5007.                notype_declarator maybeasm '='
  5008.                init
  5009.              | notype_declarator maybeasm
  5010.              ;
  5011.  
  5012. Here `initdcl' can redeclare a typedef name, but `notype_initdcl'
  5013. cannot.  The distinction between `declarator' and `notype_declarator'
  5014. is the same sort of thing.
  5015.  
  5016.    There is some similarity between this technique and a lexical tie-in
  5017. (described next), in that information which alters the lexical analysis
  5018. is changed during parsing by other parts of the program.  The
  5019. difference is here the information is global, and is used for other
  5020. purposes in the program.  A true lexical tie-in has a special-purpose
  5021. flag controlled by the syntactic context.
  5022.  
  5023. 
  5024. File: bison,  Node: Lexical Tie-ins,  Next: Tie-in Recovery,  Prev: Semantic Tokens,  Up: Context Dependency
  5025.  
  5026. 7.2 Lexical Tie-ins
  5027. ===================
  5028.  
  5029. One way to handle context-dependency is the "lexical tie-in": a flag
  5030. which is set by Bison actions, whose purpose is to alter the way tokens
  5031. are parsed.
  5032.  
  5033.    For example, suppose we have a language vaguely like C, but with a
  5034. special construct `hex (HEX-EXPR)'.  After the keyword `hex' comes an
  5035. expression in parentheses in which all integers are hexadecimal.  In
  5036. particular, the token `a1b' must be treated as an integer rather than
  5037. as an identifier if it appears in that context.  Here is how you can do
  5038. it:
  5039.  
  5040.      %{
  5041.        int hexflag;
  5042.        int yylex (void);
  5043.        void yyerror (char const *);
  5044.      %}
  5045.      %%
  5046.      ...
  5047.      expr:   IDENTIFIER
  5048.              | constant
  5049.              | HEX '('
  5050.                      { hexflag = 1; }
  5051.                expr ')'
  5052.                      { hexflag = 0;
  5053.                         $$ = $4; }
  5054.              | expr '+' expr
  5055.                      { $$ = make_sum ($1, $3); }
  5056.              ...
  5057.              ;
  5058.  
  5059.      constant:
  5060.                INTEGER
  5061.              | STRING
  5062.              ;
  5063.  
  5064. Here we assume that `yylex' looks at the value of `hexflag'; when it is
  5065. nonzero, all integers are parsed in hexadecimal, and tokens starting
  5066. with letters are parsed as integers if possible.
  5067.  
  5068.    The declaration of `hexflag' shown in the prologue of the parser file
  5069. is needed to make it accessible to the actions (*note The Prologue:
  5070. Prologue.).  You must also write the code in `yylex' to obey the flag.
  5071.  
  5072. 
  5073. File: bison,  Node: Tie-in Recovery,  Prev: Lexical Tie-ins,  Up: Context Dependency
  5074.  
  5075. 7.3 Lexical Tie-ins and Error Recovery
  5076. ======================================
  5077.  
  5078. Lexical tie-ins make strict demands on any error recovery rules you
  5079. have.  *Note Error Recovery::.
  5080.  
  5081.    The reason for this is that the purpose of an error recovery rule is
  5082. to abort the parsing of one construct and resume in some larger
  5083. construct.  For example, in C-like languages, a typical error recovery
  5084. rule is to skip tokens until the next semicolon, and then start a new
  5085. statement, like this:
  5086.  
  5087.      stmt:   expr ';'
  5088.              | IF '(' expr ')' stmt { ... }
  5089.              ...
  5090.              error ';'
  5091.                      { hexflag = 0; }
  5092.              ;
  5093.  
  5094.    If there is a syntax error in the middle of a `hex (EXPR)'
  5095. construct, this error rule will apply, and then the action for the
  5096. completed `hex (EXPR)' will never run.  So `hexflag' would remain set
  5097. for the entire rest of the input, or until the next `hex' keyword,
  5098. causing identifiers to be misinterpreted as integers.
  5099.  
  5100.    To avoid this problem the error recovery rule itself clears
  5101. `hexflag'.
  5102.  
  5103.    There may also be an error recovery rule that works within
  5104. expressions.  For example, there could be a rule which applies within
  5105. parentheses and skips to the close-parenthesis:
  5106.  
  5107.      expr:   ...
  5108.              | '(' expr ')'
  5109.                      { $$ = $2; }
  5110.              | '(' error ')'
  5111.              ...
  5112.  
  5113.    If this rule acts within the `hex' construct, it is not going to
  5114. abort that construct (since it applies to an inner level of parentheses
  5115. within the construct).  Therefore, it should not clear the flag: the
  5116. rest of the `hex' construct should be parsed with the flag still in
  5117. effect.
  5118.  
  5119.    What if there is an error recovery rule which might abort out of the
  5120. `hex' construct or might not, depending on circumstances?  There is no
  5121. way you can write the action to determine whether a `hex' construct is
  5122. being aborted or not.  So if you are using a lexical tie-in, you had
  5123. better make sure your error recovery rules are not of this kind.  Each
  5124. rule must be such that you can be sure that it always will, or always
  5125. won't, have to clear the flag.
  5126.  
  5127. 
  5128. File: bison,  Node: Debugging,  Next: Invocation,  Prev: Context Dependency,  Up: Top
  5129.  
  5130. 8 Debugging Your Parser
  5131. ***********************
  5132.  
  5133. Developing a parser can be a challenge, especially if you don't
  5134. understand the algorithm (*note The Bison Parser Algorithm:
  5135. Algorithm.).  Even so, sometimes a detailed description of the automaton
  5136. can help (*note Understanding Your Parser: Understanding.), or tracing
  5137. the execution of the parser can give some insight on why it behaves
  5138. improperly (*note Tracing Your Parser: Tracing.).
  5139.  
  5140. * Menu:
  5141.  
  5142. * Understanding::     Understanding the structure of your parser.
  5143. * Tracing::           Tracing the execution of your parser.
  5144.  
  5145. 
  5146. File: bison,  Node: Understanding,  Next: Tracing,  Up: Debugging
  5147.  
  5148. 8.1 Understanding Your Parser
  5149. =============================
  5150.  
  5151. As documented elsewhere (*note The Bison Parser Algorithm: Algorithm.)
  5152. Bison parsers are "shift/reduce automata".  In some cases (much more
  5153. frequent than one would hope), looking at this automaton is required to
  5154. tune or simply fix a parser.  Bison provides two different
  5155. representation of it, either textually or graphically (as a VCG file).
  5156.  
  5157.    The textual file is generated when the options `--report' or
  5158. `--verbose' are specified, see *Note Invoking Bison: Invocation.  Its
  5159. name is made by removing `.tab.c' or `.c' from the parser output file
  5160. name, and adding `.output' instead.  Therefore, if the input file is
  5161. `foo.y', then the parser file is called `foo.tab.c' by default.  As a
  5162. consequence, the verbose output file is called `foo.output'.
  5163.  
  5164.    The following grammar file, `calc.y', will be used in the sequel:
  5165.  
  5166.      %token NUM STR
  5167.      %left '+' '-'
  5168.      %left '*'
  5169.      %%
  5170.      exp: exp '+' exp
  5171.         | exp '-' exp
  5172.         | exp '*' exp
  5173.         | exp '/' exp
  5174.         | NUM
  5175.         ;
  5176.      useless: STR;
  5177.      %%
  5178.  
  5179.    `bison' reports:
  5180.  
  5181.      calc.y: warning: 1 useless nonterminal and 1 useless rule
  5182.      calc.y:11.1-7: warning: useless nonterminal: useless
  5183.      calc.y:11.10-12: warning: useless rule: useless: STR
  5184.      calc.y: conflicts: 7 shift/reduce
  5185.  
  5186.    When given `--report=state', in addition to `calc.tab.c', it creates
  5187. a file `calc.output' with contents detailed below.  The order of the
  5188. output and the exact presentation might vary, but the interpretation is
  5189. the same.
  5190.  
  5191.    The first section includes details on conflicts that were solved
  5192. thanks to precedence and/or associativity:
  5193.  
  5194.      Conflict in state 8 between rule 2 and token '+' resolved as reduce.
  5195.      Conflict in state 8 between rule 2 and token '-' resolved as reduce.
  5196.      Conflict in state 8 between rule 2 and token '*' resolved as shift.
  5197. ...
  5198.  
  5199.  
  5200. The next section lists states that still have conflicts.
  5201.  
  5202.      State 8 conflicts: 1 shift/reduce
  5203.      State 9 conflicts: 1 shift/reduce
  5204.      State 10 conflicts: 1 shift/reduce
  5205.      State 11 conflicts: 4 shift/reduce
  5206.  
  5207. The next section reports useless tokens, nonterminal and rules.  Useless
  5208. nonterminals and rules are removed in order to produce a smaller parser,
  5209. but useless tokens are preserved, since they might be used by the
  5210. scanner (note the difference between "useless" and "not used" below):
  5211.  
  5212.      Useless nonterminals:
  5213.         useless
  5214.  
  5215.      Terminals which are not used:
  5216.         STR
  5217.  
  5218.      Useless rules:
  5219.      #6     useless: STR;
  5220.  
  5221. The next section reproduces the exact grammar that Bison used:
  5222.  
  5223.      Grammar
  5224.  
  5225.        Number, Line, Rule
  5226.          0   5 $accept -> exp $end
  5227.          1   5 exp -> exp '+' exp
  5228.          2   6 exp -> exp '-' exp
  5229.          3   7 exp -> exp '*' exp
  5230.          4   8 exp -> exp '/' exp
  5231.          5   9 exp -> NUM
  5232.  
  5233. and reports the uses of the symbols:
  5234.  
  5235.      Terminals, with rules where they appear
  5236.  
  5237.      $end (0) 0
  5238.      '*' (42) 3
  5239.      '+' (43) 1
  5240.      '-' (45) 2
  5241.      '/' (47) 4
  5242.      error (256)
  5243.      NUM (258) 5
  5244.  
  5245.      Nonterminals, with rules where they appear
  5246.  
  5247.      $accept (8)
  5248.          on left: 0
  5249.      exp (9)
  5250.          on left: 1 2 3 4 5, on right: 0 1 2 3 4
  5251.  
  5252. Bison then proceeds onto the automaton itself, describing each state
  5253. with it set of "items", also known as "pointed rules".  Each item is a
  5254. production rule together with a point (marked by `.') that the input
  5255. cursor.
  5256.  
  5257.      state 0
  5258.  
  5259.          $accept  ->  . exp $   (rule 0)
  5260.  
  5261.          NUM         shift, and go to state 1
  5262.  
  5263.          exp         go to state 2
  5264.  
  5265.    This reads as follows: "state 0 corresponds to being at the very
  5266. beginning of the parsing, in the initial rule, right before the start
  5267. symbol (here, `exp').  When the parser returns to this state right
  5268. after having reduced a rule that produced an `exp', the control flow
  5269. jumps to state 2.  If there is no such transition on a nonterminal
  5270. symbol, and the lookahead is a `NUM', then this token is shifted on the
  5271. parse stack, and the control flow jumps to state 1.  Any other
  5272. lookahead triggers a syntax error."
  5273.  
  5274.    Even though the only active rule in state 0 seems to be rule 0, the
  5275. report lists `NUM' as a lookahead symbol because `NUM' can be at the
  5276. beginning of any rule deriving an `exp'.  By default Bison reports the
  5277. so-called "core" or "kernel" of the item set, but if you want to see
  5278. more detail you can invoke `bison' with `--report=itemset' to list all
  5279. the items, include those that can be derived:
  5280.  
  5281.      state 0
  5282.  
  5283.          $accept  ->  . exp $   (rule 0)
  5284.          exp  ->  . exp '+' exp   (rule 1)
  5285.          exp  ->  . exp '-' exp   (rule 2)
  5286.          exp  ->  . exp '*' exp   (rule 3)
  5287.          exp  ->  . exp '/' exp   (rule 4)
  5288.          exp  ->  . NUM   (rule 5)
  5289.  
  5290.          NUM         shift, and go to state 1
  5291.  
  5292.          exp         go to state 2
  5293.  
  5294. In the state 1...
  5295.  
  5296.      state 1
  5297.  
  5298.          exp  ->  NUM .   (rule 5)
  5299.  
  5300.          $default    reduce using rule 5 (exp)
  5301.  
  5302. the rule 5, `exp: NUM;', is completed.  Whatever the lookahead
  5303. (`$default'), the parser will reduce it.  If it was coming from state
  5304. 0, then, after this reduction it will return to state 0, and will jump
  5305. to state 2 (`exp: go to state 2').
  5306.  
  5307.      state 2
  5308.  
  5309.          $accept  ->  exp . $   (rule 0)
  5310.          exp  ->  exp . '+' exp   (rule 1)
  5311.          exp  ->  exp . '-' exp   (rule 2)
  5312.          exp  ->  exp . '*' exp   (rule 3)
  5313.          exp  ->  exp . '/' exp   (rule 4)
  5314.  
  5315.          $           shift, and go to state 3
  5316.          '+'         shift, and go to state 4
  5317.          '-'         shift, and go to state 5
  5318.          '*'         shift, and go to state 6
  5319.          '/'         shift, and go to state 7
  5320.  
  5321. In state 2, the automaton can only shift a symbol.  For instance,
  5322. because of the item `exp -> exp . '+' exp', if the lookahead if `+', it
  5323. will be shifted on the parse stack, and the automaton control will jump
  5324. to state 4, corresponding to the item `exp -> exp '+' . exp'.  Since
  5325. there is no default action, any other token than those listed above
  5326. will trigger a syntax error.
  5327.  
  5328.    The state 3 is named the "final state", or the "accepting state":
  5329.  
  5330.      state 3
  5331.  
  5332.          $accept  ->  exp $ .   (rule 0)
  5333.  
  5334.          $default    accept
  5335.  
  5336. the initial rule is completed (the start symbol and the end of input
  5337. were read), the parsing exits successfully.
  5338.  
  5339.    The interpretation of states 4 to 7 is straightforward, and is left
  5340. to the reader.
  5341.  
  5342.      state 4
  5343.  
  5344.          exp  ->  exp '+' . exp   (rule 1)
  5345.  
  5346.          NUM         shift, and go to state 1
  5347.  
  5348.          exp         go to state 8
  5349.  
  5350.      state 5
  5351.  
  5352.          exp  ->  exp '-' . exp   (rule 2)
  5353.  
  5354.          NUM         shift, and go to state 1
  5355.  
  5356.          exp         go to state 9
  5357.  
  5358.      state 6
  5359.  
  5360.          exp  ->  exp '*' . exp   (rule 3)
  5361.  
  5362.          NUM         shift, and go to state 1
  5363.  
  5364.          exp         go to state 10
  5365.  
  5366.      state 7
  5367.  
  5368.          exp  ->  exp '/' . exp   (rule 4)
  5369.  
  5370.          NUM         shift, and go to state 1
  5371.  
  5372.          exp         go to state 11
  5373.  
  5374.    As was announced in beginning of the report, `State 8 conflicts: 1
  5375. shift/reduce':
  5376.  
  5377.      state 8
  5378.  
  5379.          exp  ->  exp . '+' exp   (rule 1)
  5380.          exp  ->  exp '+' exp .   (rule 1)
  5381.          exp  ->  exp . '-' exp   (rule 2)
  5382.          exp  ->  exp . '*' exp   (rule 3)
  5383.          exp  ->  exp . '/' exp   (rule 4)
  5384.  
  5385.          '*'         shift, and go to state 6
  5386.          '/'         shift, and go to state 7
  5387.  
  5388.          '/'         [reduce using rule 1 (exp)]
  5389.          $default    reduce using rule 1 (exp)
  5390.  
  5391.    Indeed, there are two actions associated to the lookahead `/':
  5392. either shifting (and going to state 7), or reducing rule 1.  The
  5393. conflict means that either the grammar is ambiguous, or the parser lacks
  5394. information to make the right decision.  Indeed the grammar is
  5395. ambiguous, as, since we did not specify the precedence of `/', the
  5396. sentence `NUM + NUM / NUM' can be parsed as `NUM + (NUM / NUM)', which
  5397. corresponds to shifting `/', or as `(NUM + NUM) / NUM', which
  5398. corresponds to reducing rule 1.
  5399.  
  5400.    Because in LALR(1) parsing a single decision can be made, Bison
  5401. arbitrarily chose to disable the reduction, see *Note Shift/Reduce
  5402. Conflicts: Shift/Reduce.  Discarded actions are reported in between
  5403. square brackets.
  5404.  
  5405.    Note that all the previous states had a single possible action:
  5406. either shifting the next token and going to the corresponding state, or
  5407. reducing a single rule.  In the other cases, i.e., when shifting _and_
  5408. reducing is possible or when _several_ reductions are possible, the
  5409. lookahead is required to select the action.  State 8 is one such state:
  5410. if the lookahead is `*' or `/' then the action is shifting, otherwise
  5411. the action is reducing rule 1.  In other words, the first two items,
  5412. corresponding to rule 1, are not eligible when the lookahead is `*',
  5413. since we specified that `*' has higher precedence that `+'.  More
  5414. generally, some items are eligible only with some set of possible
  5415. lookaheads.  When run with `--report=lookahead', Bison specifies these
  5416. lookaheads:
  5417.  
  5418.      state 8
  5419.  
  5420.          exp  ->  exp . '+' exp  [$, '+', '-', '/']   (rule 1)
  5421.          exp  ->  exp '+' exp .  [$, '+', '-', '/']   (rule 1)
  5422.          exp  ->  exp . '-' exp   (rule 2)
  5423.          exp  ->  exp . '*' exp   (rule 3)
  5424.          exp  ->  exp . '/' exp   (rule 4)
  5425.  
  5426.          '*'         shift, and go to state 6
  5427.          '/'         shift, and go to state 7
  5428.  
  5429.          '/'         [reduce using rule 1 (exp)]
  5430.          $default    reduce using rule 1 (exp)
  5431.  
  5432.    The remaining states are similar:
  5433.  
  5434.      state 9
  5435.  
  5436.          exp  ->  exp . '+' exp   (rule 1)
  5437.          exp  ->  exp . '-' exp   (rule 2)
  5438.          exp  ->  exp '-' exp .   (rule 2)
  5439.          exp  ->  exp . '*' exp   (rule 3)
  5440.          exp  ->  exp . '/' exp   (rule 4)
  5441.  
  5442.          '*'         shift, and go to state 6
  5443.          '/'         shift, and go to state 7
  5444.  
  5445.          '/'         [reduce using rule 2 (exp)]
  5446.          $default    reduce using rule 2 (exp)
  5447.  
  5448.      state 10
  5449.  
  5450.          exp  ->  exp . '+' exp   (rule 1)
  5451.          exp  ->  exp . '-' exp   (rule 2)
  5452.          exp  ->  exp . '*' exp   (rule 3)
  5453.          exp  ->  exp '*' exp .   (rule 3)
  5454.          exp  ->  exp . '/' exp   (rule 4)
  5455.  
  5456.          '/'         shift, and go to state 7
  5457.  
  5458.          '/'         [reduce using rule 3 (exp)]
  5459.          $default    reduce using rule 3 (exp)
  5460.  
  5461.      state 11
  5462.  
  5463.          exp  ->  exp . '+' exp   (rule 1)
  5464.          exp  ->  exp . '-' exp   (rule 2)
  5465.          exp  ->  exp . '*' exp   (rule 3)
  5466.          exp  ->  exp . '/' exp   (rule 4)
  5467.          exp  ->  exp '/' exp .   (rule 4)
  5468.  
  5469.          '+'         shift, and go to state 4
  5470.          '-'         shift, and go to state 5
  5471.          '*'         shift, and go to state 6
  5472.          '/'         shift, and go to state 7
  5473.  
  5474.          '+'         [reduce using rule 4 (exp)]
  5475.          '-'         [reduce using rule 4 (exp)]
  5476.          '*'         [reduce using rule 4 (exp)]
  5477.          '/'         [reduce using rule 4 (exp)]
  5478.          $default    reduce using rule 4 (exp)
  5479.  
  5480. Observe that state 11 contains conflicts due to the lack of precedence
  5481. of `/' wrt `+', `-', and `*', but also because the associativity of `/'
  5482. is not specified.
  5483.  
  5484. 
  5485. File: bison,  Node: Tracing,  Prev: Understanding,  Up: Debugging
  5486.  
  5487. 8.2 Tracing Your Parser
  5488. =======================
  5489.  
  5490. If a Bison grammar compiles properly but doesn't do what you want when
  5491. it runs, the `yydebug' parser-trace feature can help you figure out why.
  5492.  
  5493.    There are several means to enable compilation of trace facilities:
  5494.  
  5495. the macro `YYDEBUG'
  5496.      Define the macro `YYDEBUG' to a nonzero value when you compile the
  5497.      parser.  This is compliant with POSIX Yacc.  You could use
  5498.      `-DYYDEBUG=1' as a compiler option or you could put `#define
  5499.      YYDEBUG 1' in the prologue of the grammar file (*note The
  5500.      Prologue: Prologue.).
  5501.  
  5502. the option `-t', `--debug'
  5503.      Use the `-t' option when you run Bison (*note Invoking Bison:
  5504.      Invocation.).  This is POSIX compliant too.
  5505.  
  5506. the directive `%debug'
  5507.      Add the `%debug' directive (*note Bison Declaration Summary: Decl
  5508.      Summary.).  This is a Bison extension, which will prove useful
  5509.      when Bison will output parsers for languages that don't use a
  5510.      preprocessor.  Unless POSIX and Yacc portability matter to you,
  5511.      this is the preferred solution.
  5512.  
  5513.    We suggest that you always enable the debug option so that debugging
  5514. is always possible.
  5515.  
  5516.    The trace facility outputs messages with macro calls of the form
  5517. `YYFPRINTF (stderr, FORMAT, ARGS)' where FORMAT and ARGS are the usual
  5518. `printf' format and arguments.  If you define `YYDEBUG' to a nonzero
  5519. value but do not define `YYFPRINTF', `<stdio.h>' is automatically
  5520. included and `YYPRINTF' is defined to `fprintf'.
  5521.  
  5522.    Once you have compiled the program with trace facilities, the way to
  5523. request a trace is to store a nonzero value in the variable `yydebug'.
  5524. You can do this by making the C code do it (in `main', perhaps), or you
  5525. can alter the value with a C debugger.
  5526.  
  5527.    Each step taken by the parser when `yydebug' is nonzero produces a
  5528. line or two of trace information, written on `stderr'.  The trace
  5529. messages tell you these things:
  5530.  
  5531.    * Each time the parser calls `yylex', what kind of token was read.
  5532.  
  5533.    * Each time a token is shifted, the depth and complete contents of
  5534.      the state stack (*note Parser States::).
  5535.  
  5536.    * Each time a rule is reduced, which rule it is, and the complete
  5537.      contents of the state stack afterward.
  5538.  
  5539.    To make sense of this information, it helps to refer to the listing
  5540. file produced by the Bison `-v' option (*note Invoking Bison:
  5541. Invocation.).  This file shows the meaning of each state in terms of
  5542. positions in various rules, and also what each state will do with each
  5543. possible input token.  As you read the successive trace messages, you
  5544. can see that the parser is functioning according to its specification in
  5545. the listing file.  Eventually you will arrive at the place where
  5546. something undesirable happens, and you will see which parts of the
  5547. grammar are to blame.
  5548.  
  5549.    The parser file is a C program and you can use C debuggers on it,
  5550. but it's not easy to interpret what it is doing.  The parser function
  5551. is a finite-state machine interpreter, and aside from the actions it
  5552. executes the same code over and over.  Only the values of variables
  5553. show where in the grammar it is working.
  5554.  
  5555.    The debugging information normally gives the token type of each token
  5556. read, but not its semantic value.  You can optionally define a macro
  5557. named `YYPRINT' to provide a way to print the value.  If you define
  5558. `YYPRINT', it should take three arguments.  The parser will pass a
  5559. standard I/O stream, the numeric code for the token type, and the token
  5560. value (from `yylval').
  5561.  
  5562.    Here is an example of `YYPRINT' suitable for the multi-function
  5563. calculator (*note Declarations for `mfcalc': Mfcalc Decl.):
  5564.  
  5565.      %{
  5566.        static void print_token_value (FILE *, int, YYSTYPE);
  5567.        #define YYPRINT(file, type, value) print_token_value (file, type, value)
  5568.      %}
  5569.  
  5570.      ... %% ... %% ...
  5571.  
  5572.      static void
  5573.      print_token_value (FILE *file, int type, YYSTYPE value)
  5574.      {
  5575.        if (type == VAR)
  5576.          fprintf (file, "%s", value.tptr->name);
  5577.        else if (type == NUM)
  5578.          fprintf (file, "%d", value.val);
  5579.      }
  5580.  
  5581. 
  5582. File: bison,  Node: Invocation,  Next: Table of Symbols,  Prev: Debugging,  Up: Top
  5583.  
  5584. 9 Invoking Bison
  5585. ****************
  5586.  
  5587. The usual way to invoke Bison is as follows:
  5588.  
  5589.      bison INFILE
  5590.  
  5591.    Here INFILE is the grammar file name, which usually ends in `.y'.
  5592. The parser file's name is made by replacing the `.y' with `.tab.c'.
  5593. Thus, the `bison foo.y' filename yields `foo.tab.c', and the `bison
  5594. hack/foo.y' filename yields `hack/foo.tab.c'.  It's also possible, in
  5595. case you are writing C++ code instead of C in your grammar file, to
  5596. name it `foo.ypp' or `foo.y++'.  Then, the output files will take an
  5597. extension like the given one as input (respectively `foo.tab.cpp' and
  5598. `foo.tab.c++').  This feature takes effect with all options that
  5599. manipulate filenames like `-o' or `-d'.
  5600.  
  5601.    For example :
  5602.  
  5603.      bison -d INFILE.YXX
  5604.    will produce `infile.tab.cxx' and `infile.tab.hxx', and
  5605.  
  5606.      bison -d -o OUTPUT.C++ INFILE.Y
  5607.    will produce `output.c++' and `outfile.h++'.
  5608.  
  5609.    For compatibility with POSIX, the standard Bison distribution also
  5610. contains a shell script called `yacc' that invokes Bison with the `-y'
  5611. option.
  5612.  
  5613. * Menu:
  5614.  
  5615. * Bison Options::     All the options described in detail,
  5616.                         in alphabetical order by short options.
  5617. * Option Cross Key::  Alphabetical list of long options.
  5618. * Yacc Library::      Yacc-compatible `yylex' and `main'.
  5619.  
  5620. 
  5621. File: bison,  Node: Bison Options,  Next: Option Cross Key,  Up: Invocation
  5622.  
  5623. 9.1 Bison Options
  5624. =================
  5625.  
  5626. Bison supports both traditional single-letter options and mnemonic long
  5627. option names.  Long option names are indicated with `--' instead of
  5628. `-'.  Abbreviations for option names are allowed as long as they are
  5629. unique.  When a long option takes an argument, like `--file-prefix',
  5630. connect the option name and the argument with `='.
  5631.  
  5632.    Here is a list of options that can be used with Bison, alphabetized
  5633. by short option.  It is followed by a cross key alphabetized by long
  5634. option.
  5635.  
  5636. Operations modes:
  5637. `-h'
  5638. `--help'
  5639.      Print a summary of the command-line options to Bison and exit.
  5640.  
  5641. `-V'
  5642. `--version'
  5643.      Print the version number of Bison and exit.
  5644.  
  5645. `-y'
  5646. `--yacc'
  5647.      Equivalent to `-o y.tab.c'; the parser output file is called
  5648.      `y.tab.c', and the other outputs are called `y.output' and
  5649.      `y.tab.h'.  The purpose of this option is to imitate Yacc's output
  5650.      file name conventions.  Thus, the following shell script can
  5651.      substitute for Yacc, and the Bison distribution contains such a
  5652.      script for compatibility with POSIX:
  5653.  
  5654.           #! /bin/sh
  5655.           bison -y "$
  5656.           "
  5657.  
  5658. Tuning the parser:
  5659.  
  5660. `-S FILE'
  5661. `--skeleton=FILE'
  5662.      Specify the skeleton to use.  You probably don't need this option
  5663.      unless you are developing Bison.
  5664.  
  5665. `-t'
  5666. `--debug'
  5667.      In the parser file, define the macro `YYDEBUG' to 1 if it is not
  5668.      already defined, so that the debugging facilities are compiled.
  5669.      *Note Tracing Your Parser: Tracing.
  5670.  
  5671. `--locations'
  5672.      Pretend that `%locations' was specified.  *Note Decl Summary::.
  5673.  
  5674. `-p PREFIX'
  5675. `--name-prefix=PREFIX'
  5676.      Pretend that `%name-prefix="PREFIX"' was specified.  *Note Decl
  5677.      Summary::.
  5678.  
  5679. `-l'
  5680. `--no-lines'
  5681.      Don't put any `#line' preprocessor commands in the parser file.
  5682.      Ordinarily Bison puts them in the parser file so that the C
  5683.      compiler and debuggers will associate errors with your source
  5684.      file, the grammar file.  This option causes them to associate
  5685.      errors with the parser file, treating it as an independent source
  5686.      file in its own right.
  5687.  
  5688. `-n'
  5689. `--no-parser'
  5690.      Pretend that `%no-parser' was specified.  *Note Decl Summary::.
  5691.  
  5692. `-k'
  5693. `--token-table'
  5694.      Pretend that `%token-table' was specified.  *Note Decl Summary::.
  5695.  
  5696. Adjust the output:
  5697.  
  5698. `-d'
  5699. `--defines'
  5700.      Pretend that `%defines' was specified, i.e., write an extra output
  5701.      file containing macro definitions for the token type names defined
  5702.      in the grammar and the semantic value type `YYSTYPE', as well as a
  5703.      few `extern' variable declarations.  *Note Decl Summary::.
  5704.  
  5705. `--defines=DEFINES-FILE'
  5706.      Same as above, but save in the file DEFINES-FILE.
  5707.  
  5708. `-b FILE-PREFIX'
  5709. `--file-prefix=PREFIX'
  5710.      Pretend that `%verbose' was specified, i.e, specify prefix to use
  5711.      for all Bison output file names.  *Note Decl Summary::.
  5712.  
  5713. `-r THINGS'
  5714. `--report=THINGS'
  5715.      Write an extra output file containing verbose description of the
  5716.      comma separated list of THINGS among:
  5717.  
  5718.     `state'
  5719.           Description of the grammar, conflicts (resolved and
  5720.           unresolved), and LALR automaton.
  5721.  
  5722.     `lookahead'
  5723.           Implies `state' and augments the description of the automaton
  5724.           with each rule's lookahead set.
  5725.  
  5726.     `itemset'
  5727.           Implies `state' and augments the description of the automaton
  5728.           with the full set of items for each state, instead of its
  5729.           core only.
  5730.  
  5731.      For instance, on the following grammar
  5732.  
  5733. `-v'
  5734. `--verbose'
  5735.      Pretend that `%verbose' was specified, i.e, write an extra output
  5736.      file containing verbose descriptions of the grammar and parser.
  5737.      *Note Decl Summary::.
  5738.  
  5739. `-o FILENAME'
  5740. `--output=FILENAME'
  5741.      Specify the FILENAME for the parser file.
  5742.  
  5743.      The other output files' names are constructed from FILENAME as
  5744.      described under the `-v' and `-d' options.
  5745.  
  5746. `-g'
  5747.      Output a VCG definition of the LALR(1) grammar automaton computed
  5748.      by Bison.  If the grammar file is `foo.y', the VCG output file will
  5749.      be `foo.vcg'.
  5750.  
  5751. `--graph=GRAPH-FILE'
  5752.      The behavior of -GRAPH is the same than `-g'.  The only difference
  5753.      is that it has an optional argument which is the name of the
  5754.      output graph filename.
  5755.  
  5756. 
  5757. File: bison,  Node: Option Cross Key,  Next: Yacc Library,  Prev: Bison Options,  Up: Invocation
  5758.  
  5759. 9.2 Option Cross Key
  5760. ====================
  5761.  
  5762. Here is a list of options, alphabetized by long option, to help you find
  5763. the corresponding short option.
  5764.  
  5765.      --debug                               -t
  5766.      --defines=DEFINES-FILE          -d
  5767.      --file-prefix=PREFIX                  -b FILE-PREFIX
  5768.      --graph=GRAPH-FILE              -d
  5769.      --help                                -h
  5770.      --name-prefix=PREFIX                  -p NAME-PREFIX
  5771.      --no-lines                            -l
  5772.      --no-parser                           -n
  5773.      --output=OUTFILE                      -o OUTFILE
  5774.      --token-table                         -k
  5775.      --verbose                             -v
  5776.      --version                             -V
  5777.      --yacc                                -y
  5778.  
  5779. 
  5780. File: bison,  Node: Yacc Library,  Prev: Option Cross Key,  Up: Invocation
  5781.  
  5782. 9.3 Yacc Library
  5783. ================
  5784.  
  5785. The Yacc library contains default implementations of the `yyerror' and
  5786. `main' functions.  These default implementations are normally not
  5787. useful, but POSIX requires them.  To use the Yacc library, link your
  5788. program with the `-ly' option.  Note that Bison's implementation of the
  5789. Yacc library is distributed under the terms of the GNU General Public
  5790. License (*note Copying::).
  5791.  
  5792.    If you use the Yacc library's `yyerror' function, you should declare
  5793. `yyerror' as follows:
  5794.  
  5795.      int yyerror (char const *);
  5796.  
  5797.    Bison ignores the `int' value returned by this `yyerror'.  If you
  5798. use the Yacc library's `main' function, your `yyparse' function should
  5799. have the following type signature:
  5800.  
  5801.      int yyparse (void);
  5802.  
  5803. 
  5804. File: bison,  Node: FAQ,  Next: Copying This Manual,  Prev: Glossary,  Up: Top
  5805.  
  5806. 10 Frequently Asked Questions
  5807. *****************************
  5808.  
  5809. Several questions about Bison come up occasionally.  Here some of them
  5810. are addressed.
  5811.  
  5812. * Menu:
  5813.  
  5814. * Parser Stack Overflow::      Breaking the Stack Limits
  5815.  
  5816. 
  5817. File: bison,  Node: Parser Stack Overflow,  Up: FAQ
  5818.  
  5819. 10.1 Parser Stack Overflow
  5820. ==========================
  5821.  
  5822.      My parser returns with error with a `parser stack overflow'
  5823.      message.  What can I do?
  5824.  
  5825.    This question is already addressed elsewhere, *Note Recursive Rules:
  5826. Recursion.
  5827.  
  5828. 
  5829. File: bison,  Node: Table of Symbols,  Next: Glossary,  Prev: Invocation,  Up: Top
  5830.  
  5831. Appendix A Bison Symbols
  5832. ************************
  5833.  
  5834.  -- Variable: @$
  5835.      In an action, the location of the left-hand side of the rule.
  5836.      *Note Locations Overview: Locations.
  5837.  
  5838.  -- Variable: @N
  5839.      In an action, the location of the N-th symbol of the right-hand
  5840.      side of the rule.  *Note Locations Overview: Locations.
  5841.  
  5842.  -- Variable: $$
  5843.      In an action, the semantic value of the left-hand side of the rule.
  5844.      *Note Actions::.
  5845.  
  5846.  -- Variable: $N
  5847.      In an action, the semantic value of the N-th symbol of the
  5848.      right-hand side of the rule.  *Note Actions::.
  5849.  
  5850.  -- Symbol: $accept
  5851.      The predefined nonterminal whose only rule is `$accept: START
  5852.      $end', where START is the start symbol.  *Note The Start-Symbol:
  5853.      Start Decl.  It cannot be used in the grammar.
  5854.  
  5855.  -- Symbol: $end
  5856.      The predefined token marking the end of the token stream.  It
  5857.      cannot be used in the grammar.
  5858.  
  5859.  -- Symbol: $undefined
  5860.      The predefined token onto which all undefined values returned by
  5861.      `yylex' are mapped.  It cannot be used in the grammar, rather, use
  5862.      `error'.
  5863.  
  5864.  -- Symbol: error
  5865.      A token name reserved for error recovery.  This token may be used
  5866.      in grammar rules so as to allow the Bison parser to recognize an
  5867.      error in the grammar without halting the process.  In effect, a
  5868.      sentence containing an error may be recognized as valid.  On a
  5869.      syntax error, the token `error' becomes the current look-ahead
  5870.      token.  Actions corresponding to `error' are then executed, and
  5871.      the look-ahead token is reset to the token that originally caused
  5872.      the violation.  *Note Error Recovery::.
  5873.  
  5874.  -- Macro: YYABORT
  5875.      Macro to pretend that an unrecoverable syntax error has occurred,
  5876.      by making `yyparse' return 1 immediately.  The error reporting
  5877.      function `yyerror' is not called.  *Note The Parser Function
  5878.      `yyparse': Parser Function.
  5879.  
  5880.  -- Macro: YYACCEPT
  5881.      Macro to pretend that a complete utterance of the language has been
  5882.      read, by making `yyparse' return 0 immediately.  *Note The Parser
  5883.      Function `yyparse': Parser Function.
  5884.  
  5885.  -- Macro: YYBACKUP
  5886.      Macro to discard a value from the parser stack and fake a
  5887.      look-ahead token.  *Note Special Features for Use in Actions:
  5888.      Action Features.
  5889.  
  5890.  -- Macro: YYDEBUG
  5891.      Macro to define to equip the parser with tracing code.  *Note
  5892.      Tracing Your Parser: Tracing.
  5893.  
  5894.  -- Macro: YYERROR
  5895.      Macro to pretend that a syntax error has just been detected: call
  5896.      `yyerror' and then perform normal error recovery if possible
  5897.      (*note Error Recovery::), or (if recovery is impossible) make
  5898.      `yyparse' return 1.  *Note Error Recovery::.
  5899.  
  5900.  -- Macro: YYERROR_VERBOSE
  5901.      An obsolete macro that you define with `#define' in the prologue
  5902.      to request verbose, specific error message strings when `yyerror'
  5903.      is called.  It doesn't matter what definition you use for
  5904.      `YYERROR_VERBOSE', just whether you define it.  Using
  5905.      `%error-verbose' is preferred.
  5906.  
  5907.  -- Macro: YYINITDEPTH
  5908.      Macro for specifying the initial size of the parser stack.  *Note
  5909.      Stack Overflow::.
  5910.  
  5911.  -- Macro: YYLEX_PARAM
  5912.      An obsolete macro for specifying an extra argument (or list of
  5913.      extra arguments) for `yyparse' to pass to `yylex'.  he use of this
  5914.      macro is deprecated, and is supported only for Yacc like parsers.
  5915.      *Note Calling Conventions for Pure Parsers: Pure Calling.
  5916.  
  5917.  -- Type: YYLTYPE
  5918.      Data type of `yylloc'; by default, a structure with four members.
  5919.      *Note Data Types of Locations: Location Type.
  5920.  
  5921.  -- Macro: YYMAXDEPTH
  5922.      Macro for specifying the maximum size of the parser stack.  *Note
  5923.      Stack Overflow::.
  5924.  
  5925.  -- Macro: YYPARSE_PARAM
  5926.      An obsolete macro for specifying the name of a parameter that
  5927.      `yyparse' should accept.  The use of this macro is deprecated, and
  5928.      is supported only for Yacc like parsers.  *Note Calling
  5929.      Conventions for Pure Parsers: Pure Calling.
  5930.  
  5931.  -- Macro: YYRECOVERING
  5932.      Macro whose value indicates whether the parser is recovering from a
  5933.      syntax error.  *Note Special Features for Use in Actions: Action
  5934.      Features.
  5935.  
  5936.  -- Macro: YYSTACK_USE_ALLOCA
  5937.      Macro used to control the use of `alloca'.  If defined to `0', the
  5938.      parser will not use `alloca' but `malloc' when trying to grow its
  5939.      internal stacks.  Do _not_ define `YYSTACK_USE_ALLOCA' to anything
  5940.      else.
  5941.  
  5942.  -- Type: YYSTYPE
  5943.      Data type of semantic values; `int' by default.  *Note Data Types
  5944.      of Semantic Values: Value Type.
  5945.  
  5946.  -- Variable: yychar
  5947.      External integer variable that contains the integer value of the
  5948.      current look-ahead token.  (In a pure parser, it is a local
  5949.      variable within `yyparse'.)  Error-recovery rule actions may
  5950.      examine this variable.  *Note Special Features for Use in Actions:
  5951.      Action Features.
  5952.  
  5953.  -- Variable: yyclearin
  5954.      Macro used in error-recovery rule actions.  It clears the previous
  5955.      look-ahead token.  *Note Error Recovery::.
  5956.  
  5957.  -- Variable: yydebug
  5958.      External integer variable set to zero by default.  If `yydebug' is
  5959.      given a nonzero value, the parser will output information on input
  5960.      symbols and parser action.  *Note Tracing Your Parser: Tracing.
  5961.  
  5962.  -- Macro: yyerrok
  5963.      Macro to cause parser to recover immediately to its normal mode
  5964.      after a syntax error.  *Note Error Recovery::.
  5965.  
  5966.  -- Function: yyerror
  5967.      User-supplied function to be called by `yyparse' on error.  *Note
  5968.      The Error Reporting Function `yyerror': Error Reporting.
  5969.  
  5970.  -- Function: yylex
  5971.      User-supplied lexical analyzer function, called with no arguments
  5972.      to get the next token.  *Note The Lexical Analyzer Function
  5973.      `yylex': Lexical.
  5974.  
  5975.  -- Variable: yylval
  5976.      External variable in which `yylex' should place the semantic value
  5977.      associated with a token.  (In a pure parser, it is a local
  5978.      variable within `yyparse', and its address is passed to `yylex'.)
  5979.      *Note Semantic Values of Tokens: Token Values.
  5980.  
  5981.  -- Variable: yylloc
  5982.      External variable in which `yylex' should place the line and column
  5983.      numbers associated with a token.  (In a pure parser, it is a local
  5984.      variable within `yyparse', and its address is passed to `yylex'.)
  5985.      You can ignore this variable if you don't use the `@' feature in
  5986.      the grammar actions.  *Note Textual Positions of Tokens: Token
  5987.      Positions.
  5988.  
  5989.  -- Variable: yynerrs
  5990.      Global variable which Bison increments each time there is a syntax
  5991.      error.  (In a pure parser, it is a local variable within
  5992.      `yyparse'.)  *Note The Error Reporting Function `yyerror': Error
  5993.      Reporting.
  5994.  
  5995.  -- Function: yyparse
  5996.      The parser function produced by Bison; call this function to start
  5997.      parsing.  *Note The Parser Function `yyparse': Parser Function.
  5998.  
  5999.  -- Directive: %debug
  6000.      Equip the parser for debugging.  *Note Decl Summary::.
  6001.  
  6002.  -- Directive: %defines
  6003.      Bison declaration to create a header file meant for the scanner.
  6004.      *Note Decl Summary::.
  6005.  
  6006.  -- Directive: %destructor
  6007.      Specifying how the parser should reclaim the memory associated to
  6008.      discarded symbols. *Note Freeing Discarded Symbols: Destructor
  6009.      Decl.
  6010.  
  6011.  -- Directive: %dprec
  6012.      Bison declaration to assign a precedence to a rule that is used at
  6013.      parse time to resolve reduce/reduce conflicts.  *Note Writing GLR
  6014.      Parsers: GLR Parsers.
  6015.  
  6016.  -- Directive: %error-verbose
  6017.      Bison declaration to request verbose, specific error message
  6018.      strings when `yyerror' is called.
  6019.  
  6020.  -- Directive: %file-prefix="PREFIX"
  6021.      Bison declaration to set the prefix of the output files.  *Note
  6022.      Decl Summary::.
  6023.  
  6024.  -- Directive: %glr-parser
  6025.      Bison declaration to produce a GLR parser.  *Note Writing GLR
  6026.      Parsers: GLR Parsers.
  6027.  
  6028.  -- Directive: %left
  6029.      Bison declaration to assign left associativity to token(s).  *Note
  6030.      Operator Precedence: Precedence Decl.
  6031.  
  6032.  -- Directive: %merge
  6033.      Bison declaration to assign a merging function to a rule.  If
  6034.      there is a reduce/reduce conflict with a rule having the same
  6035.      merging function, the function is applied to the two semantic
  6036.      values to get a single result.  *Note Writing GLR Parsers: GLR
  6037.      Parsers.
  6038.  
  6039.  -- Directive: %name-prefix="PREFIX"
  6040.      Bison declaration to rename the external symbols.  *Note Decl
  6041.      Summary::.
  6042.  
  6043.  -- Directive: %no-lines
  6044.      Bison declaration to avoid generating `#line' directives in the
  6045.      parser file.  *Note Decl Summary::.
  6046.  
  6047.  -- Directive: %nonassoc
  6048.      Bison declaration to assign non-associativity to token(s).  *Note
  6049.      Operator Precedence: Precedence Decl.
  6050.  
  6051.  -- Directive: %output="FILENAME"
  6052.      Bison declaration to set the name of the parser file.  *Note Decl
  6053.      Summary::.
  6054.  
  6055.  -- Directive: %prec
  6056.      Bison declaration to assign a precedence to a specific rule.
  6057.      *Note Context-Dependent Precedence: Contextual Precedence.
  6058.  
  6059.  -- Directive: %pure-parser
  6060.      Bison declaration to request a pure (reentrant) parser.  *Note A
  6061.      Pure (Reentrant) Parser: Pure Decl.
  6062.  
  6063.  -- Directive: %right
  6064.      Bison declaration to assign right associativity to token(s).
  6065.      *Note Operator Precedence: Precedence Decl.
  6066.  
  6067.  -- Directive: %start
  6068.      Bison declaration to specify the start symbol.  *Note The
  6069.      Start-Symbol: Start Decl.
  6070.  
  6071.  -- Directive: %token
  6072.      Bison declaration to declare token(s) without specifying
  6073.      precedence.  *Note Token Type Names: Token Decl.
  6074.  
  6075.  -- Directive: %token-table
  6076.      Bison declaration to include a token name table in the parser file.
  6077.      *Note Decl Summary::.
  6078.  
  6079.  -- Directive: %type
  6080.      Bison declaration to declare nonterminals.  *Note Nonterminal
  6081.      Symbols: Type Decl.
  6082.  
  6083.  -- Directive: %union
  6084.      Bison declaration to specify several possible data types for
  6085.      semantic values.  *Note The Collection of Value Types: Union Decl.
  6086.  
  6087.  
  6088.    These are the punctuation and delimiters used in Bison input:
  6089.  
  6090.  -- Delimiter: %%
  6091.      Delimiter used to separate the grammar rule section from the Bison
  6092.      declarations section or the epilogue.  *Note The Overall Layout of
  6093.      a Bison Grammar: Grammar Layout.
  6094.  
  6095.  -- Delimiter: %{CODE%}
  6096.      All code listed between `%{' and `%}' is copied directly to the
  6097.      output file uninterpreted.  Such code forms the prologue of the
  6098.      input file.  *Note Outline of a Bison Grammar: Grammar Outline.
  6099.  
  6100.  -- Construct: /*...*/
  6101.      Comment delimiters, as in C.
  6102.  
  6103.  -- Delimiter: :
  6104.      Separates a rule's result from its components.  *Note Syntax of
  6105.      Grammar Rules: Rules.
  6106.  
  6107.  -- Delimiter: ;
  6108.      Terminates a rule.  *Note Syntax of Grammar Rules: Rules.
  6109.  
  6110.  -- Delimiter: |
  6111.      Separates alternate rules for the same result nonterminal.  *Note
  6112.      Syntax of Grammar Rules: Rules.
  6113.  
  6114. 
  6115. File: bison,  Node: Glossary,  Next: FAQ,  Prev: Table of Symbols,  Up: Top
  6116.  
  6117. Appendix B Glossary
  6118. *******************
  6119.  
  6120. Backus-Naur Form (BNF; also called "Backus Normal Form")
  6121.      Formal method of specifying context-free grammars originally
  6122.      proposed by John Backus, and slightly improved by Peter Naur in
  6123.      his 1960-01-02 committee document contributing to what became the
  6124.      Algol 60 report.  *Note Languages and Context-Free Grammars:
  6125.      Language and Grammar.
  6126.  
  6127. Context-free grammars
  6128.      Grammars specified as rules that can be applied regardless of
  6129.      context.  Thus, if there is a rule which says that an integer can
  6130.      be used as an expression, integers are allowed _anywhere_ an
  6131.      expression is permitted.  *Note Languages and Context-Free
  6132.      Grammars: Language and Grammar.
  6133.  
  6134. Dynamic allocation
  6135.      Allocation of memory that occurs during execution, rather than at
  6136.      compile time or on entry to a function.
  6137.  
  6138. Empty string
  6139.      Analogous to the empty set in set theory, the empty string is a
  6140.      character string of length zero.
  6141.  
  6142. Finite-state stack machine
  6143.      A "machine" that has discrete states in which it is said to exist
  6144.      at each instant in time.  As input to the machine is processed, the
  6145.      machine moves from state to state as specified by the logic of the
  6146.      machine.  In the case of the parser, the input is the language
  6147.      being parsed, and the states correspond to various stages in the
  6148.      grammar rules.  *Note The Bison Parser Algorithm: Algorithm.
  6149.  
  6150. Generalized LR (GLR)
  6151.      A parsing algorithm that can handle all context-free grammars,
  6152.      including those that are not LALR(1).  It resolves situations that
  6153.      Bison's usual LALR(1) algorithm cannot by effectively splitting
  6154.      off multiple parsers, trying all possible parsers, and discarding
  6155.      those that fail in the light of additional right context.  *Note
  6156.      Generalized LR Parsing: Generalized LR Parsing.
  6157.  
  6158. Grouping
  6159.      A language construct that is (in general) grammatically divisible;
  6160.      for example, `expression' or `declaration' in C.  *Note Languages
  6161.      and Context-Free Grammars: Language and Grammar.
  6162.  
  6163. Infix operator
  6164.      An arithmetic operator that is placed between the operands on
  6165.      which it performs some operation.
  6166.  
  6167. Input stream
  6168.      A continuous flow of data between devices or programs.
  6169.  
  6170. Language construct
  6171.      One of the typical usage schemas of the language.  For example,
  6172.      one of the constructs of the C language is the `if' statement.
  6173.      *Note Languages and Context-Free Grammars: Language and Grammar.
  6174.  
  6175. Left associativity
  6176.      Operators having left associativity are analyzed from left to
  6177.      right: `a+b+c' first computes `a+b' and then combines with `c'.
  6178.      *Note Operator Precedence: Precedence.
  6179.  
  6180. Left recursion
  6181.      A rule whose result symbol is also its first component symbol; for
  6182.      example, `expseq1 : expseq1 ',' exp;'.  *Note Recursive Rules:
  6183.      Recursion.
  6184.  
  6185. Left-to-right parsing
  6186.      Parsing a sentence of a language by analyzing it token by token
  6187.      from left to right.  *Note The Bison Parser Algorithm: Algorithm.
  6188.  
  6189. Lexical analyzer (scanner)
  6190.      A function that reads an input stream and returns tokens one by
  6191.      one.  *Note The Lexical Analyzer Function `yylex': Lexical.
  6192.  
  6193. Lexical tie-in
  6194.      A flag, set by actions in the grammar rules, which alters the way
  6195.      tokens are parsed.  *Note Lexical Tie-ins::.
  6196.  
  6197. Literal string token
  6198.      A token which consists of two or more fixed characters.  *Note
  6199.      Symbols::.
  6200.  
  6201. Look-ahead token
  6202.      A token already read but not yet shifted.  *Note Look-Ahead
  6203.      Tokens: Look-Ahead.
  6204.  
  6205. LALR(1)
  6206.      The class of context-free grammars that Bison (like most other
  6207.      parser generators) can handle; a subset of LR(1).  *Note
  6208.      Mysterious Reduce/Reduce Conflicts: Mystery Conflicts.
  6209.  
  6210. LR(1)
  6211.      The class of context-free grammars in which at most one token of
  6212.      look-ahead is needed to disambiguate the parsing of any piece of
  6213.      input.
  6214.  
  6215. Nonterminal symbol
  6216.      A grammar symbol standing for a grammatical construct that can be
  6217.      expressed through rules in terms of smaller constructs; in other
  6218.      words, a construct that is not a token.  *Note Symbols::.
  6219.  
  6220. Parser
  6221.      A function that recognizes valid sentences of a language by
  6222.      analyzing the syntax structure of a set of tokens passed to it
  6223.      from a lexical analyzer.
  6224.  
  6225. Postfix operator
  6226.      An arithmetic operator that is placed after the operands upon
  6227.      which it performs some operation.
  6228.  
  6229. Reduction
  6230.      Replacing a string of nonterminals and/or terminals with a single
  6231.      nonterminal, according to a grammar rule.  *Note The Bison Parser
  6232.      Algorithm: Algorithm.
  6233.  
  6234. Reentrant
  6235.      A reentrant subprogram is a subprogram which can be in invoked any
  6236.      number of times in parallel, without interference between the
  6237.      various invocations.  *Note A Pure (Reentrant) Parser: Pure Decl.
  6238.  
  6239. Reverse polish notation
  6240.      A language in which all operators are postfix operators.
  6241.  
  6242. Right recursion
  6243.      A rule whose result symbol is also its last component symbol; for
  6244.      example, `expseq1: exp ',' expseq1;'.  *Note Recursive Rules:
  6245.      Recursion.
  6246.  
  6247. Semantics
  6248.      In computer languages, the semantics are specified by the actions
  6249.      taken for each instance of the language, i.e., the meaning of each
  6250.      statement.  *Note Defining Language Semantics: Semantics.
  6251.  
  6252. Shift
  6253.      A parser is said to shift when it makes the choice of analyzing
  6254.      further input from the stream rather than reducing immediately some
  6255.      already-recognized rule.  *Note The Bison Parser Algorithm:
  6256.      Algorithm.
  6257.  
  6258. Single-character literal
  6259.      A single character that is recognized and interpreted as is.
  6260.      *Note From Formal Rules to Bison Input: Grammar in Bison.
  6261.  
  6262. Start symbol
  6263.      The nonterminal symbol that stands for a complete valid utterance
  6264.      in the language being parsed.  The start symbol is usually listed
  6265.      as the first nonterminal symbol in a language specification.
  6266.      *Note The Start-Symbol: Start Decl.
  6267.  
  6268. Symbol table
  6269.      A data structure where symbol names and associated data are stored
  6270.      during parsing to allow for recognition and use of existing
  6271.      information in repeated uses of a symbol.  *Note Multi-function
  6272.      Calc::.
  6273.  
  6274. Syntax error
  6275.      An error encountered during parsing of an input stream due to
  6276.      invalid syntax.  *Note Error Recovery::.
  6277.  
  6278. Token
  6279.      A basic, grammatically indivisible unit of a language.  The symbol
  6280.      that describes a token in the grammar is a terminal symbol.  The
  6281.      input of the Bison parser is a stream of tokens which comes from
  6282.      the lexical analyzer.  *Note Symbols::.
  6283.  
  6284. Terminal symbol
  6285.      A grammar symbol that has no rules in the grammar and therefore is
  6286.      grammatically indivisible.  The piece of text it represents is a
  6287.      token.  *Note Languages and Context-Free Grammars: Language and
  6288.      Grammar.
  6289.  
  6290. 
  6291. File: bison,  Node: Copying This Manual,  Next: Index,  Prev: FAQ,  Up: Top
  6292.  
  6293. Appendix C Copying This Manual
  6294. ******************************
  6295.  
  6296. * Menu:
  6297.  
  6298. * GNU Free Documentation License::  License for copying this manual.
  6299.  
  6300. 
  6301. File: bison,  Node: GNU Free Documentation License,  Up: Copying This Manual
  6302.  
  6303. C.1 GNU Free Documentation License
  6304. ==================================
  6305.  
  6306.                       Version 1.2, November 2002
  6307.  
  6308.      Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
  6309.      59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
  6310.  
  6311.      Everyone is permitted to copy and distribute verbatim copies
  6312.      of this license document, but changing it is not allowed.
  6313.  
  6314.   0. PREAMBLE
  6315.  
  6316.      The purpose of this License is to make a manual, textbook, or other
  6317.      functional and useful document "free" in the sense of freedom: to
  6318.      assure everyone the effective freedom to copy and redistribute it,
  6319.      with or without modifying it, either commercially or
  6320.      noncommercially.  Secondarily, this License preserves for the
  6321.      author and publisher a way to get credit for their work, while not
  6322.      being considered responsible for modifications made by others.
  6323.  
  6324.      This License is a kind of "copyleft", which means that derivative
  6325.      works of the document must themselves be free in the same sense.
  6326.      It complements the GNU General Public License, which is a copyleft
  6327.      license designed for free software.
  6328.  
  6329.      We have designed this License in order to use it for manuals for
  6330.      free software, because free software needs free documentation: a
  6331.      free program should come with manuals providing the same freedoms
  6332.      that the software does.  But this License is not limited to
  6333.      software manuals; it can be used for any textual work, regardless
  6334.      of subject matter or whether it is published as a printed book.
  6335.      We recommend this License principally for works whose purpose is
  6336.      instruction or reference.
  6337.  
  6338.   1. APPLICABILITY AND DEFINITIONS
  6339.  
  6340.      This License applies to any manual or other work, in any medium,
  6341.      that contains a notice placed by the copyright holder saying it
  6342.      can be distributed under the terms of this License.  Such a notice
  6343.      grants a world-wide, royalty-free license, unlimited in duration,
  6344.      to use that work under the conditions stated herein.  The
  6345.      "Document", below, refers to any such manual or work.  Any member
  6346.      of the public is a licensee, and is addressed as "you".  You
  6347.      accept the license if you copy, modify or distribute the work in a
  6348.      way requiring permission under copyright law.
  6349.  
  6350.      A "Modified Version" of the Document means any work containing the
  6351.      Document or a portion of it, either copied verbatim, or with
  6352.      modifications and/or translated into another language.
  6353.  
  6354.      A "Secondary Section" is a named appendix or a front-matter section
  6355.      of the Document that deals exclusively with the relationship of the
  6356.      publishers or authors of the Document to the Document's overall
  6357.      subject (or to related matters) and contains nothing that could
  6358.      fall directly within that overall subject.  (Thus, if the Document
  6359.      is in part a textbook of mathematics, a Secondary Section may not
  6360.      explain any mathematics.)  The relationship could be a matter of
  6361.      historical connection with the subject or with related matters, or
  6362.      of legal, commercial, philosophical, ethical or political position
  6363.      regarding them.
  6364.  
  6365.      The "Invariant Sections" are certain Secondary Sections whose
  6366.      titles are designated, as being those of Invariant Sections, in
  6367.      the notice that says that the Document is released under this
  6368.      License.  If a section does not fit the above definition of
  6369.      Secondary then it is not allowed to be designated as Invariant.
  6370.      The Document may contain zero Invariant Sections.  If the Document
  6371.      does not identify any Invariant Sections then there are none.
  6372.  
  6373.      The "Cover Texts" are certain short passages of text that are
  6374.      listed, as Front-Cover Texts or Back-Cover Texts, in the notice
  6375.      that says that the Document is released under this License.  A
  6376.      Front-Cover Text may be at most 5 words, and a Back-Cover Text may
  6377.      be at most 25 words.
  6378.  
  6379.      A "Transparent" copy of the Document means a machine-readable copy,
  6380.      represented in a format whose specification is available to the
  6381.      general public, that is suitable for revising the document
  6382.      straightforwardly with generic text editors or (for images
  6383.      composed of pixels) generic paint programs or (for drawings) some
  6384.      widely available drawing editor, and that is suitable for input to
  6385.      text formatters or for automatic translation to a variety of
  6386.      formats suitable for input to text formatters.  A copy made in an
  6387.      otherwise Transparent file format whose markup, or absence of
  6388.      markup, has been arranged to thwart or discourage subsequent
  6389.      modification by readers is not Transparent.  An image format is
  6390.      not Transparent if used for any substantial amount of text.  A
  6391.      copy that is not "Transparent" is called "Opaque".
  6392.  
  6393.      Examples of suitable formats for Transparent copies include plain
  6394.      ASCII without markup, Texinfo input format, LaTeX input format,
  6395.      SGML or XML using a publicly available DTD, and
  6396.      standard-conforming simple HTML, PostScript or PDF designed for
  6397.      human modification.  Examples of transparent image formats include
  6398.      PNG, XCF and JPG.  Opaque formats include proprietary formats that
  6399.      can be read and edited only by proprietary word processors, SGML or
  6400.      XML for which the DTD and/or processing tools are not generally
  6401.      available, and the machine-generated HTML, PostScript or PDF
  6402.      produced by some word processors for output purposes only.
  6403.  
  6404.      The "Title Page" means, for a printed book, the title page itself,
  6405.      plus such following pages as are needed to hold, legibly, the
  6406.      material this License requires to appear in the title page.  For
  6407.      works in formats which do not have any title page as such, "Title
  6408.      Page" means the text near the most prominent appearance of the
  6409.      work's title, preceding the beginning of the body of the text.
  6410.  
  6411.      A section "Entitled XYZ" means a named subunit of the Document
  6412.      whose title either is precisely XYZ or contains XYZ in parentheses
  6413.      following text that translates XYZ in another language.  (Here XYZ
  6414.      stands for a specific section name mentioned below, such as
  6415.      "Acknowledgements", "Dedications", "Endorsements", or "History".)
  6416.      To "Preserve the Title" of such a section when you modify the
  6417.      Document means that it remains a section "Entitled XYZ" according
  6418.      to this definition.
  6419.  
  6420.      The Document may include Warranty Disclaimers next to the notice
  6421.      which states that this License applies to the Document.  These
  6422.      Warranty Disclaimers are considered to be included by reference in
  6423.      this License, but only as regards disclaiming warranties: any other
  6424.      implication that these Warranty Disclaimers may have is void and
  6425.      has no effect on the meaning of this License.
  6426.  
  6427.   2. VERBATIM COPYING
  6428.  
  6429.      You may copy and distribute the Document in any medium, either
  6430.      commercially or noncommercially, provided that this License, the
  6431.      copyright notices, and the license notice saying this License
  6432.      applies to the Document are reproduced in all copies, and that you
  6433.      add no other conditions whatsoever to those of this License.  You
  6434.      may not use technical measures to obstruct or control the reading
  6435.      or further copying of the copies you make or distribute.  However,
  6436.      you may accept compensation in exchange for copies.  If you
  6437.      distribute a large enough number of copies you must also follow
  6438.      the conditions in section 3.
  6439.  
  6440.      You may also lend copies, under the same conditions stated above,
  6441.      and you may publicly display copies.
  6442.  
  6443.   3. COPYING IN QUANTITY
  6444.  
  6445.      If you publish printed copies (or copies in media that commonly
  6446.      have printed covers) of the Document, numbering more than 100, and
  6447.      the Document's license notice requires Cover Texts, you must
  6448.      enclose the copies in covers that carry, clearly and legibly, all
  6449.      these Cover Texts: Front-Cover Texts on the front cover, and
  6450.      Back-Cover Texts on the back cover.  Both covers must also clearly
  6451.      and legibly identify you as the publisher of these copies.  The
  6452.      front cover must present the full title with all words of the
  6453.      title equally prominent and visible.  You may add other material
  6454.      on the covers in addition.  Copying with changes limited to the
  6455.      covers, as long as they preserve the title of the Document and
  6456.      satisfy these conditions, can be treated as verbatim copying in
  6457.      other respects.
  6458.  
  6459.      If the required texts for either cover are too voluminous to fit
  6460.      legibly, you should put the first ones listed (as many as fit
  6461.      reasonably) on the actual cover, and continue the rest onto
  6462.      adjacent pages.
  6463.  
  6464.      If you publish or distribute Opaque copies of the Document
  6465.      numbering more than 100, you must either include a
  6466.      machine-readable Transparent copy along with each Opaque copy, or
  6467.      state in or with each Opaque copy a computer-network location from
  6468.      which the general network-using public has access to download
  6469.      using public-standard network protocols a complete Transparent
  6470.      copy of the Document, free of added material.  If you use the
  6471.      latter option, you must take reasonably prudent steps, when you
  6472.      begin distribution of Opaque copies in quantity, to ensure that
  6473.      this Transparent copy will remain thus accessible at the stated
  6474.      location until at least one year after the last time you
  6475.      distribute an Opaque copy (directly or through your agents or
  6476.      retailers) of that edition to the public.
  6477.  
  6478.      It is requested, but not required, that you contact the authors of
  6479.      the Document well before redistributing any large number of
  6480.      copies, to give them a chance to provide you with an updated
  6481.      version of the Document.
  6482.  
  6483.   4. MODIFICATIONS
  6484.  
  6485.      You may copy and distribute a Modified Version of the Document
  6486.      under the conditions of sections 2 and 3 above, provided that you
  6487.      release the Modified Version under precisely this License, with
  6488.      the Modified Version filling the role of the Document, thus
  6489.      licensing distribution and modification of the Modified Version to
  6490.      whoever possesses a copy of it.  In addition, you must do these
  6491.      things in the Modified Version:
  6492.  
  6493.        A. Use in the Title Page (and on the covers, if any) a title
  6494.           distinct from that of the Document, and from those of
  6495.           previous versions (which should, if there were any, be listed
  6496.           in the History section of the Document).  You may use the
  6497.           same title as a previous version if the original publisher of
  6498.           that version gives permission.
  6499.  
  6500.        B. List on the Title Page, as authors, one or more persons or
  6501.           entities responsible for authorship of the modifications in
  6502.           the Modified Version, together with at least five of the
  6503.           principal authors of the Document (all of its principal
  6504.           authors, if it has fewer than five), unless they release you
  6505.           from this requirement.
  6506.  
  6507.        C. State on the Title page the name of the publisher of the
  6508.           Modified Version, as the publisher.
  6509.  
  6510.        D. Preserve all the copyright notices of the Document.
  6511.  
  6512.        E. Add an appropriate copyright notice for your modifications
  6513.           adjacent to the other copyright notices.
  6514.  
  6515.        F. Include, immediately after the copyright notices, a license
  6516.           notice giving the public permission to use the Modified
  6517.           Version under the terms of this License, in the form shown in
  6518.           the Addendum below.
  6519.  
  6520.        G. Preserve in that license notice the full lists of Invariant
  6521.           Sections and required Cover Texts given in the Document's
  6522.           license notice.
  6523.  
  6524.        H. Include an unaltered copy of this License.
  6525.  
  6526.        I. Preserve the section Entitled "History", Preserve its Title,
  6527.           and add to it an item stating at least the title, year, new
  6528.           authors, and publisher of the Modified Version as given on
  6529.           the Title Page.  If there is no section Entitled "History" in
  6530.           the Document, create one stating the title, year, authors,
  6531.           and publisher of the Document as given on its Title Page,
  6532.           then add an item describing the Modified Version as stated in
  6533.           the previous sentence.
  6534.  
  6535.        J. Preserve the network location, if any, given in the Document
  6536.           for public access to a Transparent copy of the Document, and
  6537.           likewise the network locations given in the Document for
  6538.           previous versions it was based on.  These may be placed in
  6539.           the "History" section.  You may omit a network location for a
  6540.           work that was published at least four years before the
  6541.           Document itself, or if the original publisher of the version
  6542.           it refers to gives permission.
  6543.  
  6544.        K. For any section Entitled "Acknowledgements" or "Dedications",
  6545.           Preserve the Title of the section, and preserve in the
  6546.           section all the substance and tone of each of the contributor
  6547.           acknowledgements and/or dedications given therein.
  6548.  
  6549.        L. Preserve all the Invariant Sections of the Document,
  6550.           unaltered in their text and in their titles.  Section numbers
  6551.           or the equivalent are not considered part of the section
  6552.           titles.
  6553.  
  6554.        M. Delete any section Entitled "Endorsements".  Such a section
  6555.           may not be included in the Modified Version.
  6556.  
  6557.        N. Do not retitle any existing section to be Entitled
  6558.           "Endorsements" or to conflict in title with any Invariant
  6559.           Section.
  6560.  
  6561.        O. Preserve any Warranty Disclaimers.
  6562.  
  6563.      If the Modified Version includes new front-matter sections or
  6564.      appendices that qualify as Secondary Sections and contain no
  6565.      material copied from the Document, you may at your option
  6566.      designate some or all of these sections as invariant.  To do this,
  6567.      add their titles to the list of Invariant Sections in the Modified
  6568.      Version's license notice.  These titles must be distinct from any
  6569.      other section titles.
  6570.  
  6571.      You may add a section Entitled "Endorsements", provided it contains
  6572.      nothing but endorsements of your Modified Version by various
  6573.      parties--for example, statements of peer review or that the text
  6574.      has been approved by an organization as the authoritative
  6575.      definition of a standard.
  6576.  
  6577.      You may add a passage of up to five words as a Front-Cover Text,
  6578.      and a passage of up to 25 words as a Back-Cover Text, to the end
  6579.      of the list of Cover Texts in the Modified Version.  Only one
  6580.      passage of Front-Cover Text and one of Back-Cover Text may be
  6581.      added by (or through arrangements made by) any one entity.  If the
  6582.      Document already includes a cover text for the same cover,
  6583.      previously added by you or by arrangement made by the same entity
  6584.      you are acting on behalf of, you may not add another; but you may
  6585.      replace the old one, on explicit permission from the previous
  6586.      publisher that added the old one.
  6587.  
  6588.      The author(s) and publisher(s) of the Document do not by this
  6589.      License give permission to use their names for publicity for or to
  6590.      assert or imply endorsement of any Modified Version.
  6591.  
  6592.   5. COMBINING DOCUMENTS
  6593.  
  6594.      You may combine the Document with other documents released under
  6595.      this License, under the terms defined in section 4 above for
  6596.      modified versions, provided that you include in the combination
  6597.      all of the Invariant Sections of all of the original documents,
  6598.      unmodified, and list them all as Invariant Sections of your
  6599.      combined work in its license notice, and that you preserve all
  6600.      their Warranty Disclaimers.
  6601.  
  6602.      The combined work need only contain one copy of this License, and
  6603.      multiple identical Invariant Sections may be replaced with a single
  6604.      copy.  If there are multiple Invariant Sections with the same name
  6605.      but different contents, make the title of each such section unique
  6606.      by adding at the end of it, in parentheses, the name of the
  6607.      original author or publisher of that section if known, or else a
  6608.      unique number.  Make the same adjustment to the section titles in
  6609.      the list of Invariant Sections in the license notice of the
  6610.      combined work.
  6611.  
  6612.      In the combination, you must combine any sections Entitled
  6613.      "History" in the various original documents, forming one section
  6614.      Entitled "History"; likewise combine any sections Entitled
  6615.      "Acknowledgements", and any sections Entitled "Dedications".  You
  6616.      must delete all sections Entitled "Endorsements."
  6617.  
  6618.   6. COLLECTIONS OF DOCUMENTS
  6619.  
  6620.      You may make a collection consisting of the Document and other
  6621.      documents released under this License, and replace the individual
  6622.      copies of this License in the various documents with a single copy
  6623.      that is included in the collection, provided that you follow the
  6624.      rules of this License for verbatim copying of each of the
  6625.      documents in all other respects.
  6626.  
  6627.      You may extract a single document from such a collection, and
  6628.      distribute it individually under this License, provided you insert
  6629.      a copy of this License into the extracted document, and follow
  6630.      this License in all other respects regarding verbatim copying of
  6631.      that document.
  6632.  
  6633.   7. AGGREGATION WITH INDEPENDENT WORKS
  6634.  
  6635.      A compilation of the Document or its derivatives with other
  6636.      separate and independent documents or works, in or on a volume of
  6637.      a storage or distribution medium, is called an "aggregate" if the
  6638.      copyright resulting from the compilation is not used to limit the
  6639.      legal rights of the compilation's users beyond what the individual
  6640.      works permit.  When the Document is included an aggregate, this
  6641.      License does not apply to the other works in the aggregate which
  6642.      are not themselves derivative works of the Document.
  6643.  
  6644.      If the Cover Text requirement of section 3 is applicable to these
  6645.      copies of the Document, then if the Document is less than one half
  6646.      of the entire aggregate, the Document's Cover Texts may be placed
  6647.      on covers that bracket the Document within the aggregate, or the
  6648.      electronic equivalent of covers if the Document is in electronic
  6649.      form.  Otherwise they must appear on printed covers that bracket
  6650.      the whole aggregate.
  6651.  
  6652.   8. TRANSLATION
  6653.  
  6654.      Translation is considered a kind of modification, so you may
  6655.      distribute translations of the Document under the terms of section
  6656.      4.  Replacing Invariant Sections with translations requires special
  6657.      permission from their copyright holders, but you may include
  6658.      translations of some or all Invariant Sections in addition to the
  6659.      original versions of these Invariant Sections.  You may include a
  6660.      translation of this License, and all the license notices in the
  6661.      Document, and any Warrany Disclaimers, provided that you also
  6662.      include the original English version of this License and the
  6663.      original versions of those notices and disclaimers.  In case of a
  6664.      disagreement between the translation and the original version of
  6665.      this License or a notice or disclaimer, the original version will
  6666.      prevail.
  6667.  
  6668.      If a section in the Document is Entitled "Acknowledgements",
  6669.      "Dedications", or "History", the requirement (section 4) to
  6670.      Preserve its Title (section 1) will typically require changing the
  6671.      actual title.
  6672.  
  6673.   9. TERMINATION
  6674.  
  6675.      You may not copy, modify, sublicense, or distribute the Document
  6676.      except as expressly provided for under this License.  Any other
  6677.      attempt to copy, modify, sublicense or distribute the Document is
  6678.      void, and will automatically terminate your rights under this
  6679.      License.  However, parties who have received copies, or rights,
  6680.      from you under this License will not have their licenses
  6681.      terminated so long as such parties remain in full compliance.
  6682.  
  6683.  10. FUTURE REVISIONS OF THIS LICENSE
  6684.  
  6685.      The Free Software Foundation may publish new, revised versions of
  6686.      the GNU Free Documentation License from time to time.  Such new
  6687.      versions will be similar in spirit to the present version, but may
  6688.      differ in detail to address new problems or concerns.  See
  6689.      `http://www.gnu.org/copyleft/'.
  6690.  
  6691.      Each version of the License is given a distinguishing version
  6692.      number.  If the Document specifies that a particular numbered
  6693.      version of this License "or any later version" applies to it, you
  6694.      have the option of following the terms and conditions either of
  6695.      that specified version or of any later version that has been
  6696.      published (not as a draft) by the Free Software Foundation.  If
  6697.      the Document does not specify a version number of this License,
  6698.      you may choose any version ever published (not as a draft) by the
  6699.      Free Software Foundation.
  6700.  
  6701. C.1.1 ADDENDUM: How to use this License for your documents
  6702. ----------------------------------------------------------
  6703.  
  6704. To use this License in a document you have written, include a copy of
  6705. the License in the document and put the following copyright and license
  6706. notices just after the title page:
  6707.  
  6708.        Copyright (C)  YEAR  YOUR NAME.
  6709.        Permission is granted to copy, distribute and/or modify this document
  6710.        under the terms of the GNU Free Documentation License, Version 1.2
  6711.        or any later version published by the Free Software Foundation;
  6712.        with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
  6713.        A copy of the license is included in the section entitled ``GNU
  6714.        Free Documentation License''.
  6715.  
  6716.    If you have Invariant Sections, Front-Cover Texts and Back-Cover
  6717. Texts, replace the "with...Texts." line with this:
  6718.  
  6719.          with the Invariant Sections being LIST THEIR TITLES, with
  6720.          the Front-Cover Texts being LIST, and with the Back-Cover Texts
  6721.          being LIST.
  6722.  
  6723.    If you have Invariant Sections without Cover Texts, or some other
  6724. combination of the three, merge those two alternatives to suit the
  6725. situation.
  6726.  
  6727.    If your document contains nontrivial examples of program code, we
  6728. recommend releasing these examples in parallel under your choice of
  6729. free software license, such as the GNU General Public License, to
  6730. permit their use in free software.
  6731.  
  6732. 
  6733. File: bison,  Node: Index,  Prev: Copying This Manual,  Up: Top
  6734.  
  6735. Index
  6736. *****
  6737.  
  6738. [index]
  6739. * Menu:
  6740.  
  6741. * $ <1>:                                 Table of Symbols.    (line  19)
  6742. * $:                                     Action Features.     (line  14)
  6743. * $$ <1>:                                Table of Symbols.    (line  15)
  6744. * $$ <2>:                                Action Features.     (line  10)
  6745. * $$:                                    Actions.             (line   6)
  6746. * $<:                                    Action Features.     (line  18)
  6747. * $accept:                               Table of Symbols.    (line  23)
  6748. * $end:                                  Table of Symbols.    (line  28)
  6749. * $N:                                    Actions.             (line   6)
  6750. * $undefined:                            Table of Symbols.    (line  32)
  6751. * %:                                     Table of Symbols.    (line 268)
  6752. * %%:                                    Table of Symbols.    (line 263)
  6753. * %debug <1>:                            Table of Symbols.    (line 172)
  6754. * %debug <2>:                            Tracing.             (line  23)
  6755. * %debug:                                Decl Summary.        (line  46)
  6756. * %defines <1>:                          Table of Symbols.    (line 175)
  6757. * %defines:                              Decl Summary.        (line  51)
  6758. * %destructor <1>:                       Table of Symbols.    (line 179)
  6759. * %destructor <2>:                       Decl Summary.        (line  64)
  6760. * %destructor:                           Destructor Decl.     (line   6)
  6761. * %dprec:                                Table of Symbols.    (line 184)
  6762. * %error-verbose <1>:                    Table of Symbols.    (line 189)
  6763. * %error-verbose:                        Error Reporting.     (line  17)
  6764. * %expect <1>:                           Decl Summary.        (line  38)
  6765. * %expect:                               Expect Decl.         (line   6)
  6766. * %file-prefix=" <1>:                    Table of Symbols.    (line 193)
  6767. * %file-prefix=":                        Decl Summary.        (line  69)
  6768. * %glr-parser <1>:                       Table of Symbols.    (line 197)
  6769. * %glr-parser:                           GLR Parsers.         (line   6)
  6770. * %left <1>:                             Table of Symbols.    (line 201)
  6771. * %left <2>:                             Using Precedence.    (line   6)
  6772. * %left:                                 Decl Summary.        (line  21)
  6773. * %locations:                            Decl Summary.        (line  73)
  6774. * %merge:                                Table of Symbols.    (line 205)
  6775. * %name-prefix=" <1>:                    Table of Symbols.    (line 212)
  6776. * %name-prefix=":                        Decl Summary.        (line  80)
  6777. * %no-lines <1>:                         Table of Symbols.    (line 216)
  6778. * %no-lines:                             Decl Summary.        (line  98)
  6779. * %no-parser:                            Decl Summary.        (line  89)
  6780. * %nonassoc <1>:                         Table of Symbols.    (line 220)
  6781. * %nonassoc <2>:                         Using Precedence.    (line   6)
  6782. * %nonassoc:                             Decl Summary.        (line  25)
  6783. * %output=" <1>:                         Table of Symbols.    (line 224)
  6784. * %output=":                             Decl Summary.        (line 106)
  6785. * %prec <1>:                             Table of Symbols.    (line 228)
  6786. * %prec:                                 Contextual Precedence.
  6787.                                                               (line   6)
  6788. * %pure-parser <1>:                      Table of Symbols.    (line 232)
  6789. * %pure-parser <2>:                      Decl Summary.        (line 109)
  6790. * %pure-parser:                          Pure Decl.           (line   6)
  6791. * %right <1>:                            Table of Symbols.    (line 236)
  6792. * %right <2>:                            Using Precedence.    (line   6)
  6793. * %right:                                Decl Summary.        (line  17)
  6794. * %start <1>:                            Table of Symbols.    (line 240)
  6795. * %start <2>:                            Decl Summary.        (line  34)
  6796. * %start:                                Start Decl.          (line   6)
  6797. * %token <1>:                            Table of Symbols.    (line 244)
  6798. * %token <2>:                            Decl Summary.        (line  13)
  6799. * %token:                                Token Decl.          (line   6)
  6800. * %token-table <1>:                      Table of Symbols.    (line 248)
  6801. * %token-table:                          Decl Summary.        (line 113)
  6802. * %type <1>:                             Table of Symbols.    (line 252)
  6803. * %type <2>:                             Decl Summary.        (line  30)
  6804. * %type:                                 Type Decl.           (line   6)
  6805. * %union <1>:                            Table of Symbols.    (line 256)
  6806. * %union <2>:                            Decl Summary.        (line   9)
  6807. * %union:                                Union Decl.          (line   6)
  6808. * %verbose:                              Decl Summary.        (line 147)
  6809. * %yacc:                                 Decl Summary.        (line 153)
  6810. * /*:                                    Table of Symbols.    (line 273)
  6811. * ::                                     Table of Symbols.    (line 276)
  6812. * ;:                                     Table of Symbols.    (line 280)
  6813. * @$ <1>:                                Table of Symbols.    (line   7)
  6814. * @$ <2>:                                Action Features.     (line  80)
  6815. * @$:                                    Actions and Locations.
  6816.                                                               (line   6)
  6817. * @N <1>:                                Table of Symbols.    (line  11)
  6818. * @N <2>:                                Action Features.     (line  86)
  6819. * @N:                                    Actions and Locations.
  6820.                                                               (line   6)
  6821. * action:                                Actions.             (line   6)
  6822. * action data types:                     Action Types.        (line   6)
  6823. * action features summary:               Action Features.     (line   6)
  6824. * actions in mid-rule:                   Mid-Rule Actions.    (line   6)
  6825. * actions, location:                     Actions and Locations.
  6826.                                                               (line   6)
  6827. * actions, semantic:                     Semantic Actions.    (line   6)
  6828. * additional C code section:             Epilogue.            (line   6)
  6829. * algorithm of parser:                   Algorithm.           (line   6)
  6830. * ambiguous grammars <1>:                Generalized LR Parsing.
  6831.                                                               (line   6)
  6832. * ambiguous grammars:                    Language and Grammar.
  6833.                                                               (line  33)
  6834. * associativity:                         Why Precedence.      (line  33)
  6835. * Backus-Naur form:                      Language and Grammar.
  6836.                                                               (line  16)
  6837. * Bison declaration summary:             Decl Summary.        (line   6)
  6838. * Bison declarations:                    Declarations.        (line   6)
  6839. * Bison declarations (introduction):     Bison Declarations.  (line   6)
  6840. * Bison grammar:                         Grammar in Bison.    (line   6)
  6841. * Bison invocation:                      Invocation.          (line   6)
  6842. * Bison parser:                          Bison Parser.        (line   6)
  6843. * Bison parser algorithm:                Algorithm.           (line   6)
  6844. * Bison symbols, table of:               Table of Symbols.    (line   6)
  6845. * Bison utility:                         Bison Parser.        (line   6)
  6846. * BNF:                                   Language and Grammar.
  6847.                                                               (line  16)
  6848. * C code, section for additional:        Epilogue.            (line   6)
  6849. * C-language interface:                  Interface.           (line   6)
  6850. * calc:                                  Infix Calc.          (line   6)
  6851. * calculator, infix notation:            Infix Calc.          (line   6)
  6852. * calculator, location tracking:         Location Tracking Calc.
  6853.                                                               (line   6)
  6854. * calculator, multi-function:            Multi-function Calc. (line   6)
  6855. * calculator, simple:                    RPN Calc.            (line   6)
  6856. * character token:                       Symbols.             (line  31)
  6857. * compiling the parser:                  Rpcalc Compile.      (line   6)
  6858. * conflicts <1>:                         Shift/Reduce.        (line   6)
  6859. * conflicts:                             GLR Parsers.         (line   6)
  6860. * conflicts, reduce/reduce:              Reduce/Reduce.       (line   6)
  6861. * conflicts, suppressing warnings of:    Expect Decl.         (line   6)
  6862. * context-dependent precedence:          Contextual Precedence.
  6863.                                                               (line   6)
  6864. * context-free grammar:                  Language and Grammar.
  6865.                                                               (line   6)
  6866. * controlling function:                  Rpcalc Main.         (line   6)
  6867. * core, item set:                        Understanding.       (line 129)
  6868. * dangling else:                         Shift/Reduce.        (line   6)
  6869. * data type of locations:                Location Type.       (line   6)
  6870. * data types in actions:                 Action Types.        (line   6)
  6871. * data types of semantic values:         Value Type.          (line   6)
  6872. * debugging:                             Tracing.             (line   6)
  6873. * declaration summary:                   Decl Summary.        (line   6)
  6874. * declarations:                          Prologue.            (line   6)
  6875. * declarations section:                  Prologue.            (line   6)
  6876. * declarations, Bison:                   Declarations.        (line   6)
  6877. * declarations, Bison (introduction):    Bison Declarations.  (line   6)
  6878. * declaring literal string tokens:       Token Decl.          (line   6)
  6879. * declaring operator precedence:         Precedence Decl.     (line   6)
  6880. * declaring the start symbol:            Start Decl.          (line   6)
  6881. * declaring token type names:            Token Decl.          (line   6)
  6882. * declaring value types:                 Union Decl.          (line   6)
  6883. * declaring value types, nonterminals:   Type Decl.           (line   6)
  6884. * default action:                        Actions.             (line  55)
  6885. * default data type:                     Value Type.          (line   6)
  6886. * default location type:                 Location Type.       (line   6)
  6887. * default stack limit:                   Stack Overflow.      (line  27)
  6888. * default start symbol:                  Start Decl.          (line   6)
  6889. * defining language semantics:           Semantics.           (line   6)
  6890. * else, dangling:                        Shift/Reduce.        (line   6)
  6891. * epilogue:                              Epilogue.            (line   6)
  6892. * error <1>:                             Table of Symbols.    (line  37)
  6893. * error:                                 Error Recovery.      (line  20)
  6894. * error recovery:                        Error Recovery.      (line   6)
  6895. * error recovery, simple:                Simple Error Recovery.
  6896.                                                               (line   6)
  6897. * error reporting function:              Error Reporting.     (line   6)
  6898. * error reporting routine:               Rpcalc Error.        (line   6)
  6899. * examples, simple:                      Examples.            (line   6)
  6900. * exercises:                             Exercises.           (line   6)
  6901. * FDL, GNU Free Documentation License:   GNU Free Documentation License.
  6902.                                                               (line   6)
  6903. * file format:                           Grammar Layout.      (line   6)
  6904. * finite-state machine:                  Parser States.       (line   6)
  6905. * formal grammar:                        Grammar in Bison.    (line   6)
  6906. * format of grammar file:                Grammar Layout.      (line   6)
  6907. * freeing discarded symbols:             Destructor Decl.     (line   6)
  6908. * frequently asked questions:            FAQ.                 (line   6)
  6909. * generalized LR (GLR) parsing <1>:      Generalized LR Parsing.
  6910.                                                               (line   6)
  6911. * generalized LR (GLR) parsing <2>:      GLR Parsers.         (line   6)
  6912. * generalized LR (GLR) parsing:          Language and Grammar.
  6913.                                                               (line  33)
  6914. * glossary:                              Glossary.            (line   6)
  6915. * GLR parsers and inline:                GLR Parsers.         (line 150)
  6916. * GLR parsing <1>:                       Generalized LR Parsing.
  6917.                                                               (line   6)
  6918. * GLR parsing <2>:                       GLR Parsers.         (line   6)
  6919. * GLR parsing:                           Language and Grammar.
  6920.                                                               (line  33)
  6921. * grammar file:                          Grammar Layout.      (line   6)
  6922. * grammar rule syntax:                   Rules.               (line   6)
  6923. * grammar rules section:                 Grammar Rules.       (line   6)
  6924. * grammar, Bison:                        Grammar in Bison.    (line   6)
  6925. * grammar, context-free:                 Language and Grammar.
  6926.                                                               (line   6)
  6927. * grouping, syntactic:                   Language and Grammar.
  6928.                                                               (line  47)
  6929. * incline:                               GLR Parsers.         (line 150)
  6930. * infix notation calculator:             Infix Calc.          (line   6)
  6931. * interface:                             Interface.           (line   6)
  6932. * introduction:                          Introduction.        (line   6)
  6933. * invoking Bison:                        Invocation.          (line   6)
  6934. * item:                                  Understanding.       (line 107)
  6935. * item set core:                         Understanding.       (line 129)
  6936. * kernel, item set:                      Understanding.       (line 129)
  6937. * LALR(1):                               Mystery Conflicts.   (line  36)
  6938. * LALR(1) grammars:                      Language and Grammar.
  6939.                                                               (line  22)
  6940. * language semantics, defining:          Semantics.           (line   6)
  6941. * layout of Bison grammar:               Grammar Layout.      (line   6)
  6942. * left recursion:                        Recursion.           (line  16)
  6943. * lexical analyzer:                      Lexical.             (line   6)
  6944. * lexical analyzer, purpose:             Bison Parser.        (line   6)
  6945. * lexical analyzer, writing:             Rpcalc Lexer.        (line   6)
  6946. * lexical tie-in:                        Lexical Tie-ins.     (line   6)
  6947. * literal string token:                  Symbols.             (line  53)
  6948. * literal token:                         Symbols.             (line  31)
  6949. * location <1>:                          Locations.           (line   6)
  6950. * location:                              Locations Overview.  (line   6)
  6951. * location actions:                      Actions and Locations.
  6952.                                                               (line   6)
  6953. * location tracking calculator:          Location Tracking Calc.
  6954.                                                               (line   6)
  6955. * look-ahead token:                      Look-Ahead.          (line   6)
  6956. * LR(1):                                 Mystery Conflicts.   (line  36)
  6957. * LR(1) grammars:                        Language and Grammar.
  6958.                                                               (line  22)
  6959. * ltcalc:                                Location Tracking Calc.
  6960.                                                               (line   6)
  6961. * main function in simple example:       Rpcalc Main.         (line   6)
  6962. * mfcalc:                                Multi-function Calc. (line   6)
  6963. * mid-rule actions:                      Mid-Rule Actions.    (line   6)
  6964. * multi-function calculator:             Multi-function Calc. (line   6)
  6965. * multicharacter literal:                Symbols.             (line  53)
  6966. * mutual recursion:                      Recursion.           (line  32)
  6967. * non-deterministic parsing <1>:         Generalized LR Parsing.
  6968.                                                               (line   6)
  6969. * non-deterministic parsing:             Language and Grammar.
  6970.                                                               (line  33)
  6971. * nonterminal symbol:                    Symbols.             (line   6)
  6972. * nonterminal, useless:                  Understanding.       (line  62)
  6973. * operator precedence:                   Precedence.          (line   6)
  6974. * operator precedence, declaring:        Precedence Decl.     (line   6)
  6975. * options for invoking Bison:            Invocation.          (line   6)
  6976. * overflow of parser stack:              Stack Overflow.      (line   6)
  6977. * parse error:                           Error Reporting.     (line   6)
  6978. * parser:                                Bison Parser.        (line   6)
  6979. * parser stack:                          Algorithm.           (line   6)
  6980. * parser stack overflow:                 Stack Overflow.      (line   6)
  6981. * parser state:                          Parser States.       (line   6)
  6982. * pointed rule:                          Understanding.       (line 107)
  6983. * polish notation calculator:            RPN Calc.            (line   6)
  6984. * position, textual <1>:                 Locations.           (line   6)
  6985. * position, textual:                     Locations Overview.  (line   6)
  6986. * precedence declarations:               Precedence Decl.     (line   6)
  6987. * precedence of operators:               Precedence.          (line   6)
  6988. * precedence, context-dependent:         Contextual Precedence.
  6989.                                                               (line   6)
  6990. * precedence, unary operator:            Contextual Precedence.
  6991.                                                               (line   6)
  6992. * preventing warnings about conflicts:   Expect Decl.         (line   6)
  6993. * Prologue:                              Prologue.            (line   6)
  6994. * pure parser:                           Pure Decl.           (line   6)
  6995. * questions:                             FAQ.                 (line   6)
  6996. * recovery from errors:                  Error Recovery.      (line   6)
  6997. * recursive rule:                        Recursion.           (line   6)
  6998. * reduce/reduce conflict:                Reduce/Reduce.       (line   6)
  6999. * reduction:                             Algorithm.           (line   6)
  7000. * reentrant parser:                      Pure Decl.           (line   6)
  7001. * reverse polish notation:               RPN Calc.            (line   6)
  7002. * right recursion:                       Recursion.           (line  16)
  7003. * rpcalc:                                RPN Calc.            (line   6)
  7004. * rule syntax:                           Rules.               (line   6)
  7005. * rule, pointed:                         Understanding.       (line 107)
  7006. * rule, useless:                         Understanding.       (line  62)
  7007. * rules section for grammar:             Grammar Rules.       (line   6)
  7008. * running Bison (introduction):          Rpcalc Gen.          (line   6)
  7009. * semantic actions:                      Semantic Actions.    (line   6)
  7010. * semantic value:                        Semantic Values.     (line   6)
  7011. * semantic value type:                   Value Type.          (line   6)
  7012. * shift/reduce conflicts <1>:            Shift/Reduce.        (line   6)
  7013. * shift/reduce conflicts:                GLR Parsers.         (line   6)
  7014. * shifting:                              Algorithm.           (line   6)
  7015. * simple examples:                       Examples.            (line   6)
  7016. * single-character literal:              Symbols.             (line  31)
  7017. * stack overflow:                        Stack Overflow.      (line   6)
  7018. * stack, parser:                         Algorithm.           (line   6)
  7019. * stages in using Bison:                 Stages.              (line   6)
  7020. * start symbol:                          Language and Grammar.
  7021.                                                               (line  96)
  7022. * start symbol, declaring:               Start Decl.          (line   6)
  7023. * state (of parser):                     Parser States.       (line   6)
  7024. * string token:                          Symbols.             (line  53)
  7025. * summary, action features:              Action Features.     (line   6)
  7026. * summary, Bison declaration:            Decl Summary.        (line   6)
  7027. * suppressing conflict warnings:         Expect Decl.         (line   6)
  7028. * symbol:                                Symbols.             (line   6)
  7029. * symbol table example:                  Mfcalc Symtab.       (line   6)
  7030. * symbols (abstract):                    Language and Grammar.
  7031.                                                               (line  47)
  7032. * symbols in Bison, table of:            Table of Symbols.    (line   6)
  7033. * syntactic grouping:                    Language and Grammar.
  7034.                                                               (line  47)
  7035. * syntax error:                          Error Reporting.     (line   6)
  7036. * syntax of grammar rules:               Rules.               (line   6)
  7037. * terminal symbol:                       Symbols.             (line   6)
  7038. * textual position <1>:                  Locations.           (line   6)
  7039. * textual position:                      Locations Overview.  (line   6)
  7040. * token:                                 Language and Grammar.
  7041.                                                               (line  47)
  7042. * token type:                            Symbols.             (line   6)
  7043. * token type names, declaring:           Token Decl.          (line   6)
  7044. * token, useless:                        Understanding.       (line  62)
  7045. * tracing the parser:                    Tracing.             (line   6)
  7046. * unary operator precedence:             Contextual Precedence.
  7047.                                                               (line   6)
  7048. * useless nonterminal:                   Understanding.       (line  62)
  7049. * useless rule:                          Understanding.       (line  62)
  7050. * useless token:                         Understanding.       (line  62)
  7051. * using Bison:                           Stages.              (line   6)
  7052. * value type, semantic:                  Value Type.          (line   6)
  7053. * value types, declaring:                Union Decl.          (line   6)
  7054. * value types, nonterminals, declaring:  Type Decl.           (line   6)
  7055. * value, semantic:                       Semantic Values.     (line   6)
  7056. * warnings, preventing:                  Expect Decl.         (line   6)
  7057. * writing a lexical analyzer:            Rpcalc Lexer.        (line   6)
  7058. * YYABORT <1>:                           Table of Symbols.    (line  47)
  7059. * YYABORT:                               Parser Function.     (line  25)
  7060. * YYABORT;:                              Action Features.     (line  28)
  7061. * YYACCEPT <1>:                          Table of Symbols.    (line  53)
  7062. * YYACCEPT:                              Parser Function.     (line  22)
  7063. * YYACCEPT;:                             Action Features.     (line  32)
  7064. * YYBACKUP <1>:                          Table of Symbols.    (line  58)
  7065. * YYBACKUP:                              Action Features.     (line  36)
  7066. * yychar <1>:                            Table of Symbols.    (line 119)
  7067. * yychar <2>:                            Look-Ahead.          (line  47)
  7068. * yychar:                                Action Features.     (line  65)
  7069. * yyclearin <1>:                         Table of Symbols.    (line 126)
  7070. * yyclearin:                             Error Recovery.      (line  97)
  7071. * yyclearin;:                            Action Features.     (line  71)
  7072. * yydebug:                               Table of Symbols.    (line 130)
  7073. * YYDEBUG <1>:                           Table of Symbols.    (line  63)
  7074. * YYDEBUG:                               Tracing.             (line  12)
  7075. * yydebug:                               Tracing.             (line   6)
  7076. * YYEMPTY:                               Action Features.     (line  49)
  7077. * yyerrok <1>:                           Table of Symbols.    (line 135)
  7078. * yyerrok:                               Error Recovery.      (line  92)
  7079. * yyerrok;:                              Action Features.     (line  75)
  7080. * yyerror:                               Table of Symbols.    (line 139)
  7081. * YYERROR <1>:                           Table of Symbols.    (line  67)
  7082. * YYERROR:                               Action Features.     (line  52)
  7083. * yyerror:                               Error Reporting.     (line   6)
  7084. * YYERROR;:                              Action Features.     (line  52)
  7085. * YYERROR_VERBOSE:                       Table of Symbols.    (line  73)
  7086. * YYINITDEPTH <1>:                       Table of Symbols.    (line  80)
  7087. * YYINITDEPTH:                           Stack Overflow.      (line  29)
  7088. * yylex <1>:                             Table of Symbols.    (line 143)
  7089. * yylex:                                 Lexical.             (line   6)
  7090. * YYLEX_PARAM:                           Table of Symbols.    (line  84)
  7091. * yylloc <1>:                            Table of Symbols.    (line 154)
  7092. * yylloc:                                Token Positions.     (line   6)
  7093. * YYLLOC_DEFAULT:                        Location Default Action.
  7094.                                                               (line   6)
  7095. * YYLTYPE <1>:                           Table of Symbols.    (line  90)
  7096. * YYLTYPE:                               Token Positions.     (line  19)
  7097. * yylval <1>:                            Table of Symbols.    (line 148)
  7098. * yylval:                                Token Values.        (line   6)
  7099. * YYMAXDEPTH <1>:                        Table of Symbols.    (line  94)
  7100. * YYMAXDEPTH:                            Stack Overflow.      (line  14)
  7101. * yynerrs <1>:                           Table of Symbols.    (line 162)
  7102. * yynerrs:                               Error Reporting.     (line  61)
  7103. * yyparse <1>:                           Table of Symbols.    (line 168)
  7104. * yyparse:                               Parser Function.     (line   6)
  7105. * YYPARSE_PARAM:                         Table of Symbols.    (line  98)
  7106. * YYPRINT:                               Tracing.             (line  71)
  7107. * YYRECOVERING <1>:                      Table of Symbols.    (line 104)
  7108. * YYRECOVERING <2>:                      Error Recovery.      (line 108)
  7109. * YYRECOVERING:                          Action Features.     (line  60)
  7110. * YYSTACK_USE_ALLOCA:                    Table of Symbols.    (line 109)
  7111. * YYSTYPE:                               Table of Symbols.    (line 115)
  7112. * | <1>:                                 Table of Symbols.    (line 283)
  7113. * |:                                     Rules.               (line  34)
  7114.  
  7115.  
  7116. 
  7117. Tag Table:
  7118. Node: Top1122
  7119. Node: Introduction10400
  7120. Node: Conditions11667
  7121. Node: Copying13550
  7122. Node: Concepts32715
  7123. Node: Language and Grammar33863
  7124. Node: Grammar in Bison39749
  7125. Node: Semantic Values41673
  7126. Node: Semantic Actions43774
  7127. Node: GLR Parsers44956
  7128. Node: Locations Overview51149
  7129. Node: Bison Parser52597
  7130. Node: Stages55312
  7131. Node: Grammar Layout56595
  7132. Node: Examples57922
  7133. Node: RPN Calc59116
  7134. Node: Rpcalc Decls60090
  7135. Node: Rpcalc Rules62006
  7136. Node: Rpcalc Input63808
  7137. Node: Rpcalc Line65278
  7138. Node: Rpcalc Expr66401
  7139. Node: Rpcalc Lexer68354
  7140. Node: Rpcalc Main70936
  7141. Node: Rpcalc Error71338
  7142. Node: Rpcalc Gen72352
  7143. Node: Rpcalc Compile73487
  7144. Node: Infix Calc74356
  7145. Node: Simple Error Recovery77114
  7146. Node: Location Tracking Calc79004
  7147. Node: Ltcalc Decls79686
  7148. Node: Ltcalc Rules80634
  7149. Node: Ltcalc Lexer82638
  7150. Node: Multi-function Calc84956
  7151. Node: Mfcalc Decl86523
  7152. Node: Mfcalc Rules88557
  7153. Node: Mfcalc Symtab89933
  7154. Node: Exercises96104
  7155. Node: Grammar File96613
  7156. Node: Grammar Outline97457
  7157. Node: Prologue98212
  7158. Node: Bison Declarations99484
  7159. Node: Grammar Rules99894
  7160. Node: Epilogue100360
  7161. Node: Symbols101371
  7162. Node: Rules107998
  7163. Node: Recursion109634
  7164. Node: Semantics111347
  7165. Node: Value Type112441
  7166. Node: Multiple Types113103
  7167. Node: Actions114124
  7168. Node: Action Types117544
  7169. Node: Mid-Rule Actions118851
  7170. Node: Locations124420
  7171. Node: Location Type125066
  7172. Node: Actions and Locations125653
  7173. Node: Location Default Action127816
  7174. Node: Declarations130035
  7175. Node: Token Decl131408
  7176. Node: Precedence Decl133426
  7177. Node: Union Decl134981
  7178. Node: Type Decl136118
  7179. Node: Destructor Decl137035
  7180. Node: Expect Decl139152
  7181. Node: Start Decl140729
  7182. Node: Pure Decl141112
  7183. Node: Decl Summary142793
  7184. Node: Multiple Parsers149061
  7185. Node: Interface150565
  7186. Node: Parser Function151424
  7187. Node: Lexical152319
  7188. Node: Calling Convention153725
  7189. Node: Token Values156597
  7190. Node: Token Positions157757
  7191. Node: Pure Calling158646
  7192. Node: Error Reporting159649
  7193. Node: Action Features162620
  7194. Node: Algorithm166105
  7195. Node: Look-Ahead168463
  7196. Node: Shift/Reduce170590
  7197. Node: Precedence173482
  7198. Node: Why Precedence174133
  7199. Node: Using Precedence176002
  7200. Node: Precedence Examples176974
  7201. Node: How Precedence177679
  7202. Node: Contextual Precedence178833
  7203. Node: Parser States180624
  7204. Node: Reduce/Reduce181867
  7205. Node: Mystery Conflicts185403
  7206. Node: Generalized LR Parsing188791
  7207. Node: Stack Overflow193072
  7208. Node: Error Recovery194940
  7209. Node: Context Dependency200233
  7210. Node: Semantic Tokens201077
  7211. Node: Lexical Tie-ins204089
  7212. Node: Tie-in Recovery205661
  7213. Node: Debugging207833
  7214. Node: Understanding208494
  7215. Node: Tracing219580
  7216. Node: Invocation223659
  7217. Node: Bison Options225021
  7218. Node: Option Cross Key229288
  7219. Node: Yacc Library230156
  7220. Node: FAQ230976
  7221. Node: Parser Stack Overflow231273
  7222. Node: Table of Symbols231563
  7223. Node: Glossary242308
  7224. Node: Copying This Manual249188
  7225. Node: GNU Free Documentation License249409
  7226. Node: Index271807
  7227. 
  7228. End Tag Table
  7229.