home *** CD-ROM | disk | FTP | other *** search
/ RISCWORLD 7 / RISCWORLD_VOL7.iso / Software / Issue4 / SDL / gcc346 / !gcc / docs / bison next >
Encoding:
Text File  |  2006-09-17  |  384.2 KB  |  7,873 lines

  1. <html lang="en">
  2. <head>
  3. <title>Bison 1.875</title>
  4. <meta http-equiv="Content-Type" content="text/html">
  5. <meta name="description" content="Bison 1.875">
  6. <meta name="generator" content="makeinfo 4.8">
  7. <link title="Top" rel="top" href="#Top">
  8. <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
  9. <!--
  10. This manual is for GNU Bison (version 1.875,
  11. 28 December 2002), the GNU parser generator.
  12.  
  13. Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
  14. 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
  15.  
  16.      Permission is granted to copy, distribute and/or modify this
  17.      document under the terms of the GNU Free Documentation License,
  18.      Version 1.1 or any later version published by the Free Software
  19.      Foundation; with no Invariant Sections, with the Front-Cover texts
  20.      being "A GNU Manual," and with the Back-Cover Texts as in (a)
  21.      below.  A copy of the license is included in the section entitled
  22.      "GNU Free Documentation License."
  23.  
  24.      (a) The FSF's Back-Cover Text is: "You have freedom to copy and
  25.      modify this GNU Manual, like GNU software.  Copies published by
  26.      the Free Software Foundation raise funds for GNU development."
  27.    -->
  28. <meta http-equiv="Content-Style-Type" content="text/css">
  29. <style type="text/css"><!--
  30.   pre.display { font-family:inherit }
  31.   pre.format  { font-family:inherit }
  32.   pre.smalldisplay { font-family:inherit; font-size:smaller }
  33.   pre.smallformat  { font-family:inherit; font-size:smaller }
  34.   pre.smallexample { font-size:smaller }
  35.   pre.smalllisp    { font-size:smaller }
  36.   span.sc    { font-variant:small-caps }
  37.   span.roman { font-family:serif; font-weight:normal; } 
  38.   span.sansserif { font-family:sans-serif; font-weight:normal; } 
  39. --></style>
  40. </head>
  41. <body>
  42. <h1 class="settitle">Bison 1.875</h1>
  43. <div class="contents">
  44. <h2>Table of Contents</h2>
  45. <ul>
  46. <li><a name="toc_Top" href="#Top">Bison</a>
  47. <li><a name="toc_Introduction" href="#Introduction">Introduction</a>
  48. <li><a name="toc_Conditions" href="#Conditions">Conditions for Using Bison</a>
  49. <li><a name="toc_Copying" href="#Copying">GNU GENERAL PUBLIC LICENSE</a>
  50. <ul>
  51. <li><a href="#Copying">Preamble</a>
  52. <li><a href="#Copying">Appendix: How to Apply These Terms to Your New Programs</a>
  53. </li></ul>
  54. <li><a name="toc_Concepts" href="#Concepts">1 The Concepts of Bison</a>
  55. <ul>
  56. <li><a href="#Language-and-Grammar">1.1 Languages and Context-Free Grammars</a>
  57. <li><a href="#Grammar-in-Bison">1.2 From Formal Rules to Bison Input</a>
  58. <li><a href="#Semantic-Values">1.3 Semantic Values</a>
  59. <li><a href="#Semantic-Actions">1.4 Semantic Actions</a>
  60. <li><a href="#GLR-Parsers">1.5 Writing <acronym>GLR</acronym> Parsers</a>
  61. <li><a href="#Locations-Overview">1.6 Locations</a>
  62. <li><a href="#Bison-Parser">1.7 Bison Output: the Parser File</a>
  63. <li><a href="#Stages">1.8 Stages in Using Bison</a>
  64. <li><a href="#Grammar-Layout">1.9 The Overall Layout of a Bison Grammar</a>
  65. </li></ul>
  66. <li><a name="toc_Examples" href="#Examples">2 Examples</a>
  67. <ul>
  68. <li><a href="#RPN-Calc">2.1 Reverse Polish Notation Calculator</a>
  69. <ul>
  70. <li><a href="#Rpcalc-Decls">2.1.1 Declarations for <code>rpcalc</code></a>
  71. <li><a href="#Rpcalc-Rules">2.1.2 Grammar Rules for <code>rpcalc</code></a>
  72. <ul>
  73. <li><a href="#Rpcalc-Input">2.1.2.1 Explanation of <code>input</code></a>
  74. <li><a href="#Rpcalc-Line">2.1.2.2 Explanation of <code>line</code></a>
  75. <li><a href="#Rpcalc-Expr">2.1.2.3 Explanation of <code>expr</code></a>
  76. </li></ul>
  77. <li><a href="#Rpcalc-Lexer">2.1.3 The <code>rpcalc</code> Lexical Analyzer</a>
  78. <li><a href="#Rpcalc-Main">2.1.4 The Controlling Function</a>
  79. <li><a href="#Rpcalc-Error">2.1.5 The Error Reporting Routine</a>
  80. <li><a href="#Rpcalc-Gen">2.1.6 Running Bison to Make the Parser</a>
  81. <li><a href="#Rpcalc-Compile">2.1.7 Compiling the Parser File</a>
  82. </li></ul>
  83. <li><a href="#Infix-Calc">2.2 Infix Notation Calculator: <code>calc</code></a>
  84. <li><a href="#Simple-Error-Recovery">2.3 Simple Error Recovery</a>
  85. <li><a href="#Location-Tracking-Calc">2.4 Location Tracking Calculator: <code>ltcalc</code></a>
  86. <ul>
  87. <li><a href="#Ltcalc-Decls">2.4.1 Declarations for <code>ltcalc</code></a>
  88. <li><a href="#Ltcalc-Rules">2.4.2 Grammar Rules for <code>ltcalc</code></a>
  89. <li><a href="#Ltcalc-Lexer">2.4.3 The <code>ltcalc</code> Lexical Analyzer.</a>
  90. </li></ul>
  91. <li><a href="#Multi_002dfunction-Calc">2.5 Multi-Function Calculator: <code>mfcalc</code></a>
  92. <ul>
  93. <li><a href="#Mfcalc-Decl">2.5.1 Declarations for <code>mfcalc</code></a>
  94. <li><a href="#Mfcalc-Rules">2.5.2 Grammar Rules for <code>mfcalc</code></a>
  95. <li><a href="#Mfcalc-Symtab">2.5.3 The <code>mfcalc</code> Symbol Table</a>
  96. </li></ul>
  97. <li><a href="#Exercises">2.6 Exercises</a>
  98. </li></ul>
  99. <li><a name="toc_Grammar-File" href="#Grammar-File">3 Bison Grammar Files</a>
  100. <ul>
  101. <li><a href="#Grammar-Outline">3.1 Outline of a Bison Grammar</a>
  102. <ul>
  103. <li><a href="#Prologue">3.1.1 The prologue</a>
  104. <li><a href="#Bison-Declarations">3.1.2 The Bison Declarations Section</a>
  105. <li><a href="#Grammar-Rules">3.1.3 The Grammar Rules Section</a>
  106. <li><a href="#Epilogue">3.1.4 The epilogue</a>
  107. </li></ul>
  108. <li><a href="#Symbols">3.2 Symbols, Terminal and Nonterminal</a>
  109. <li><a href="#Rules">3.3 Syntax of Grammar Rules</a>
  110. <li><a href="#Recursion">3.4 Recursive Rules</a>
  111. <li><a href="#Semantics">3.5 Defining Language Semantics</a>
  112. <ul>
  113. <li><a href="#Value-Type">3.5.1 Data Types of Semantic Values</a>
  114. <li><a href="#Multiple-Types">3.5.2 More Than One Value Type</a>
  115. <li><a href="#Actions">3.5.3 Actions</a>
  116. <li><a href="#Action-Types">3.5.4 Data Types of Values in Actions</a>
  117. <li><a href="#Mid_002dRule-Actions">3.5.5 Actions in Mid-Rule</a>
  118. </li></ul>
  119. <li><a href="#Locations">3.6 Tracking Locations</a>
  120. <ul>
  121. <li><a href="#Location-Type">3.6.1 Data Type of Locations</a>
  122. <li><a href="#Actions-and-Locations">3.6.2 Actions and Locations</a>
  123. <li><a href="#Location-Default-Action">3.6.3 Default Action for Locations</a>
  124. </li></ul>
  125. <li><a href="#Declarations">3.7 Bison Declarations</a>
  126. <ul>
  127. <li><a href="#Token-Decl">3.7.1 Token Type Names</a>
  128. <li><a href="#Precedence-Decl">3.7.2 Operator Precedence</a>
  129. <li><a href="#Union-Decl">3.7.3 The Collection of Value Types</a>
  130. <li><a href="#Type-Decl">3.7.4 Nonterminal Symbols</a>
  131. <li><a href="#Destructor-Decl">3.7.5 Freeing Discarded Symbols</a>
  132. <li><a href="#Expect-Decl">3.7.6 Suppressing Conflict Warnings</a>
  133. <li><a href="#Start-Decl">3.7.7 The Start-Symbol</a>
  134. <li><a href="#Pure-Decl">3.7.8 A Pure (Reentrant) Parser</a>
  135. <li><a href="#Decl-Summary">3.7.9 Bison Declaration Summary</a>
  136. </li></ul>
  137. <li><a href="#Multiple-Parsers">3.8 Multiple Parsers in the Same Program</a>
  138. </li></ul>
  139. <li><a name="toc_Interface" href="#Interface">4 Parser C-Language Interface</a>
  140. <ul>
  141. <li><a href="#Parser-Function">4.1 The Parser Function <code>yyparse</code></a>
  142. <li><a href="#Lexical">4.2 The Lexical Analyzer Function <code>yylex</code></a>
  143. <ul>
  144. <li><a href="#Calling-Convention">4.2.1 Calling Convention for <code>yylex</code></a>
  145. <li><a href="#Token-Values">4.2.2 Semantic Values of Tokens</a>
  146. <li><a href="#Token-Positions">4.2.3 Textual Positions of Tokens</a>
  147. <li><a href="#Pure-Calling">4.2.4 Calling Conventions for Pure Parsers</a>
  148. </li></ul>
  149. <li><a href="#Error-Reporting">4.3 The Error Reporting Function <code>yyerror</code></a>
  150. <li><a href="#Action-Features">4.4 Special Features for Use in Actions</a>
  151. </li></ul>
  152. <li><a name="toc_Algorithm" href="#Algorithm">5 The Bison Parser Algorithm</a>
  153. <ul>
  154. <li><a href="#Look_002dAhead">5.1 Look-Ahead Tokens</a>
  155. <li><a href="#Shift_002fReduce">5.2 Shift/Reduce Conflicts</a>
  156. <li><a href="#Precedence">5.3 Operator Precedence</a>
  157. <ul>
  158. <li><a href="#Why-Precedence">5.3.1 When Precedence is Needed</a>
  159. <li><a href="#Using-Precedence">5.3.2 Specifying Operator Precedence</a>
  160. <li><a href="#Precedence-Examples">5.3.3 Precedence Examples</a>
  161. <li><a href="#How-Precedence">5.3.4 How Precedence Works</a>
  162. </li></ul>
  163. <li><a href="#Contextual-Precedence">5.4 Context-Dependent Precedence</a>
  164. <li><a href="#Parser-States">5.5 Parser States</a>
  165. <li><a href="#Reduce_002fReduce">5.6 Reduce/Reduce Conflicts</a>
  166. <li><a href="#Mystery-Conflicts">5.7 Mysterious Reduce/Reduce Conflicts</a>
  167. <li><a href="#Generalized-LR-Parsing">5.8 Generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) Parsing</a>
  168. <li><a href="#Stack-Overflow">5.9 Stack Overflow, and How to Avoid It</a>
  169. </li></ul>
  170. <li><a name="toc_Error-Recovery" href="#Error-Recovery">6 Error Recovery</a>
  171. <li><a name="toc_Context-Dependency" href="#Context-Dependency">7 Handling Context Dependencies</a>
  172. <ul>
  173. <li><a href="#Semantic-Tokens">7.1 Semantic Info in Token Types</a>
  174. <li><a href="#Lexical-Tie_002dins">7.2 Lexical Tie-ins</a>
  175. <li><a href="#Tie_002din-Recovery">7.3 Lexical Tie-ins and Error Recovery</a>
  176. </li></ul>
  177. <li><a name="toc_Debugging" href="#Debugging">8 Debugging Your Parser</a>
  178. <ul>
  179. <li><a href="#Understanding">8.1 Understanding Your Parser</a>
  180. <li><a href="#Tracing">8.2 Tracing Your Parser</a>
  181. </li></ul>
  182. <li><a name="toc_Invocation" href="#Invocation">9 Invoking Bison</a>
  183. <ul>
  184. <li><a href="#Bison-Options">9.1 Bison Options</a>
  185. <li><a href="#Option-Cross-Key">9.2 Option Cross Key</a>
  186. <li><a href="#Yacc-Library">9.3 Yacc Library</a>
  187. </li></ul>
  188. <li><a name="toc_FAQ" href="#FAQ">10 Frequently Asked Questions</a>
  189. <ul>
  190. <li><a href="#Parser-Stack-Overflow">10.1 Parser Stack Overflow</a>
  191. </li></ul>
  192. <li><a name="toc_Table-of-Symbols" href="#Table-of-Symbols">Appendix A Bison Symbols</a>
  193. <li><a name="toc_Glossary" href="#Glossary">Appendix B Glossary</a>
  194. <li><a name="toc_Copying-This-Manual" href="#Copying-This-Manual">Appendix C Copying This Manual</a>
  195. <ul>
  196. <li><a href="#GNU-Free-Documentation-License">C.1 GNU Free Documentation License</a>
  197. <ul>
  198. <li><a href="#GNU-Free-Documentation-License">C.1.1 ADDENDUM: How to use this License for your documents</a>
  199. </li></ul>
  200. </li></ul>
  201. <li><a name="toc_Index" href="#Index">Index</a>
  202. </li></ul>
  203. </div>
  204.  
  205.  
  206.  
  207. <div class="node">
  208. <p><hr>
  209. <a name="Top"></a>
  210. Next: <a rel="next" accesskey="n" href="#Introduction">Introduction</a>,
  211. Up: <a rel="up" accesskey="u" href="#dir">(dir)</a>
  212.  
  213. </div>
  214.  
  215. <h2 class="unnumbered">Bison</h2>
  216.  
  217. <p>This manual is for <acronym>GNU</acronym> Bison (version 1.875,
  218. 28 December 2002), the <acronym>GNU</acronym> parser generator.
  219.  
  220.    <p>Copyright © 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
  221. 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
  222.  
  223.    <blockquote>
  224. Permission is granted to copy, distribute and/or modify this document
  225. under the terms of the <acronym>GNU</acronym> Free Documentation License,
  226. Version 1.1 or any later version published by the Free Software
  227. Foundation; with no Invariant Sections, with the Front-Cover texts
  228. being “A <acronym>GNU</acronym> Manual,” and with the Back-Cover Texts as in
  229. (a) below.  A copy of the license is included in the section entitled
  230. “<acronym>GNU</acronym> Free Documentation License.”
  231.  
  232.         <p>(a) The <acronym>FSF</acronym>'s Back-Cover Text is: “You have freedom to copy
  233. and modify this <acronym>GNU</acronym> Manual, like <acronym>GNU</acronym> software. 
  234. Copies published by the Free Software Foundation raise funds for
  235. <acronym>GNU</acronym> development.”
  236. </blockquote>
  237.  
  238. <ul class="menu">
  239. <li><a accesskey="1" href="#Introduction">Introduction</a>
  240. <li><a accesskey="2" href="#Conditions">Conditions</a>
  241. <li><a accesskey="3" href="#Copying">Copying</a>:            The <acronym>GNU</acronym> General Public License says
  242.                         how you can copy and share Bison
  243.  
  244. </li></ul>
  245. <p>Tutorial sections:
  246. </p>
  247. <ul class="menu">
  248. <li><a accesskey="4" href="#Concepts">Concepts</a>:           Basic concepts for understanding Bison. 
  249. <li><a accesskey="5" href="#Examples">Examples</a>:           Three simple explained examples of using Bison.
  250.  
  251. </li></ul>
  252. <p>Reference sections:
  253. </p>
  254. <ul class="menu">
  255. <li><a accesskey="6" href="#Grammar-File">Grammar File</a>:       Writing Bison declarations and rules. 
  256. <li><a accesskey="7" href="#Interface">Interface</a>:          C-language interface to the parser function <code>yyparse</code>. 
  257. <li><a accesskey="8" href="#Algorithm">Algorithm</a>:          How the Bison parser works at run-time. 
  258. <li><a accesskey="9" href="#Error-Recovery">Error Recovery</a>:     Writing rules for error recovery. 
  259. <li><a href="#Context-Dependency">Context Dependency</a>:   What to do if your language syntax is too
  260.                         messy for Bison to handle straightforwardly. 
  261. <li><a href="#Debugging">Debugging</a>:          Understanding or debugging Bison parsers. 
  262. <li><a href="#Invocation">Invocation</a>:         How to run Bison (to produce the parser source file). 
  263. <li><a href="#Table-of-Symbols">Table of Symbols</a>:   All the keywords of the Bison language are explained. 
  264. <li><a href="#Glossary">Glossary</a>:           Basic concepts are explained. 
  265. <li><a href="#FAQ">FAQ</a>:                Frequently Asked Questions
  266. <li><a href="#Copying-This-Manual">Copying This Manual</a>:   License for copying this manual. 
  267. <li><a href="#Index">Index</a>:              Cross-references to the text.
  268.  
  269. </li></ul>
  270. <p>--- The Detailed Node Listing ---
  271.  
  272. <p>The Concepts of Bison
  273.  
  274. </p>
  275. <ul class="menu">
  276. <li><a href="#Language-and-Grammar">Language and Grammar</a>:   Languages and context-free grammars,
  277.                             as mathematical ideas. 
  278. <li><a href="#Grammar-in-Bison">Grammar in Bison</a>:   How we represent grammars for Bison's sake. 
  279. <li><a href="#Semantic-Values">Semantic Values</a>:    Each token or syntactic grouping can have
  280.                         a semantic value (the value of an integer,
  281.                         the name of an identifier, etc.). 
  282. <li><a href="#Semantic-Actions">Semantic Actions</a>:   Each rule can have an action containing C code. 
  283. <li><a href="#GLR-Parsers">GLR Parsers</a>:        Writing parsers for general context-free languages
  284. <li><a href="#Locations-Overview">Locations Overview</a>:     Tracking Locations. 
  285. <li><a href="#Bison-Parser">Bison Parser</a>:       What are Bison's input and output,
  286.                         how is the output used? 
  287. <li><a href="#Stages">Stages</a>:             Stages in writing and running Bison grammars. 
  288. <li><a href="#Grammar-Layout">Grammar Layout</a>:     Overall structure of a Bison grammar file.
  289.  
  290. </li></ul>
  291. <p>Examples
  292.  
  293. </p>
  294. <ul class="menu">
  295. <li><a href="#RPN-Calc">RPN Calc</a>:           Reverse polish notation calculator;
  296.                         a first example with no operator precedence. 
  297. <li><a href="#Infix-Calc">Infix Calc</a>:         Infix (algebraic) notation calculator. 
  298.                         Operator precedence is introduced. 
  299. <li><a href="#Simple-Error-Recovery">Simple Error Recovery</a>:   Continuing after syntax errors. 
  300. <li><a href="#Location-Tracking-Calc">Location Tracking Calc</a>:  Demonstrating the use of @<var>n</var> and @$. 
  301. <li><a href="#Multi_002dfunction-Calc">Multi-function Calc</a>:   Calculator with memory and trig functions. 
  302.                            It uses multiple data-types for semantic values. 
  303. <li><a href="#Exercises">Exercises</a>:          Ideas for improving the multi-function calculator.
  304.  
  305. </li></ul>
  306. <p>Reverse Polish Notation Calculator
  307.  
  308. </p>
  309. <ul class="menu">
  310. <li><a href="#Rpcalc-Decls">Decls</a>:   Prologue (declarations) for rpcalc. 
  311. <li><a href="#Rpcalc-Rules">Rules</a>:   Grammar Rules for rpcalc, with explanation. 
  312. <li><a href="#Rpcalc-Lexer">Lexer</a>:   The lexical analyzer. 
  313. <li><a href="#Rpcalc-Main">Main</a>:     The controlling function. 
  314. <li><a href="#Rpcalc-Error">Error</a>:   The error reporting function. 
  315. <li><a href="#Rpcalc-Gen">Gen</a>:       Running Bison on the grammar file. 
  316. <li><a href="#Rpcalc-Compile">Comp</a>:  Run the C compiler on the output code.
  317.  
  318. </li></ul>
  319. <p>Grammar Rules for <code>rpcalc</code>
  320.  
  321. </p>
  322. <ul class="menu">
  323. <li><a href="#Rpcalc-Input">Rpcalc Input</a>
  324. <li><a href="#Rpcalc-Line">Rpcalc Line</a>
  325. <li><a href="#Rpcalc-Expr">Rpcalc Expr</a>
  326.  
  327. </li></ul>
  328. <p>Location Tracking Calculator: <code>ltcalc</code>
  329.  
  330. </p>
  331. <ul class="menu">
  332. <li><a href="#Ltcalc-Decls">Decls</a>:   Bison and C declarations for ltcalc. 
  333. <li><a href="#Ltcalc-Rules">Rules</a>:   Grammar rules for ltcalc, with explanations. 
  334. <li><a href="#Ltcalc-Lexer">Lexer</a>:   The lexical analyzer.
  335.  
  336. </li></ul>
  337. <p>Multi-Function Calculator: <code>mfcalc</code>
  338.  
  339. </p>
  340. <ul class="menu">
  341. <li><a href="#Mfcalc-Decl">Decl</a>:       Bison declarations for multi-function calculator. 
  342. <li><a href="#Mfcalc-Rules">Rules</a>:     Grammar rules for the calculator. 
  343. <li><a href="#Mfcalc-Symtab">Symtab</a>:   Symbol table management subroutines.
  344.  
  345. </li></ul>
  346. <p>Bison Grammar Files
  347.  
  348. </p>
  349. <ul class="menu">
  350. <li><a href="#Grammar-Outline">Grammar Outline</a>:    Overall layout of the grammar file. 
  351. <li><a href="#Symbols">Symbols</a>:            Terminal and nonterminal symbols. 
  352. <li><a href="#Rules">Rules</a>:              How to write grammar rules. 
  353. <li><a href="#Recursion">Recursion</a>:          Writing recursive rules. 
  354. <li><a href="#Semantics">Semantics</a>:          Semantic values and actions. 
  355. <li><a href="#Locations">Locations</a>:          Locations and actions. 
  356. <li><a href="#Declarations">Declarations</a>:       All kinds of Bison declarations are described here. 
  357. <li><a href="#Multiple-Parsers">Multiple Parsers</a>:   Putting more than one Bison parser in one program.
  358.  
  359. </li></ul>
  360. <p>Outline of a Bison Grammar
  361.  
  362. </p>
  363. <ul class="menu">
  364. <li><a href="#Prologue">Prologue</a>:           Syntax and usage of the prologue. 
  365. <li><a href="#Bison-Declarations">Bison Declarations</a>:   Syntax and usage of the Bison declarations section. 
  366. <li><a href="#Grammar-Rules">Grammar Rules</a>:      Syntax and usage of the grammar rules section. 
  367. <li><a href="#Epilogue">Epilogue</a>:           Syntax and usage of the epilogue.
  368.  
  369. </li></ul>
  370. <p>Defining Language Semantics
  371.  
  372. </p>
  373. <ul class="menu">
  374. <li><a href="#Value-Type">Value Type</a>:         Specifying one data type for all semantic values. 
  375. <li><a href="#Multiple-Types">Multiple Types</a>:     Specifying several alternative data types. 
  376. <li><a href="#Actions">Actions</a>:            An action is the semantic definition of a grammar rule. 
  377. <li><a href="#Action-Types">Action Types</a>:       Specifying data types for actions to operate on. 
  378. <li><a href="#Mid_002dRule-Actions">Mid-Rule Actions</a>:   Most actions go at the end of a rule. 
  379.                       This says when, why and how to use the exceptional
  380.                         action in the middle of a rule.
  381.  
  382. </li></ul>
  383. <p>Tracking Locations
  384.  
  385. </p>
  386. <ul class="menu">
  387. <li><a href="#Location-Type">Location Type</a>:                Specifying a data type for locations. 
  388. <li><a href="#Actions-and-Locations">Actions and Locations</a>:        Using locations in actions. 
  389. <li><a href="#Location-Default-Action">Location Default Action</a>:      Defining a general way to compute locations.
  390.  
  391. </li></ul>
  392. <p>Bison Declarations
  393.  
  394. </p>
  395. <ul class="menu">
  396. <li><a href="#Token-Decl">Token Decl</a>:         Declaring terminal symbols. 
  397. <li><a href="#Precedence-Decl">Precedence Decl</a>:    Declaring terminals with precedence and associativity. 
  398. <li><a href="#Union-Decl">Union Decl</a>:         Declaring the set of all semantic value types. 
  399. <li><a href="#Type-Decl">Type Decl</a>:          Declaring the choice of type for a nonterminal symbol. 
  400. <li><a href="#Destructor-Decl">Destructor Decl</a>:    Declaring how symbols are freed. 
  401. <li><a href="#Expect-Decl">Expect Decl</a>:        Suppressing warnings about shift/reduce conflicts. 
  402. <li><a href="#Start-Decl">Start Decl</a>:         Specifying the start symbol. 
  403. <li><a href="#Pure-Decl">Pure Decl</a>:          Requesting a reentrant parser. 
  404. <li><a href="#Decl-Summary">Decl Summary</a>:       Table of all Bison declarations.
  405.  
  406. </li></ul>
  407. <p>Parser C-Language Interface
  408.  
  409. </p>
  410. <ul class="menu">
  411. <li><a href="#Parser-Function">Parser Function</a>:    How to call <code>yyparse</code> and what it returns. 
  412. <li><a href="#Lexical">Lexical</a>:            You must supply a function <code>yylex</code>
  413.                         which reads tokens. 
  414. <li><a href="#Error-Reporting">Error Reporting</a>:    You must supply a function <code>yyerror</code>. 
  415. <li><a href="#Action-Features">Action Features</a>:    Special features for use in actions.
  416.  
  417. </li></ul>
  418. <p>The Lexical Analyzer Function <code>yylex</code>
  419.  
  420. </p>
  421. <ul class="menu">
  422. <li><a href="#Calling-Convention">Calling Convention</a>:   How <code>yyparse</code> calls <code>yylex</code>. 
  423. <li><a href="#Token-Values">Token Values</a>:       How <code>yylex</code> must return the semantic value
  424.                         of the token it has read. 
  425. <li><a href="#Token-Positions">Token Positions</a>:    How <code>yylex</code> must return the text position
  426.                         (line number, etc.) of the token, if the
  427.                         actions want that. 
  428. <li><a href="#Pure-Calling">Pure Calling</a>:       How the calling convention differs
  429.                         in a pure parser (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>).
  430.  
  431. </li></ul>
  432. <p>The Bison Parser Algorithm
  433.  
  434. </p>
  435. <ul class="menu">
  436. <li><a href="#Look_002dAhead">Look-Ahead</a>:         Parser looks one token ahead when deciding what to do. 
  437. <li><a href="#Shift_002fReduce">Shift/Reduce</a>:       Conflicts: when either shifting or reduction is valid. 
  438. <li><a href="#Precedence">Precedence</a>:         Operator precedence works by resolving conflicts. 
  439. <li><a href="#Contextual-Precedence">Contextual Precedence</a>:   When an operator's precedence depends on context. 
  440. <li><a href="#Parser-States">Parser States</a>:      The parser is a finite-state-machine with stack. 
  441. <li><a href="#Reduce_002fReduce">Reduce/Reduce</a>:      When two rules are applicable in the same situation. 
  442. <li><a href="#Mystery-Conflicts">Mystery Conflicts</a>:   Reduce/reduce conflicts that look unjustified. 
  443. <li><a href="#Generalized-LR-Parsing">Generalized LR Parsing</a>:   Parsing arbitrary context-free grammars. 
  444. <li><a href="#Stack-Overflow">Stack Overflow</a>:     What happens when stack gets full.  How to avoid it.
  445.  
  446. </li></ul>
  447. <p>Operator Precedence
  448.  
  449. </p>
  450. <ul class="menu">
  451. <li><a href="#Why-Precedence">Why Precedence</a>:     An example showing why precedence is needed. 
  452. <li><a href="#Using-Precedence">Using Precedence</a>:   How to specify precedence in Bison grammars. 
  453. <li><a href="#Precedence-Examples">Precedence Examples</a>:   How these features are used in the previous example. 
  454. <li><a href="#How-Precedence">How Precedence</a>:     How they work.
  455.  
  456. </li></ul>
  457. <p>Handling Context Dependencies
  458.  
  459. </p>
  460. <ul class="menu">
  461. <li><a href="#Semantic-Tokens">Semantic Tokens</a>:    Token parsing can depend on the semantic context. 
  462. <li><a href="#Lexical-Tie_002dins">Lexical Tie-ins</a>:    Token parsing can depend on the syntactic context. 
  463. <li><a href="#Tie_002din-Recovery">Tie-in Recovery</a>:    Lexical tie-ins have implications for how
  464.                         error recovery rules must be written.
  465.  
  466. </li></ul>
  467. <p>Debugging Your Parser
  468.  
  469. </p>
  470. <ul class="menu">
  471. <li><a href="#Understanding">Understanding</a>:      Understanding the structure of your parser. 
  472. <li><a href="#Tracing">Tracing</a>:            Tracing the execution of your parser.
  473.  
  474. </li></ul>
  475. <p>Invoking Bison
  476.  
  477. </p>
  478. <ul class="menu">
  479. <li><a href="#Bison-Options">Bison Options</a>:      All the options described in detail,
  480.                         in alphabetical order by short options. 
  481. <li><a href="#Option-Cross-Key">Option Cross Key</a>:   Alphabetical list of long options. 
  482. <li><a href="#Yacc-Library">Yacc Library</a>:       Yacc-compatible <code>yylex</code> and <code>main</code>.
  483.  
  484. </li></ul>
  485. <p>Frequently Asked Questions
  486.  
  487. </p>
  488. <ul class="menu">
  489. <li><a href="#Parser-Stack-Overflow">Parser Stack Overflow</a>:       Breaking the Stack Limits
  490.  
  491. </li></ul>
  492. <p>Copying This Manual
  493.  
  494. </p>
  495. <ul class="menu">
  496. <li><a href="#GNU-Free-Documentation-License">GNU Free Documentation License</a>:   License for copying this manual.
  497.  
  498.    </ul>
  499.  
  500. <div class="node">
  501. <p><hr>
  502. <a name="Introduction"></a>
  503. Next: <a rel="next" accesskey="n" href="#Conditions">Conditions</a>,
  504. Previous: <a rel="previous" accesskey="p" href="#Top">Top</a>,
  505. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  506.  
  507. </div>
  508.  
  509. <h2 class="unnumbered">Introduction</h2>
  510.  
  511. <p><a name="index-introduction-1"></a>
  512. <dfn>Bison</dfn> is a general-purpose parser generator that converts a
  513. grammar description for an <acronym>LALR</acronym>(1) context-free grammar into a C
  514. program to parse that grammar.  Once you are proficient with Bison,
  515. you may use it to develop a wide range of language parsers, from those
  516. used in simple desk calculators to complex programming languages.
  517.  
  518.    <p>Bison is upward compatible with Yacc: all properly-written Yacc grammars
  519. ought to work with Bison with no change.  Anyone familiar with Yacc
  520. should be able to use Bison with little trouble.  You need to be fluent in
  521. C programming in order to use Bison or to understand this manual.
  522.  
  523.    <p>We begin with tutorial chapters that explain the basic concepts of using
  524. Bison and show three explained examples, each building on the last.  If you
  525. don't know Bison or Yacc, start by reading these chapters.  Reference
  526. chapters follow which describe specific aspects of Bison in detail.
  527.  
  528.    <p>Bison was written primarily by Robert Corbett; Richard Stallman made it
  529. Yacc-compatible.  Wilfred Hansen of Carnegie Mellon University added
  530. multi-character string literals and other features.
  531.  
  532.    <p>This edition corresponds to version 1.875 of Bison.
  533.  
  534. <div class="node">
  535. <p><hr>
  536. <a name="Conditions"></a>
  537. Next: <a rel="next" accesskey="n" href="#Copying">Copying</a>,
  538. Previous: <a rel="previous" accesskey="p" href="#Introduction">Introduction</a>,
  539. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  540.  
  541. </div>
  542.  
  543. <h2 class="unnumbered">Conditions for Using Bison</h2>
  544.  
  545. <p>As of Bison version 1.24, we have changed the distribution terms for
  546. <code>yyparse</code> to permit using Bison's output in nonfree programs when
  547. Bison is generating C code for <acronym>LALR</acronym>(1) parsers.  Formerly, these
  548. parsers could be used only in programs that were free software.
  549.  
  550.    <p>The other <acronym>GNU</acronym> programming tools, such as the <acronym>GNU</acronym> C
  551. compiler, have never
  552. had such a requirement.  They could always be used for nonfree
  553. software.  The reason Bison was different was not due to a special
  554. policy decision; it resulted from applying the usual General Public
  555. License to all of the Bison source code.
  556.  
  557.    <p>The output of the Bison utility—the Bison parser file—contains a
  558. verbatim copy of a sizable piece of Bison, which is the code for the
  559. <code>yyparse</code> function.  (The actions from your grammar are inserted
  560. into this function at one point, but the rest of the function is not
  561. changed.)  When we applied the <acronym>GPL</acronym> terms to the code for
  562. <code>yyparse</code>,
  563. the effect was to restrict the use of Bison output to free software.
  564.  
  565.    <p>We didn't change the terms because of sympathy for people who want to
  566. make software proprietary.  <strong>Software should be free.</strong>  But we
  567. concluded that limiting Bison's use to free software was doing little to
  568. encourage people to make other software free.  So we decided to make the
  569. practical conditions for using Bison match the practical conditions for
  570. using the other <acronym>GNU</acronym> tools.
  571.  
  572.    <p>This exception applies only when Bison is generating C code for a
  573. <acronym>LALR</acronym>(1) parser; otherwise, the <acronym>GPL</acronym> terms operate
  574. as usual.  You can
  575. tell whether the exception applies to your `<samp><span class="samp">.c</span></samp>' output file by
  576. inspecting it to see whether it says “As a special exception, when
  577. this file is copied by Bison into a Bison output file, you may use
  578. that output file without restriction.”
  579.  
  580. <div class="node">
  581. <p><hr>
  582. <a name="Copying"></a>
  583. Next: <a rel="next" accesskey="n" href="#Concepts">Concepts</a>,
  584. Previous: <a rel="previous" accesskey="p" href="#Conditions">Conditions</a>,
  585. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  586.  
  587. </div>
  588.  
  589. <h2 class="unnumbered">GNU GENERAL PUBLIC LICENSE</h2>
  590.  
  591. <div align="center">Version 2, June 1991</div>
  592.  
  593. <!-- This file is intended to be included in another file. -->
  594. <pre class="display">     Copyright © 1989, 1991 Free Software Foundation, Inc.
  595.      59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
  596.      
  597.      Everyone is permitted to copy and distribute verbatim copies
  598.      of this license document, but changing it is not allowed.
  599. </pre>
  600.    <h3 class="unnumberedsec">Preamble</h3>
  601.  
  602. <p>The licenses for most software are designed to take away your
  603. freedom to share and change it.  By contrast, the GNU General Public
  604. License is intended to guarantee your freedom to share and change free
  605. software—to make sure the software is free for all its users.  This
  606. General Public License applies to most of the Free Software
  607. Foundation's software and to any other program whose authors commit to
  608. using it.  (Some other Free Software Foundation software is covered by
  609. the GNU Library General Public License instead.)  You can apply it to
  610. your programs, too.
  611.  
  612.    <p>When we speak of free software, we are referring to freedom, not
  613. price.  Our General Public Licenses are designed to make sure that you
  614. have the freedom to distribute copies of free software (and charge for
  615. this service if you wish), that you receive source code or can get it
  616. if you want it, that you can change the software or use pieces of it
  617. in new free programs; and that you know you can do these things.
  618.  
  619.    <p>To protect your rights, we need to make restrictions that forbid
  620. anyone to deny you these rights or to ask you to surrender the rights. 
  621. These restrictions translate to certain responsibilities for you if you
  622. distribute copies of the software, or if you modify it.
  623.  
  624.    <p>For example, if you distribute copies of such a program, whether
  625. gratis or for a fee, you must give the recipients all the rights that
  626. you have.  You must make sure that they, too, receive or can get the
  627. source code.  And you must show them these terms so they know their
  628. rights.
  629.  
  630.    <p>We protect your rights with two steps: (1) copyright the software, and
  631. (2) offer you this license which gives you legal permission to copy,
  632. distribute and/or modify the software.
  633.  
  634.    <p>Also, for each author's protection and ours, we want to make certain
  635. that everyone understands that there is no warranty for this free
  636. software.  If the software is modified by someone else and passed on, we
  637. want its recipients to know that what they have is not the original, so
  638. that any problems introduced by others will not reflect on the original
  639. authors' reputations.
  640.  
  641.    <p>Finally, any free program is threatened constantly by software
  642. patents.  We wish to avoid the danger that redistributors of a free
  643. program will individually obtain patent licenses, in effect making the
  644. program proprietary.  To prevent this, we have made it clear that any
  645. patent must be licensed for everyone's free use or not licensed at all.
  646.  
  647.    <p>The precise terms and conditions for copying, distribution and
  648. modification follow.
  649.  
  650.      <ol type=1 start=0>
  651. <li>This License applies to any program or other work which contains
  652. a notice placed by the copyright holder saying it may be distributed
  653. under the terms of this General Public License.  The “Program”, below,
  654. refers to any such program or work, and a “work based on the Program”
  655. means either the Program or any derivative work under copyright law:
  656. that is to say, a work containing the Program or a portion of it,
  657. either verbatim or with modifications and/or translated into another
  658. language.  (Hereinafter, translation is included without limitation in
  659. the term “modification”.)  Each licensee is addressed as “you”.
  660.  
  661.      <p>Activities other than copying, distribution and modification are not
  662. covered by this License; they are outside its scope.  The act of
  663. running the Program is not restricted, and the output from the Program
  664. is covered only if its contents constitute a work based on the
  665. Program (independent of having been made by running the Program). 
  666. Whether that is true depends on what the Program does.
  667.  
  668.      <li>You may copy and distribute verbatim copies of the Program's
  669. source code as you receive it, in any medium, provided that you
  670. conspicuously and appropriately publish on each copy an appropriate
  671. copyright notice and disclaimer of warranty; keep intact all the
  672. notices that refer to this License and to the absence of any warranty;
  673. and give any other recipients of the Program a copy of this License
  674. along with the Program.
  675.  
  676.      <p>You may charge a fee for the physical act of transferring a copy, and
  677. you may at your option offer warranty protection in exchange for a fee.
  678.  
  679.      <li>You may modify your copy or copies of the Program or any portion
  680. of it, thus forming a work based on the Program, and copy and
  681. distribute such modifications or work under the terms of Section 1
  682. above, provided that you also meet all of these conditions:
  683.  
  684.           <ol type=a start=1>
  685. <li>You must cause the modified files to carry prominent notices
  686. stating that you changed the files and the date of any change.
  687.  
  688.           <li>You must cause any work that you distribute or publish, that in
  689. whole or in part contains or is derived from the Program or any
  690. part thereof, to be licensed as a whole at no charge to all third
  691. parties under the terms of this License.
  692.  
  693.           <li>If the modified program normally reads commands interactively
  694. when run, you must cause it, when started running for such
  695. interactive use in the most ordinary way, to print or display an
  696. announcement including an appropriate copyright notice and a
  697. notice that there is no warranty (or else, saying that you provide
  698. a warranty) and that users may redistribute the program under
  699. these conditions, and telling the user how to view a copy of this
  700. License.  (Exception: if the Program itself is interactive but
  701. does not normally print such an announcement, your work based on
  702. the Program is not required to print an announcement.)
  703.           </ol>
  704.  
  705.      <p>These requirements apply to the modified work as a whole.  If
  706. identifiable sections of that work are not derived from the Program,
  707. and can be reasonably considered independent and separate works in
  708. themselves, then this License, and its terms, do not apply to those
  709. sections when you distribute them as separate works.  But when you
  710. distribute the same sections as part of a whole which is a work based
  711. on the Program, the distribution of the whole must be on the terms of
  712. this License, whose permissions for other licensees extend to the
  713. entire whole, and thus to each and every part regardless of who wrote it.
  714.  
  715.      <p>Thus, it is not the intent of this section to claim rights or contest
  716. your rights to work written entirely by you; rather, the intent is to
  717. exercise the right to control the distribution of derivative or
  718. collective works based on the Program.
  719.  
  720.      <p>In addition, mere aggregation of another work not based on the Program
  721. with the Program (or with a work based on the Program) on a volume of
  722. a storage or distribution medium does not bring the other work under
  723. the scope of this License.
  724.  
  725.      <li>You may copy and distribute the Program (or a work based on it,
  726. under Section 2) in object code or executable form under the terms of
  727. Sections 1 and 2 above provided that you also do one of the following:
  728.  
  729.           <ol type=a start=1>
  730. <li>Accompany it with the complete corresponding machine-readable
  731. source code, which must be distributed under the terms of Sections
  732. 1 and 2 above on a medium customarily used for software interchange; or,
  733.  
  734.           <li>Accompany it with a written offer, valid for at least three
  735. years, to give any third party, for a charge no more than your
  736. cost of physically performing source distribution, a complete
  737. machine-readable copy of the corresponding source code, to be
  738. distributed under the terms of Sections 1 and 2 above on a medium
  739. customarily used for software interchange; or,
  740.  
  741.           <li>Accompany it with the information you received as to the offer
  742. to distribute corresponding source code.  (This alternative is
  743. allowed only for noncommercial distribution and only if you
  744. received the program in object code or executable form with such
  745. an offer, in accord with Subsection b above.)
  746.           </ol>
  747.  
  748.      <p>The source code for a work means the preferred form of the work for
  749. making modifications to it.  For an executable work, complete source
  750. code means all the source code for all modules it contains, plus any
  751. associated interface definition files, plus the scripts used to
  752. control compilation and installation of the executable.  However, as a
  753. special exception, the source code distributed need not include
  754. anything that is normally distributed (in either source or binary
  755. form) with the major components (compiler, kernel, and so on) of the
  756. operating system on which the executable runs, unless that component
  757. itself accompanies the executable.
  758.  
  759.      <p>If distribution of executable or object code is made by offering
  760. access to copy from a designated place, then offering equivalent
  761. access to copy the source code from the same place counts as
  762. distribution of the source code, even though third parties are not
  763. compelled to copy the source along with the object code.
  764.  
  765.      <li>You may not copy, modify, sublicense, or distribute the Program
  766. except as expressly provided under this License.  Any attempt
  767. otherwise to copy, modify, sublicense or distribute the Program is
  768. void, and will automatically terminate your rights under this License. 
  769. However, parties who have received copies, or rights, from you under
  770. this License will not have their licenses terminated so long as such
  771. parties remain in full compliance.
  772.  
  773.      <li>You are not required to accept this License, since you have not
  774. signed it.  However, nothing else grants you permission to modify or
  775. distribute the Program or its derivative works.  These actions are
  776. prohibited by law if you do not accept this License.  Therefore, by
  777. modifying or distributing the Program (or any work based on the
  778. Program), you indicate your acceptance of this License to do so, and
  779. all its terms and conditions for copying, distributing or modifying
  780. the Program or works based on it.
  781.  
  782.      <li>Each time you redistribute the Program (or any work based on the
  783. Program), the recipient automatically receives a license from the
  784. original licensor to copy, distribute or modify the Program subject to
  785. these terms and conditions.  You may not impose any further
  786. restrictions on the recipients' exercise of the rights granted herein. 
  787. You are not responsible for enforcing compliance by third parties to
  788. this License.
  789.  
  790.      <li>If, as a consequence of a court judgment or allegation of patent
  791. infringement or for any other reason (not limited to patent issues),
  792. conditions are imposed on you (whether by court order, agreement or
  793. otherwise) that contradict the conditions of this License, they do not
  794. excuse you from the conditions of this License.  If you cannot
  795. distribute so as to satisfy simultaneously your obligations under this
  796. License and any other pertinent obligations, then as a consequence you
  797. may not distribute the Program at all.  For example, if a patent
  798. license would not permit royalty-free redistribution of the Program by
  799. all those who receive copies directly or indirectly through you, then
  800. the only way you could satisfy both it and this License would be to
  801. refrain entirely from distribution of the Program.
  802.  
  803.      <p>If any portion of this section is held invalid or unenforceable under
  804. any particular circumstance, the balance of the section is intended to
  805. apply and the section as a whole is intended to apply in other
  806. circumstances.
  807.  
  808.      <p>It is not the purpose of this section to induce you to infringe any
  809. patents or other property right claims or to contest validity of any
  810. such claims; this section has the sole purpose of protecting the
  811. integrity of the free software distribution system, which is
  812. implemented by public license practices.  Many people have made
  813. generous contributions to the wide range of software distributed
  814. through that system in reliance on consistent application of that
  815. system; it is up to the author/donor to decide if he or she is willing
  816. to distribute software through any other system and a licensee cannot
  817. impose that choice.
  818.  
  819.      <p>This section is intended to make thoroughly clear what is believed to
  820. be a consequence of the rest of this License.
  821.  
  822.      <li>If the distribution and/or use of the Program is restricted in
  823. certain countries either by patents or by copyrighted interfaces, the
  824. original copyright holder who places the Program under this License
  825. may add an explicit geographical distribution limitation excluding
  826. those countries, so that distribution is permitted only in or among
  827. countries not thus excluded.  In such case, this License incorporates
  828. the limitation as if written in the body of this License.
  829.  
  830.      <li>The Free Software Foundation may publish revised and/or new versions
  831. of the General Public License from time to time.  Such new versions will
  832. be similar in spirit to the present version, but may differ in detail to
  833. address new problems or concerns.
  834.  
  835.      <p>Each version is given a distinguishing version number.  If the Program
  836. specifies a version number of this License which applies to it and “any
  837. later version”, you have the option of following the terms and conditions
  838. either of that version or of any later version published by the Free
  839. Software Foundation.  If the Program does not specify a version number of
  840. this License, you may choose any version ever published by the Free Software
  841. Foundation.
  842.  
  843.      <li>If you wish to incorporate parts of the Program into other free
  844. programs whose distribution conditions are different, write to the author
  845. to ask for permission.  For software which is copyrighted by the Free
  846. Software Foundation, write to the Free Software Foundation; we sometimes
  847. make exceptions for this.  Our decision will be guided by the two goals
  848. of preserving the free status of all derivatives of our free software and
  849. of promoting the sharing and reuse of software generally.
  850.  
  851.      <li>BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  852. FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  853. OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  854. PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  855. OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  856. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  857. TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  858. PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  859. REPAIR OR CORRECTION.
  860.  
  861.      <li>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  862. WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  863. REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  864. INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  865. OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  866. TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  867. YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  868. PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  869. POSSIBILITY OF SUCH DAMAGES.
  870.         </ol>
  871.  
  872. <h3 class="unnumberedsec">Appendix: How to Apply These Terms to Your New Programs</h3>
  873.  
  874. <p>If you develop a new program, and you want it to be of the greatest
  875. possible use to the public, the best way to achieve this is to make it
  876. free software which everyone can redistribute and change under these terms.
  877.  
  878.    <p>To do so, attach the following notices to the program.  It is safest
  879. to attach them to the start of each source file to most effectively
  880. convey the exclusion of warranty; and each file should have at least
  881. the “copyright” line and a pointer to where the full notice is found.
  882.  
  883. <pre class="smallexample">     <var>one line to give the program's name and a brief idea of what it does.</var>
  884.      Copyright (C) <var>yyyy</var>  <var>name of author</var>
  885.      
  886.      This program is free software; you can redistribute it and/or modify
  887.      it under the terms of the GNU General Public License as published by
  888.      the Free Software Foundation; either version 2 of the License, or
  889.      (at your option) any later version.
  890.      
  891.      This program is distributed in the hope that it will be useful,
  892.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  893.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  894.      GNU General Public License for more details.
  895.      
  896.      You should have received a copy of the GNU General Public License
  897.      along with this program; if not, write to the Free Software
  898.      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  899. </pre>
  900.    <p>Also add information on how to contact you by electronic and paper mail.
  901.  
  902.    <p>If the program is interactive, make it output a short notice like this
  903. when it starts in an interactive mode:
  904.  
  905. <pre class="smallexample">     Gnomovision version 69, Copyright (C) 19<var>yy</var> <var>name of author</var>
  906.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  907.      This is free software, and you are welcome to redistribute it
  908.      under certain conditions; type `show c' for details.
  909. </pre>
  910.    <p>The hypothetical commands `<samp><span class="samp">show w</span></samp>' and `<samp><span class="samp">show c</span></samp>' should show
  911. the appropriate parts of the General Public License.  Of course, the
  912. commands you use may be called something other than `<samp><span class="samp">show w</span></samp>' and
  913. `<samp><span class="samp">show c</span></samp>'; they could even be mouse-clicks or menu items—whatever
  914. suits your program.
  915.  
  916.    <p>You should also get your employer (if you work as a programmer) or your
  917. school, if any, to sign a “copyright disclaimer” for the program, if
  918. necessary.  Here is a sample; alter the names:
  919.  
  920. <pre class="example">     Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  921.      `Gnomovision' (which makes passes at compilers) written by James Hacker.
  922.      
  923.      <var>signature of Ty Coon</var>, 1 April 1989
  924.      Ty Coon, President of Vice
  925. </pre>
  926.    <p>This General Public License does not permit incorporating your program into
  927. proprietary programs.  If your program is a subroutine library, you may
  928. consider it more useful to permit linking proprietary applications with the
  929. library.  If this is what you want to do, use the GNU Library General
  930. Public License instead of this License.
  931.  
  932. <div class="node">
  933. <p><hr>
  934. <a name="Concepts"></a>
  935. Next: <a rel="next" accesskey="n" href="#Examples">Examples</a>,
  936. Previous: <a rel="previous" accesskey="p" href="#Copying">Copying</a>,
  937. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  938.  
  939. </div>
  940.  
  941. <h2 class="chapter">1 The Concepts of Bison</h2>
  942.  
  943. <p>This chapter introduces many of the basic concepts without which the
  944. details of Bison will not make sense.  If you do not already know how to
  945. use Bison or Yacc, we suggest you start by reading this chapter carefully.
  946.  
  947. <ul class="menu">
  948. <li><a accesskey="1" href="#Language-and-Grammar">Language and Grammar</a>:   Languages and context-free grammars,
  949.                             as mathematical ideas. 
  950. <li><a accesskey="2" href="#Grammar-in-Bison">Grammar in Bison</a>:   How we represent grammars for Bison's sake. 
  951. <li><a accesskey="3" href="#Semantic-Values">Semantic Values</a>:    Each token or syntactic grouping can have
  952.                         a semantic value (the value of an integer,
  953.                         the name of an identifier, etc.). 
  954. <li><a accesskey="4" href="#Semantic-Actions">Semantic Actions</a>:   Each rule can have an action containing C code. 
  955. <li><a accesskey="5" href="#GLR-Parsers">GLR Parsers</a>:        Writing parsers for general context-free languages
  956. <li><a accesskey="6" href="#Locations-Overview">Locations Overview</a>:     Tracking Locations. 
  957. <li><a accesskey="7" href="#Bison-Parser">Bison Parser</a>:       What are Bison's input and output,
  958.                         how is the output used? 
  959. <li><a accesskey="8" href="#Stages">Stages</a>:             Stages in writing and running Bison grammars. 
  960. <li><a accesskey="9" href="#Grammar-Layout">Grammar Layout</a>:     Overall structure of a Bison grammar file. 
  961. </ul>
  962.  
  963. <div class="node">
  964. <p><hr>
  965. <a name="Language-and-Grammar"></a>
  966. Next: <a rel="next" accesskey="n" href="#Grammar-in-Bison">Grammar in Bison</a>,
  967. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  968.  
  969. </div>
  970.  
  971. <h3 class="section">1.1 Languages and Context-Free Grammars</h3>
  972.  
  973. <p><a name="index-context_002dfree-grammar-2"></a><a name="index-grammar_002c-context_002dfree-3"></a>In order for Bison to parse a language, it must be described by a
  974. <dfn>context-free grammar</dfn>.  This means that you specify one or more
  975. <dfn>syntactic groupings</dfn> and give rules for constructing them from their
  976. parts.  For example, in the C language, one kind of grouping is called an
  977. `expression'.  One rule for making an expression might be, “An expression
  978. can be made of a minus sign and another expression”.  Another would be,
  979. “An expression can be an integer”.  As you can see, rules are often
  980. recursive, but there must be at least one rule which leads out of the
  981. recursion.
  982.  
  983.    <p><a name="index-g_t_0040acronym_007bBNF_007d-4"></a><a name="index-Backus_002dNaur-form-5"></a>The most common formal system for presenting such rules for humans to read
  984. is <dfn>Backus-Naur Form</dfn> or “<acronym>BNF</acronym>”, which was developed in
  985. order to specify the language Algol 60.  Any grammar expressed in
  986. <acronym>BNF</acronym> is a context-free grammar.  The input to Bison is
  987. essentially machine-readable <acronym>BNF</acronym>.
  988.  
  989.    <p><a name="index-g_t_0040acronym_007bLALR_007d_00281_0029-grammars-6"></a><a name="index-g_t_0040acronym_007bLR_007d_00281_0029-grammars-7"></a>There are various important subclasses of context-free grammar.  Although it
  990. can handle almost all context-free grammars, Bison is optimized for what
  991. are called <acronym>LALR</acronym>(1) grammars. 
  992. In brief, in these grammars, it must be possible to
  993. tell how to parse any portion of an input string with just a single
  994. token of look-ahead.  Strictly speaking, that is a description of an
  995. <acronym>LR</acronym>(1) grammar, and <acronym>LALR</acronym>(1) involves additional
  996. restrictions that are
  997. hard to explain simply; but it is rare in actual practice to find an
  998. <acronym>LR</acronym>(1) grammar that fails to be <acronym>LALR</acronym>(1). 
  999. See <a href="#Mystery-Conflicts">Mysterious Reduce/Reduce Conflicts</a>, for
  1000. more information on this.
  1001.  
  1002.    <p><a name="index-g_t_0040acronym_007bGLR_007d-parsing-8"></a><a name="index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-9"></a><a name="index-ambiguous-grammars-10"></a><a name="index-non_002ddeterministic-parsing-11"></a>
  1003. Parsers for <acronym>LALR</acronym>(1) grammars are <dfn>deterministic</dfn>, meaning
  1004. roughly that the next grammar rule to apply at any point in the input is
  1005. uniquely determined by the preceding input and a fixed, finite portion
  1006. (called a <dfn>look-ahead</dfn>) of the remaining input.  A context-free
  1007. grammar can be <dfn>ambiguous</dfn>, meaning that there are multiple ways to
  1008. apply the grammar rules to get the some inputs.  Even unambiguous
  1009. grammars can be <dfn>non-deterministic</dfn>, meaning that no fixed
  1010. look-ahead always suffices to determine the next grammar rule to apply. 
  1011. With the proper declarations, Bison is also able to parse these more
  1012. general context-free grammars, using a technique known as <acronym>GLR</acronym>
  1013. parsing (for Generalized <acronym>LR</acronym>).  Bison's <acronym>GLR</acronym> parsers
  1014. are able to handle any context-free grammar for which the number of
  1015. possible parses of any given string is finite.
  1016.  
  1017.    <p><a name="index-symbols-_0028abstract_0029-12"></a><a name="index-token-13"></a><a name="index-syntactic-grouping-14"></a><a name="index-grouping_002c-syntactic-15"></a>In the formal grammatical rules for a language, each kind of syntactic
  1018. unit or grouping is named by a <dfn>symbol</dfn>.  Those which are built by
  1019. grouping smaller constructs according to grammatical rules are called
  1020. <dfn>nonterminal symbols</dfn>; those which can't be subdivided are called
  1021. <dfn>terminal symbols</dfn> or <dfn>token types</dfn>.  We call a piece of input
  1022. corresponding to a single terminal symbol a <dfn>token</dfn>, and a piece
  1023. corresponding to a single nonterminal symbol a <dfn>grouping</dfn>.
  1024.  
  1025.    <p>We can use the C language as an example of what symbols, terminal and
  1026. nonterminal, mean.  The tokens of C are identifiers, constants (numeric
  1027. and string), and the various keywords, arithmetic operators and
  1028. punctuation marks.  So the terminal symbols of a grammar for C include
  1029. `identifier', `number', `string', plus one symbol for each keyword,
  1030. operator or punctuation mark: `if', `return', `const', `static', `int',
  1031. `char', `plus-sign', `open-brace', `close-brace', `comma' and many more. 
  1032. (These tokens can be subdivided into characters, but that is a matter of
  1033. lexicography, not grammar.)
  1034.  
  1035.    <p>Here is a simple C function subdivided into tokens:
  1036.  
  1037. <pre class="example">     int             /* <span class="roman">keyword `int'</span> */
  1038.      square (int x)  /* <span class="roman">identifier, open-paren, identifier, identifier, close-paren</span> */
  1039.      {               /* <span class="roman">open-brace</span> */
  1040.        return x * x; /* <span class="roman">keyword `return', identifier, asterisk, identifier, semicolon</span> */
  1041.      }               /* <span class="roman">close-brace</span> */
  1042. </pre>
  1043.    <p>The syntactic groupings of C include the expression, the statement, the
  1044. declaration, and the function definition.  These are represented in the
  1045. grammar of C by nonterminal symbols `expression', `statement',
  1046. `declaration' and `function definition'.  The full grammar uses dozens of
  1047. additional language constructs, each with its own nonterminal symbol, in
  1048. order to express the meanings of these four.  The example above is a
  1049. function definition; it contains one declaration, and one statement.  In
  1050. the statement, each `<samp><span class="samp">x</span></samp>' is an expression and so is `<samp><span class="samp">x * x</span></samp>'.
  1051.  
  1052.    <p>Each nonterminal symbol must have grammatical rules showing how it is made
  1053. out of simpler constructs.  For example, one kind of C statement is the
  1054. <code>return</code> statement; this would be described with a grammar rule which
  1055. reads informally as follows:
  1056.  
  1057.    <blockquote>
  1058. A `statement' can be made of a `return' keyword, an `expression' and a
  1059. `semicolon'. 
  1060. </blockquote>
  1061.  
  1062. <p class="noindent">There would be many other rules for `statement', one for each kind of
  1063. statement in C.
  1064.  
  1065.    <p><a name="index-start-symbol-16"></a>One nonterminal symbol must be distinguished as the special one which
  1066. defines a complete utterance in the language.  It is called the <dfn>start
  1067. symbol</dfn>.  In a compiler, this means a complete input program.  In the C
  1068. language, the nonterminal symbol `sequence of definitions and declarations'
  1069. plays this role.
  1070.  
  1071.    <p>For example, `<samp><span class="samp">1 + 2</span></samp>' is a valid C expression—a valid part of a C
  1072. program—but it is not valid as an <em>entire</em> C program.  In the
  1073. context-free grammar of C, this follows from the fact that `expression' is
  1074. not the start symbol.
  1075.  
  1076.    <p>The Bison parser reads a sequence of tokens as its input, and groups the
  1077. tokens using the grammar rules.  If the input is valid, the end result is
  1078. that the entire token sequence reduces to a single grouping whose symbol is
  1079. the grammar's start symbol.  If we use a grammar for C, the entire input
  1080. must be a `sequence of definitions and declarations'.  If not, the parser
  1081. reports a syntax error.
  1082.  
  1083. <div class="node">
  1084. <p><hr>
  1085. <a name="Grammar-in-Bison"></a>
  1086. Next: <a rel="next" accesskey="n" href="#Semantic-Values">Semantic Values</a>,
  1087. Previous: <a rel="previous" accesskey="p" href="#Language-and-Grammar">Language and Grammar</a>,
  1088. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1089.  
  1090. </div>
  1091.  
  1092. <h3 class="section">1.2 From Formal Rules to Bison Input</h3>
  1093.  
  1094. <p><a name="index-Bison-grammar-17"></a><a name="index-grammar_002c-Bison-18"></a><a name="index-formal-grammar-19"></a>
  1095. A formal grammar is a mathematical construct.  To define the language
  1096. for Bison, you must write a file expressing the grammar in Bison syntax:
  1097. a <dfn>Bison grammar</dfn> file.  See <a href="#Grammar-File">Bison Grammar Files</a>.
  1098.  
  1099.    <p>A nonterminal symbol in the formal grammar is represented in Bison input
  1100. as an identifier, like an identifier in C.  By convention, it should be
  1101. in lower case, such as <code>expr</code>, <code>stmt</code> or <code>declaration</code>.
  1102.  
  1103.    <p>The Bison representation for a terminal symbol is also called a <dfn>token
  1104. type</dfn>.  Token types as well can be represented as C-like identifiers.  By
  1105. convention, these identifiers should be upper case to distinguish them from
  1106. nonterminals: for example, <code>INTEGER</code>, <code>IDENTIFIER</code>, <code>IF</code> or
  1107. <code>RETURN</code>.  A terminal symbol that stands for a particular keyword in
  1108. the language should be named after that keyword converted to upper case. 
  1109. The terminal symbol <code>error</code> is reserved for error recovery. 
  1110. See <a href="#Symbols">Symbols</a>.
  1111.  
  1112.    <p>A terminal symbol can also be represented as a character literal, just like
  1113. a C character constant.  You should do this whenever a token is just a
  1114. single character (parenthesis, plus-sign, etc.): use that same character in
  1115. a literal as the terminal symbol for that token.
  1116.  
  1117.    <p>A third way to represent a terminal symbol is with a C string constant
  1118. containing several characters.  See <a href="#Symbols">Symbols</a>, for more information.
  1119.  
  1120.    <p>The grammar rules also have an expression in Bison syntax.  For example,
  1121. here is the Bison rule for a C <code>return</code> statement.  The semicolon in
  1122. quotes is a literal character token, representing part of the C syntax for
  1123. the statement; the naked semicolon, and the colon, are Bison punctuation
  1124. used in every rule.
  1125.  
  1126. <pre class="example">     stmt:   RETURN expr ';'
  1127.              ;
  1128. </pre>
  1129.    <p class="noindent">See <a href="#Rules">Syntax of Grammar Rules</a>.
  1130.  
  1131. <div class="node">
  1132. <p><hr>
  1133. <a name="Semantic-Values"></a>
  1134. Next: <a rel="next" accesskey="n" href="#Semantic-Actions">Semantic Actions</a>,
  1135. Previous: <a rel="previous" accesskey="p" href="#Grammar-in-Bison">Grammar in Bison</a>,
  1136. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1137.  
  1138. </div>
  1139.  
  1140. <h3 class="section">1.3 Semantic Values</h3>
  1141.  
  1142. <p><a name="index-semantic-value-20"></a><a name="index-value_002c-semantic-21"></a>
  1143. A formal grammar selects tokens only by their classifications: for example,
  1144. if a rule mentions the terminal symbol `integer constant', it means that
  1145. <em>any</em> integer constant is grammatically valid in that position.  The
  1146. precise value of the constant is irrelevant to how to parse the input: if
  1147. `<samp><span class="samp">x+4</span></samp>' is grammatical then `<samp><span class="samp">x+1</span></samp>' or `<samp><span class="samp">x+3989</span></samp>' is equally
  1148. grammatical.
  1149.  
  1150.    <p>But the precise value is very important for what the input means once it is
  1151. parsed.  A compiler is useless if it fails to distinguish between 4, 1 and
  1152. 3989 as constants in the program!  Therefore, each token in a Bison grammar
  1153. has both a token type and a <dfn>semantic value</dfn>.  See <a href="#Semantics">Defining Language Semantics</a>,
  1154. for details.
  1155.  
  1156.    <p>The token type is a terminal symbol defined in the grammar, such as
  1157. <code>INTEGER</code>, <code>IDENTIFIER</code> or <code>','</code>.  It tells everything
  1158. you need to know to decide where the token may validly appear and how to
  1159. group it with other tokens.  The grammar rules know nothing about tokens
  1160. except their types.
  1161.  
  1162.    <p>The semantic value has all the rest of the information about the
  1163. meaning of the token, such as the value of an integer, or the name of an
  1164. identifier.  (A token such as <code>','</code> which is just punctuation doesn't
  1165. need to have any semantic value.)
  1166.  
  1167.    <p>For example, an input token might be classified as token type
  1168. <code>INTEGER</code> and have the semantic value 4.  Another input token might
  1169. have the same token type <code>INTEGER</code> but value 3989.  When a grammar
  1170. rule says that <code>INTEGER</code> is allowed, either of these tokens is
  1171. acceptable because each is an <code>INTEGER</code>.  When the parser accepts the
  1172. token, it keeps track of the token's semantic value.
  1173.  
  1174.    <p>Each grouping can also have a semantic value as well as its nonterminal
  1175. symbol.  For example, in a calculator, an expression typically has a
  1176. semantic value that is a number.  In a compiler for a programming
  1177. language, an expression typically has a semantic value that is a tree
  1178. structure describing the meaning of the expression.
  1179.  
  1180. <div class="node">
  1181. <p><hr>
  1182. <a name="Semantic-Actions"></a>
  1183. Next: <a rel="next" accesskey="n" href="#GLR-Parsers">GLR Parsers</a>,
  1184. Previous: <a rel="previous" accesskey="p" href="#Semantic-Values">Semantic Values</a>,
  1185. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1186.  
  1187. </div>
  1188.  
  1189. <h3 class="section">1.4 Semantic Actions</h3>
  1190.  
  1191. <p><a name="index-semantic-actions-22"></a><a name="index-actions_002c-semantic-23"></a>
  1192. In order to be useful, a program must do more than parse input; it must
  1193. also produce some output based on the input.  In a Bison grammar, a grammar
  1194. rule can have an <dfn>action</dfn> made up of C statements.  Each time the
  1195. parser recognizes a match for that rule, the action is executed. 
  1196. See <a href="#Actions">Actions</a>.
  1197.  
  1198.    <p>Most of the time, the purpose of an action is to compute the semantic value
  1199. of the whole construct from the semantic values of its parts.  For example,
  1200. suppose we have a rule which says an expression can be the sum of two
  1201. expressions.  When the parser recognizes such a sum, each of the
  1202. subexpressions has a semantic value which describes how it was built up. 
  1203. The action for this rule should create a similar sort of value for the
  1204. newly recognized larger expression.
  1205.  
  1206.    <p>For example, here is a rule that says an expression can be the sum of
  1207. two subexpressions:
  1208.  
  1209. <pre class="example">     expr: expr '+' expr   { $$ = $1 + $3; }
  1210.              ;
  1211. </pre>
  1212.    <p class="noindent">The action says how to produce the semantic value of the sum expression
  1213. from the values of the two subexpressions.
  1214.  
  1215. <div class="node">
  1216. <p><hr>
  1217. <a name="GLR-Parsers"></a>
  1218. Next: <a rel="next" accesskey="n" href="#Locations-Overview">Locations Overview</a>,
  1219. Previous: <a rel="previous" accesskey="p" href="#Semantic-Actions">Semantic Actions</a>,
  1220. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1221.  
  1222. </div>
  1223.  
  1224. <h3 class="section">1.5 Writing <acronym>GLR</acronym> Parsers</h3>
  1225.  
  1226. <p><a name="index-g_t_0040acronym_007bGLR_007d-parsing-24"></a><a name="index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-25"></a><a name="index-g_t_0025glr_002dparser-26"></a><a name="index-conflicts-27"></a><a name="index-shift_002freduce-conflicts-28"></a>
  1227. In some grammars, there will be cases where Bison's standard
  1228. <acronym>LALR</acronym>(1) parsing algorithm cannot decide whether to apply a
  1229. certain grammar rule at a given point.  That is, it may not be able to
  1230. decide (on the basis of the input read so far) which of two possible
  1231. reductions (applications of a grammar rule) applies, or whether to apply
  1232. a reduction or read more of the input and apply a reduction later in the
  1233. input.  These are known respectively as <dfn>reduce/reduce</dfn> conflicts
  1234. (see <a href="#Reduce_002fReduce">Reduce/Reduce</a>), and <dfn>shift/reduce</dfn> conflicts
  1235. (see <a href="#Shift_002fReduce">Shift/Reduce</a>).
  1236.  
  1237.    <p>To use a grammar that is not easily modified to be <acronym>LALR</acronym>(1), a
  1238. more general parsing algorithm is sometimes necessary.  If you include
  1239. <code>%glr-parser</code> among the Bison declarations in your file
  1240. (see <a href="#Grammar-Outline">Grammar Outline</a>), the result will be a Generalized <acronym>LR</acronym>
  1241. (<acronym>GLR</acronym>) parser.  These parsers handle Bison grammars that
  1242. contain no unresolved conflicts (i.e., after applying precedence
  1243. declarations) identically to <acronym>LALR</acronym>(1) parsers.  However, when
  1244. faced with unresolved shift/reduce and reduce/reduce conflicts,
  1245. <acronym>GLR</acronym> parsers use the simple expedient of doing both,
  1246. effectively cloning the parser to follow both possibilities.  Each of
  1247. the resulting parsers can again split, so that at any given time, there
  1248. can be any number of possible parses being explored.  The parsers
  1249. proceed in lockstep; that is, all of them consume (shift) a given input
  1250. symbol before any of them proceed to the next.  Each of the cloned
  1251. parsers eventually meets one of two possible fates: either it runs into
  1252. a parsing error, in which case it simply vanishes, or it merges with
  1253. another parser, because the two of them have reduced the input to an
  1254. identical set of symbols.
  1255.  
  1256.    <p>During the time that there are multiple parsers, semantic actions are
  1257. recorded, but not performed.  When a parser disappears, its recorded
  1258. semantic actions disappear as well, and are never performed.  When a
  1259. reduction makes two parsers identical, causing them to merge, Bison
  1260. records both sets of semantic actions.  Whenever the last two parsers
  1261. merge, reverting to the single-parser case, Bison resolves all the
  1262. outstanding actions either by precedences given to the grammar rules
  1263. involved, or by performing both actions, and then calling a designated
  1264. user-defined function on the resulting values to produce an arbitrary
  1265. merged result.
  1266.  
  1267.    <p>Let's consider an example, vastly simplified from a C++ grammar.
  1268.  
  1269. <pre class="example">     %{
  1270.        #include <stdio.h>
  1271.        #define YYSTYPE char const *
  1272.        int yylex (void);
  1273.        void yyerror (char const *);
  1274.      %}
  1275.      
  1276.      %token TYPENAME ID
  1277.      
  1278.      %right '='
  1279.      %left '+'
  1280.      
  1281.      %glr-parser
  1282.      
  1283.      %%
  1284.      
  1285.      prog :
  1286.           | prog stmt   { printf ("\n"); }
  1287.           ;
  1288.      
  1289.      stmt : expr ';'  %dprec 1
  1290.           | decl      %dprec 2
  1291.           ;
  1292.      
  1293.      expr : ID               { printf ("%s ", $$); }
  1294.           | TYPENAME '(' expr ')'
  1295.                              { printf ("%s <cast> ", $1); }
  1296.           | expr '+' expr    { printf ("+ "); }
  1297.           | expr '=' expr    { printf ("= "); }
  1298.           ;
  1299.      
  1300.      decl : TYPENAME declarator ';'
  1301.                              { printf ("%s <declare> ", $1); }
  1302.           | TYPENAME declarator '=' expr ';'
  1303.                              { printf ("%s <init-declare> ", $1); }
  1304.           ;
  1305.      
  1306.      declarator : ID         { printf ("\"%s\" ", $1); }
  1307.           | '(' declarator ')'
  1308.           ;
  1309. </pre>
  1310.    <p class="noindent">This models a problematic part of the C++ grammar—the ambiguity between
  1311. certain declarations and statements.  For example,
  1312.  
  1313. <pre class="example">     T (x) = y+z;
  1314. </pre>
  1315.    <p class="noindent">parses as either an <code>expr</code> or a <code>stmt</code>
  1316. (assuming that `<samp><span class="samp">T</span></samp>' is recognized as a <code>TYPENAME</code> and
  1317. `<samp><span class="samp">x</span></samp>' as an <code>ID</code>). 
  1318. Bison detects this as a reduce/reduce conflict between the rules
  1319. <code>expr : ID</code> and <code>declarator : ID</code>, which it cannot resolve at the
  1320. time it encounters <code>x</code> in the example above.  The two <code>%dprec</code>
  1321. declarations, however, give precedence to interpreting the example as a
  1322. <code>decl</code>, which implies that <code>x</code> is a declarator. 
  1323. The parser therefore prints
  1324.  
  1325. <pre class="example">     "x" y z + T <init-declare>
  1326. </pre>
  1327.    <p>Consider a different input string for this parser:
  1328.  
  1329. <pre class="example">     T (x) + y;
  1330. </pre>
  1331.    <p class="noindent">Here, there is no ambiguity (this cannot be parsed as a declaration). 
  1332. However, at the time the Bison parser encounters <code>x</code>, it does not
  1333. have enough information to resolve the reduce/reduce conflict (again,
  1334. between <code>x</code> as an <code>expr</code> or a <code>declarator</code>).  In this
  1335. case, no precedence declaration is used.  Instead, the parser splits
  1336. into two, one assuming that <code>x</code> is an <code>expr</code>, and the other
  1337. assuming <code>x</code> is a <code>declarator</code>.  The second of these parsers
  1338. then vanishes when it sees <code>+</code>, and the parser prints
  1339.  
  1340. <pre class="example">     x T <cast> y +
  1341. </pre>
  1342.    <p>Suppose that instead of resolving the ambiguity, you wanted to see all
  1343. the possibilities.  For this purpose, we must <dfn>merge</dfn> the semantic
  1344. actions of the two possible parsers, rather than choosing one over the
  1345. other.  To do so, you could change the declaration of <code>stmt</code> as
  1346. follows:
  1347.  
  1348. <pre class="example">     stmt : expr ';'  %merge <stmtMerge>
  1349.           | decl      %merge <stmtMerge>
  1350.           ;
  1351. </pre>
  1352.    <p class="noindent">and define the <code>stmtMerge</code> function as:
  1353.  
  1354. <pre class="example">     static YYSTYPE
  1355.      stmtMerge (YYSTYPE x0, YYSTYPE x1)
  1356.      {
  1357.        printf ("<OR> ");
  1358.        return "";
  1359.      }
  1360. </pre>
  1361.    <p class="noindent">with an accompanying forward declaration
  1362. in the C declarations at the beginning of the file:
  1363.  
  1364. <pre class="example">     %{
  1365.        #define YYSTYPE char const *
  1366.        static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
  1367.      %}
  1368. </pre>
  1369.    <p class="noindent">With these declarations, the resulting parser will parse the first example
  1370. as both an <code>expr</code> and a <code>decl</code>, and print
  1371.  
  1372. <pre class="example">     "x" y z + T <init-declare> x T <cast> y z + = <OR>
  1373. </pre>
  1374.    <pre class="sp">
  1375.  
  1376. </pre>
  1377.  
  1378. <a name="index-g_t_0040code_007bincline_007d-29"></a><a name="index-g_t_0040acronym_007bGLR_007d-parsers-and-_0040code_007binline_007d-30"></a>The <acronym>GLR</acronym> parsers require a compiler for <acronym>ISO</acronym> C89 or
  1379. later.  In addition, they use the <code>inline</code> keyword, which is not
  1380. C89, but is C99 and is a common extension in pre-C99 compilers.  It is
  1381. up to the user of these parsers to handle
  1382. portability issues.  For instance, if using Autoconf and the Autoconf
  1383. macro <code>AC_C_INLINE</code>, a mere
  1384.  
  1385. <pre class="example">     %{
  1386.        #include <config.h>
  1387.      %}
  1388. </pre>
  1389.    <p class="noindent">will suffice.  Otherwise, we suggest
  1390.  
  1391. <pre class="example">     %{
  1392.        #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
  1393.         #define inline
  1394.        #endif
  1395.      %}
  1396. </pre>
  1397.    <div class="node">
  1398. <p><hr>
  1399. <a name="Locations-Overview"></a>
  1400. Next: <a rel="next" accesskey="n" href="#Bison-Parser">Bison Parser</a>,
  1401. Previous: <a rel="previous" accesskey="p" href="#GLR-Parsers">GLR Parsers</a>,
  1402. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1403.  
  1404. </div>
  1405.  
  1406. <h3 class="section">1.6 Locations</h3>
  1407.  
  1408. <p><a name="index-location-31"></a><a name="index-textual-position-32"></a><a name="index-position_002c-textual-33"></a>
  1409. Many applications, like interpreters or compilers, have to produce verbose
  1410. and useful error messages.  To achieve this, one must be able to keep track of
  1411. the <dfn>textual position</dfn>, or <dfn>location</dfn>, of each syntactic construct. 
  1412. Bison provides a mechanism for handling these locations.
  1413.  
  1414.    <p>Each token has a semantic value.  In a similar fashion, each token has an
  1415. associated location, but the type of locations is the same for all tokens and
  1416. groupings.  Moreover, the output parser is equipped with a default data
  1417. structure for storing locations (see <a href="#Locations">Locations</a>, for more details).
  1418.  
  1419.    <p>Like semantic values, locations can be reached in actions using a dedicated
  1420. set of constructs.  In the example above, the location of the whole grouping
  1421. is <code>@$</code>, while the locations of the subexpressions are <code>@1</code> and
  1422. <code>@3</code>.
  1423.  
  1424.    <p>When a rule is matched, a default action is used to compute the semantic value
  1425. of its left hand side (see <a href="#Actions">Actions</a>).  In the same way, another default
  1426. action is used for locations.  However, the action for locations is general
  1427. enough for most cases, meaning there is usually no need to describe for each
  1428. rule how <code>@$</code> should be formed.  When building a new location for a given
  1429. grouping, the default behavior of the output parser is to take the beginning
  1430. of the first symbol, and the end of the last symbol.
  1431.  
  1432. <div class="node">
  1433. <p><hr>
  1434. <a name="Bison-Parser"></a>
  1435. Next: <a rel="next" accesskey="n" href="#Stages">Stages</a>,
  1436. Previous: <a rel="previous" accesskey="p" href="#Locations-Overview">Locations Overview</a>,
  1437. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1438.  
  1439. </div>
  1440.  
  1441. <h3 class="section">1.7 Bison Output: the Parser File</h3>
  1442.  
  1443. <p><a name="index-Bison-parser-34"></a><a name="index-Bison-utility-35"></a><a name="index-lexical-analyzer_002c-purpose-36"></a><a name="index-parser-37"></a>
  1444. When you run Bison, you give it a Bison grammar file as input.  The output
  1445. is a C source file that parses the language described by the grammar. 
  1446. This file is called a <dfn>Bison parser</dfn>.  Keep in mind that the Bison
  1447. utility and the Bison parser are two distinct programs: the Bison utility
  1448. is a program whose output is the Bison parser that becomes part of your
  1449. program.
  1450.  
  1451.    <p>The job of the Bison parser is to group tokens into groupings according to
  1452. the grammar rules—for example, to build identifiers and operators into
  1453. expressions.  As it does this, it runs the actions for the grammar rules it
  1454. uses.
  1455.  
  1456.    <p>The tokens come from a function called the <dfn>lexical analyzer</dfn> that
  1457. you must supply in some fashion (such as by writing it in C).  The Bison
  1458. parser calls the lexical analyzer each time it wants a new token.  It
  1459. doesn't know what is “inside” the tokens (though their semantic values
  1460. may reflect this).  Typically the lexical analyzer makes the tokens by
  1461. parsing characters of text, but Bison does not depend on this. 
  1462. See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>.
  1463.  
  1464.    <p>The Bison parser file is C code which defines a function named
  1465. <code>yyparse</code> which implements that grammar.  This function does not make
  1466. a complete C program: you must supply some additional functions.  One is
  1467. the lexical analyzer.  Another is an error-reporting function which the
  1468. parser calls to report an error.  In addition, a complete C program must
  1469. start with a function called <code>main</code>; you have to provide this, and
  1470. arrange for it to call <code>yyparse</code> or the parser will never run. 
  1471. See <a href="#Interface">Parser C-Language Interface</a>.
  1472.  
  1473.    <p>Aside from the token type names and the symbols in the actions you
  1474. write, all symbols defined in the Bison parser file itself
  1475. begin with `<samp><span class="samp">yy</span></samp>' or `<samp><span class="samp">YY</span></samp>'.  This includes interface functions
  1476. such as the lexical analyzer function <code>yylex</code>, the error reporting
  1477. function <code>yyerror</code> and the parser function <code>yyparse</code> itself. 
  1478. This also includes numerous identifiers used for internal purposes. 
  1479. Therefore, you should avoid using C identifiers starting with `<samp><span class="samp">yy</span></samp>'
  1480. or `<samp><span class="samp">YY</span></samp>' in the Bison grammar file except for the ones defined in
  1481. this manual.
  1482.  
  1483.    <p>In some cases the Bison parser file includes system headers, and in
  1484. those cases your code should respect the identifiers reserved by those
  1485. headers.  On some non-<acronym>GNU</acronym> hosts, <code><alloca.h></code>,
  1486. <code><stddef.h></code>, and <code><stdlib.h></code> are included as needed to
  1487. declare memory allocators and related types.  Other system headers may
  1488. be included if you define <code>YYDEBUG</code> to a nonzero value
  1489. (see <a href="#Tracing">Tracing Your Parser</a>).
  1490.  
  1491. <div class="node">
  1492. <p><hr>
  1493. <a name="Stages"></a>
  1494. Next: <a rel="next" accesskey="n" href="#Grammar-Layout">Grammar Layout</a>,
  1495. Previous: <a rel="previous" accesskey="p" href="#Bison-Parser">Bison Parser</a>,
  1496. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1497.  
  1498. </div>
  1499.  
  1500. <h3 class="section">1.8 Stages in Using Bison</h3>
  1501.  
  1502. <p><a name="index-stages-in-using-Bison-38"></a><a name="index-using-Bison-39"></a>
  1503. The actual language-design process using Bison, from grammar specification
  1504. to a working compiler or interpreter, has these parts:
  1505.  
  1506.      <ol type=1 start=1>
  1507. <li>Formally specify the grammar in a form recognized by Bison
  1508. (see <a href="#Grammar-File">Bison Grammar Files</a>).  For each grammatical rule
  1509. in the language, describe the action that is to be taken when an
  1510. instance of that rule is recognized.  The action is described by a
  1511. sequence of C statements.
  1512.  
  1513.      <li>Write a lexical analyzer to process input and pass tokens to the parser. 
  1514. The lexical analyzer may be written by hand in C (see <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>).  It could also be produced
  1515. using Lex, but the use of Lex is not discussed in this manual.
  1516.  
  1517.      <li>Write a controlling function that calls the Bison-produced parser.
  1518.  
  1519.      <li>Write error-reporting routines.
  1520.         </ol>
  1521.  
  1522.    <p>To turn this source code as written into a runnable program, you
  1523. must follow these steps:
  1524.  
  1525.      <ol type=1 start=1>
  1526. <li>Run Bison on the grammar to produce the parser.
  1527.  
  1528.      <li>Compile the code output by Bison, as well as any other source files.
  1529.  
  1530.      <li>Link the object files to produce the finished product.
  1531.         </ol>
  1532.  
  1533. <div class="node">
  1534. <p><hr>
  1535. <a name="Grammar-Layout"></a>
  1536. Previous: <a rel="previous" accesskey="p" href="#Stages">Stages</a>,
  1537. Up: <a rel="up" accesskey="u" href="#Concepts">Concepts</a>
  1538.  
  1539. </div>
  1540.  
  1541. <h3 class="section">1.9 The Overall Layout of a Bison Grammar</h3>
  1542.  
  1543. <p><a name="index-grammar-file-40"></a><a name="index-file-format-41"></a><a name="index-format-of-grammar-file-42"></a><a name="index-layout-of-Bison-grammar-43"></a>
  1544. The input file for the Bison utility is a <dfn>Bison grammar file</dfn>.  The
  1545. general form of a Bison grammar file is as follows:
  1546.  
  1547. <pre class="example">     %{
  1548.      <var>Prologue</var>
  1549.      %}
  1550.      
  1551.      <var>Bison declarations</var>
  1552.      
  1553.      %%
  1554.      <var>Grammar rules</var>
  1555.      %%
  1556.      <var>Epilogue</var>
  1557. </pre>
  1558.    <p class="noindent">The `<samp><span class="samp">%%</span></samp>', `<samp><span class="samp">%{</span></samp>' and `<samp><span class="samp">%}</span></samp>' are punctuation that appears
  1559. in every Bison grammar file to separate the sections.
  1560.  
  1561.    <p>The prologue may define types and variables used in the actions.  You can
  1562. also use preprocessor commands to define macros used there, and use
  1563. <code>#include</code> to include header files that do any of these things. 
  1564. You need to declare the lexical analyzer <code>yylex</code> and the error
  1565. printer <code>yyerror</code> here, along with any other global identifiers
  1566. used by the actions in the grammar rules.
  1567.  
  1568.    <p>The Bison declarations declare the names of the terminal and nonterminal
  1569. symbols, and may also describe operator precedence and the data types of
  1570. semantic values of various symbols.
  1571.  
  1572.    <p>The grammar rules define how to construct each nonterminal symbol from its
  1573. parts.
  1574.  
  1575.    <p>The epilogue can contain any code you want to use.  Often the
  1576. definitions of functions declared in the prologue go here.  In a
  1577. simple program, all the rest of the program can go here.
  1578.  
  1579. <div class="node">
  1580. <p><hr>
  1581. <a name="Examples"></a>
  1582. Next: <a rel="next" accesskey="n" href="#Grammar-File">Grammar File</a>,
  1583. Previous: <a rel="previous" accesskey="p" href="#Concepts">Concepts</a>,
  1584. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  1585.  
  1586. </div>
  1587.  
  1588. <h2 class="chapter">2 Examples</h2>
  1589.  
  1590. <p><a name="index-simple-examples-44"></a><a name="index-examples_002c-simple-45"></a>
  1591. Now we show and explain three sample programs written using Bison: a
  1592. reverse polish notation calculator, an algebraic (infix) notation
  1593. calculator, and a multi-function calculator.  All three have been tested
  1594. under BSD Unix 4.3; each produces a usable, though limited, interactive
  1595. desk-top calculator.
  1596.  
  1597.    <p>These examples are simple, but Bison grammars for real programming
  1598. languages are written the same way.
  1599.  
  1600. <ul class="menu">
  1601. <li><a accesskey="1" href="#RPN-Calc">RPN Calc</a>:           Reverse polish notation calculator;
  1602.                         a first example with no operator precedence. 
  1603. <li><a accesskey="2" href="#Infix-Calc">Infix Calc</a>:         Infix (algebraic) notation calculator. 
  1604.                         Operator precedence is introduced. 
  1605. <li><a accesskey="3" href="#Simple-Error-Recovery">Simple Error Recovery</a>:   Continuing after syntax errors. 
  1606. <li><a accesskey="4" href="#Location-Tracking-Calc">Location Tracking Calc</a>:  Demonstrating the use of @<var>n</var> and @$. 
  1607. <li><a accesskey="5" href="#Multi_002dfunction-Calc">Multi-function Calc</a>:   Calculator with memory and trig functions. 
  1608.                            It uses multiple data-types for semantic values. 
  1609. <li><a accesskey="6" href="#Exercises">Exercises</a>:          Ideas for improving the multi-function calculator. 
  1610. </ul>
  1611.  
  1612. <div class="node">
  1613. <p><hr>
  1614. <a name="RPN-Calc"></a>
  1615. Next: <a rel="next" accesskey="n" href="#Infix-Calc">Infix Calc</a>,
  1616. Up: <a rel="up" accesskey="u" href="#Examples">Examples</a>
  1617.  
  1618. </div>
  1619.  
  1620. <h3 class="section">2.1 Reverse Polish Notation Calculator</h3>
  1621.  
  1622. <p><a name="index-reverse-polish-notation-46"></a><a name="index-polish-notation-calculator-47"></a><a name="index-g_t_0040code_007brpcalc_007d-48"></a><a name="index-calculator_002c-simple-49"></a>
  1623. The first example is that of a simple double-precision <dfn>reverse polish
  1624. notation</dfn> calculator (a calculator using postfix operators).  This example
  1625. provides a good starting point, since operator precedence is not an issue. 
  1626. The second example will illustrate how operator precedence is handled.
  1627.  
  1628.    <p>The source code for this calculator is named <samp><span class="file">rpcalc.y</span></samp>.  The
  1629. `<samp><span class="samp">.y</span></samp>' extension is a convention used for Bison input files.
  1630.  
  1631. <ul class="menu">
  1632. <li><a accesskey="1" href="#Rpcalc-Decls">Decls</a>:   Prologue (declarations) for rpcalc. 
  1633. <li><a accesskey="2" href="#Rpcalc-Rules">Rules</a>:   Grammar Rules for rpcalc, with explanation. 
  1634. <li><a accesskey="3" href="#Rpcalc-Lexer">Lexer</a>:   The lexical analyzer. 
  1635. <li><a accesskey="4" href="#Rpcalc-Main">Main</a>:     The controlling function. 
  1636. <li><a accesskey="5" href="#Rpcalc-Error">Error</a>:   The error reporting function. 
  1637. <li><a accesskey="6" href="#Rpcalc-Gen">Gen</a>:       Running Bison on the grammar file. 
  1638. <li><a accesskey="7" href="#Rpcalc-Compile">Comp</a>:  Run the C compiler on the output code. 
  1639. </ul>
  1640.  
  1641. <div class="node">
  1642. <p><hr>
  1643. <a name="Rpcalc-Decls"></a>
  1644. Next: <a rel="next" accesskey="n" href="#Rpcalc-Rules">Rpcalc Rules</a>,
  1645. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  1646.  
  1647. </div>
  1648.  
  1649. <h4 class="subsection">2.1.1 Declarations for <code>rpcalc</code></h4>
  1650.  
  1651. <p>Here are the C and Bison declarations for the reverse polish notation
  1652. calculator.  As in C, comments are placed between `<samp><span class="samp">/*...*/</span></samp>'.
  1653.  
  1654. <pre class="example">     /* Reverse polish notation calculator.  */
  1655.      
  1656.      %{
  1657.        #define YYSTYPE double
  1658.        #include <math.h>
  1659.        int yylex (void);
  1660.        void yyerror (char const *);
  1661.      %}
  1662.      
  1663.      %token NUM
  1664.      
  1665.      %% /* Grammar rules and actions follow.  */
  1666. </pre>
  1667.    <p>The declarations section (see <a href="#Prologue">The prologue</a>) contains two
  1668. preprocessor directives and two forward declarations.
  1669.  
  1670.    <p>The <code>#define</code> directive defines the macro <code>YYSTYPE</code>, thus
  1671. specifying the C data type for semantic values of both tokens and
  1672. groupings (see <a href="#Value-Type">Data Types of Semantic Values</a>).  The
  1673. Bison parser will use whatever type <code>YYSTYPE</code> is defined as; if you
  1674. don't define it, <code>int</code> is the default.  Because we specify
  1675. <code>double</code>, each token and each expression has an associated value,
  1676. which is a floating point number.
  1677.  
  1678.    <p>The <code>#include</code> directive is used to declare the exponentiation
  1679. function <code>pow</code>.
  1680.  
  1681.    <p>The forward declarations for <code>yylex</code> and <code>yyerror</code> are
  1682. needed because the C language requires that functions be declared
  1683. before they are used.  These functions will be defined in the
  1684. epilogue, but the parser calls them so they must be declared in the
  1685. prologue.
  1686.  
  1687.    <p>The second section, Bison declarations, provides information to Bison
  1688. about the token types (see <a href="#Bison-Declarations">The Bison Declarations Section</a>).  Each terminal symbol that is not a
  1689. single-character literal must be declared here.  (Single-character
  1690. literals normally don't need to be declared.)  In this example, all the
  1691. arithmetic operators are designated by single-character literals, so the
  1692. only terminal symbol that needs to be declared is <code>NUM</code>, the token
  1693. type for numeric constants.
  1694.  
  1695. <div class="node">
  1696. <p><hr>
  1697. <a name="Rpcalc-Rules"></a>
  1698. Next: <a rel="next" accesskey="n" href="#Rpcalc-Lexer">Rpcalc Lexer</a>,
  1699. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Decls">Rpcalc Decls</a>,
  1700. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  1701.  
  1702. </div>
  1703.  
  1704. <h4 class="subsection">2.1.2 Grammar Rules for <code>rpcalc</code></h4>
  1705.  
  1706. <p>Here are the grammar rules for the reverse polish notation calculator.
  1707.  
  1708. <pre class="example">     input:    /* empty */
  1709.              | input line
  1710.      ;
  1711.      
  1712.      line:     '\n'
  1713.              | exp '\n'      { printf ("\t%.10g\n", $1); }
  1714.      ;
  1715.      
  1716.      exp:      NUM           { $$ = $1;           }
  1717.              | exp exp '+'   { $$ = $1 + $2;      }
  1718.              | exp exp '-'   { $$ = $1 - $2;      }
  1719.              | exp exp '*'   { $$ = $1 * $2;      }
  1720.              | exp exp '/'   { $$ = $1 / $2;      }
  1721.               /* Exponentiation */
  1722.              | exp exp '^'   { $$ = pow ($1, $2); }
  1723.               /* Unary minus    */
  1724.              | exp 'n'       { $$ = -$1;          }
  1725.      ;
  1726.      %%
  1727. </pre>
  1728.    <p>The groupings of the rpcalc “language” defined here are the expression
  1729. (given the name <code>exp</code>), the line of input (<code>line</code>), and the
  1730. complete input transcript (<code>input</code>).  Each of these nonterminal
  1731. symbols has several alternate rules, joined by the `<samp><span class="samp">|</span></samp>' punctuator
  1732. which is read as “or”.  The following sections explain what these rules
  1733. mean.
  1734.  
  1735.    <p>The semantics of the language is determined by the actions taken when a
  1736. grouping is recognized.  The actions are the C code that appears inside
  1737. braces.  See <a href="#Actions">Actions</a>.
  1738.  
  1739.    <p>You must specify these actions in C, but Bison provides the means for
  1740. passing semantic values between the rules.  In each action, the
  1741. pseudo-variable <code>$$</code> stands for the semantic value for the grouping
  1742. that the rule is going to construct.  Assigning a value to <code>$$</code> is the
  1743. main job of most actions.  The semantic values of the components of the
  1744. rule are referred to as <code>$1</code>, <code>$2</code>, and so on.
  1745.  
  1746. <ul class="menu">
  1747. <li><a accesskey="1" href="#Rpcalc-Input">Rpcalc Input</a>
  1748. <li><a accesskey="2" href="#Rpcalc-Line">Rpcalc Line</a>
  1749. <li><a accesskey="3" href="#Rpcalc-Expr">Rpcalc Expr</a>
  1750. </ul>
  1751.  
  1752. <div class="node">
  1753. <p><hr>
  1754. <a name="Rpcalc-Input"></a>
  1755. Next: <a rel="next" accesskey="n" href="#Rpcalc-Line">Rpcalc Line</a>,
  1756. Up: <a rel="up" accesskey="u" href="#Rpcalc-Rules">Rpcalc Rules</a>
  1757.  
  1758. </div>
  1759.  
  1760. <h5 class="subsubsection">2.1.2.1 Explanation of <code>input</code></h5>
  1761.  
  1762. <p>Consider the definition of <code>input</code>:
  1763.  
  1764. <pre class="example">     input:    /* empty */
  1765.              | input line
  1766.      ;
  1767. </pre>
  1768.    <p>This definition reads as follows: “A complete input is either an empty
  1769. string, or a complete input followed by an input line”.  Notice that
  1770. “complete input” is defined in terms of itself.  This definition is said
  1771. to be <dfn>left recursive</dfn> since <code>input</code> appears always as the
  1772. leftmost symbol in the sequence.  See <a href="#Recursion">Recursive Rules</a>.
  1773.  
  1774.    <p>The first alternative is empty because there are no symbols between the
  1775. colon and the first `<samp><span class="samp">|</span></samp>'; this means that <code>input</code> can match an
  1776. empty string of input (no tokens).  We write the rules this way because it
  1777. is legitimate to type <kbd>Ctrl-d</kbd> right after you start the calculator. 
  1778. It's conventional to put an empty alternative first and write the comment
  1779. `<samp><span class="samp">/* empty */</span></samp>' in it.
  1780.  
  1781.    <p>The second alternate rule (<code>input line</code>) handles all nontrivial input. 
  1782. It means, “After reading any number of lines, read one more line if
  1783. possible.”  The left recursion makes this rule into a loop.  Since the
  1784. first alternative matches empty input, the loop can be executed zero or
  1785. more times.
  1786.  
  1787.    <p>The parser function <code>yyparse</code> continues to process input until a
  1788. grammatical error is seen or the lexical analyzer says there are no more
  1789. input tokens; we will arrange for the latter to happen at end-of-input.
  1790.  
  1791. <div class="node">
  1792. <p><hr>
  1793. <a name="Rpcalc-Line"></a>
  1794. Next: <a rel="next" accesskey="n" href="#Rpcalc-Expr">Rpcalc Expr</a>,
  1795. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Input">Rpcalc Input</a>,
  1796. Up: <a rel="up" accesskey="u" href="#Rpcalc-Rules">Rpcalc Rules</a>
  1797.  
  1798. </div>
  1799.  
  1800. <h5 class="subsubsection">2.1.2.2 Explanation of <code>line</code></h5>
  1801.  
  1802. <p>Now consider the definition of <code>line</code>:
  1803.  
  1804. <pre class="example">     line:     '\n'
  1805.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1806.      ;
  1807. </pre>
  1808.    <p>The first alternative is a token which is a newline character; this means
  1809. that rpcalc accepts a blank line (and ignores it, since there is no
  1810. action).  The second alternative is an expression followed by a newline. 
  1811. This is the alternative that makes rpcalc useful.  The semantic value of
  1812. the <code>exp</code> grouping is the value of <code>$1</code> because the <code>exp</code> in
  1813. question is the first symbol in the alternative.  The action prints this
  1814. value, which is the result of the computation the user asked for.
  1815.  
  1816.    <p>This action is unusual because it does not assign a value to <code>$$</code>.  As
  1817. a consequence, the semantic value associated with the <code>line</code> is
  1818. uninitialized (its value will be unpredictable).  This would be a bug if
  1819. that value were ever used, but we don't use it: once rpcalc has printed the
  1820. value of the user's input line, that value is no longer needed.
  1821.  
  1822. <div class="node">
  1823. <p><hr>
  1824. <a name="Rpcalc-Expr"></a>
  1825. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Line">Rpcalc Line</a>,
  1826. Up: <a rel="up" accesskey="u" href="#Rpcalc-Rules">Rpcalc Rules</a>
  1827.  
  1828. </div>
  1829.  
  1830. <h5 class="subsubsection">2.1.2.3 Explanation of <code>expr</code></h5>
  1831.  
  1832. <p>The <code>exp</code> grouping has several rules, one for each kind of expression. 
  1833. The first rule handles the simplest expressions: those that are just numbers. 
  1834. The second handles an addition-expression, which looks like two expressions
  1835. followed by a plus-sign.  The third handles subtraction, and so on.
  1836.  
  1837. <pre class="example">     exp:      NUM
  1838.              | exp exp '+'     { $$ = $1 + $2;    }
  1839.              | exp exp '-'     { $$ = $1 - $2;    }
  1840.              ...
  1841.              ;
  1842. </pre>
  1843.    <p>We have used `<samp><span class="samp">|</span></samp>' to join all the rules for <code>exp</code>, but we could
  1844. equally well have written them separately:
  1845.  
  1846. <pre class="example">     exp:      NUM ;
  1847.      exp:      exp exp '+'     { $$ = $1 + $2;    } ;
  1848.      exp:      exp exp '-'     { $$ = $1 - $2;    } ;
  1849.              ...
  1850. </pre>
  1851.    <p>Most of the rules have actions that compute the value of the expression in
  1852. terms of the value of its parts.  For example, in the rule for addition,
  1853. <code>$1</code> refers to the first component <code>exp</code> and <code>$2</code> refers to
  1854. the second one.  The third component, <code>'+'</code>, has no meaningful
  1855. associated semantic value, but if it had one you could refer to it as
  1856. <code>$3</code>.  When <code>yyparse</code> recognizes a sum expression using this
  1857. rule, the sum of the two subexpressions' values is produced as the value of
  1858. the entire expression.  See <a href="#Actions">Actions</a>.
  1859.  
  1860.    <p>You don't have to give an action for every rule.  When a rule has no
  1861. action, Bison by default copies the value of <code>$1</code> into <code>$$</code>. 
  1862. This is what happens in the first rule (the one that uses <code>NUM</code>).
  1863.  
  1864.    <p>The formatting shown here is the recommended convention, but Bison does
  1865. not require it.  You can add or change white space as much as you wish. 
  1866. For example, this:
  1867.  
  1868. <pre class="example">     exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  1869. </pre>
  1870.    <p class="noindent">means the same thing as this:
  1871.  
  1872. <pre class="example">     exp:      NUM
  1873.              | exp exp '+'    { $$ = $1 + $2; }
  1874.              | ...
  1875. </pre>
  1876.    <p class="noindent">The latter, however, is much more readable.
  1877.  
  1878. <div class="node">
  1879. <p><hr>
  1880. <a name="Rpcalc-Lexer"></a>
  1881. Next: <a rel="next" accesskey="n" href="#Rpcalc-Main">Rpcalc Main</a>,
  1882. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Rules">Rpcalc Rules</a>,
  1883. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  1884.  
  1885. </div>
  1886.  
  1887. <h4 class="subsection">2.1.3 The <code>rpcalc</code> Lexical Analyzer</h4>
  1888.  
  1889. <p><a name="index-writing-a-lexical-analyzer-50"></a><a name="index-lexical-analyzer_002c-writing-51"></a>
  1890. The lexical analyzer's job is low-level parsing: converting characters
  1891. or sequences of characters into tokens.  The Bison parser gets its
  1892. tokens by calling the lexical analyzer.  See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>.
  1893.  
  1894.    <p>Only a simple lexical analyzer is needed for the <acronym>RPN</acronym>
  1895. calculator.  This
  1896. lexical analyzer skips blanks and tabs, then reads in numbers as
  1897. <code>double</code> and returns them as <code>NUM</code> tokens.  Any other character
  1898. that isn't part of a number is a separate token.  Note that the token-code
  1899. for such a single-character token is the character itself.
  1900.  
  1901.    <p>The return value of the lexical analyzer function is a numeric code which
  1902. represents a token type.  The same text used in Bison rules to stand for
  1903. this token type is also a C expression for the numeric code for the type. 
  1904. This works in two ways.  If the token type is a character literal, then its
  1905. numeric code is that of the character; you can use the same
  1906. character literal in the lexical analyzer to express the number.  If the
  1907. token type is an identifier, that identifier is defined by Bison as a C
  1908. macro whose definition is the appropriate number.  In this example,
  1909. therefore, <code>NUM</code> becomes a macro for <code>yylex</code> to use.
  1910.  
  1911.    <p>The semantic value of the token (if it has one) is stored into the
  1912. global variable <code>yylval</code>, which is where the Bison parser will look
  1913. for it.  (The C data type of <code>yylval</code> is <code>YYSTYPE</code>, which was
  1914. defined at the beginning of the grammar; see <a href="#Rpcalc-Decls">Declarations for <code>rpcalc</code></a>.)
  1915.  
  1916.    <p>A token type code of zero is returned if the end-of-input is encountered. 
  1917. (Bison recognizes any nonpositive value as indicating end-of-input.)
  1918.  
  1919.    <p>Here is the code for the lexical analyzer:
  1920.  
  1921. <pre class="example">     /* The lexical analyzer returns a double floating point
  1922.         number on the stack and the token NUM, or the numeric code
  1923.         of the character read if not a number.  It skips all blanks
  1924.         and tabs, and returns 0 for end-of-input.  */
  1925.      
  1926.      #include <ctype.h>
  1927.      
  1928.      int
  1929.      yylex (void)
  1930.      {
  1931.        int c;
  1932.      
  1933.        /* Skip white space.  */
  1934.        while ((c = getchar ()) == ' ' || c == '\t')
  1935.          ;
  1936.        /* Process numbers.  */
  1937.        if (c == '.' || isdigit (c))
  1938.          {
  1939.            ungetc (c, stdin);
  1940.            scanf ("%lf", &yylval);
  1941.            return NUM;
  1942.          }
  1943.        /* Return end-of-input.  */
  1944.        if (c == EOF)
  1945.          return 0;
  1946.        /* Return a single char.  */
  1947.        return c;
  1948.      }
  1949. </pre>
  1950.    <div class="node">
  1951. <p><hr>
  1952. <a name="Rpcalc-Main"></a>
  1953. Next: <a rel="next" accesskey="n" href="#Rpcalc-Error">Rpcalc Error</a>,
  1954. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Lexer">Rpcalc Lexer</a>,
  1955. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  1956.  
  1957. </div>
  1958.  
  1959. <h4 class="subsection">2.1.4 The Controlling Function</h4>
  1960.  
  1961. <p><a name="index-controlling-function-52"></a><a name="index-main-function-in-simple-example-53"></a>
  1962. In keeping with the spirit of this example, the controlling function is
  1963. kept to the bare minimum.  The only requirement is that it call
  1964. <code>yyparse</code> to start the process of parsing.
  1965.  
  1966. <pre class="example">     int
  1967.      main (void)
  1968.      {
  1969.        return yyparse ();
  1970.      }
  1971. </pre>
  1972.    <div class="node">
  1973. <p><hr>
  1974. <a name="Rpcalc-Error"></a>
  1975. Next: <a rel="next" accesskey="n" href="#Rpcalc-Gen">Rpcalc Gen</a>,
  1976. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Main">Rpcalc Main</a>,
  1977. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  1978.  
  1979. </div>
  1980.  
  1981. <h4 class="subsection">2.1.5 The Error Reporting Routine</h4>
  1982.  
  1983. <p><a name="index-error-reporting-routine-54"></a>
  1984. When <code>yyparse</code> detects a syntax error, it calls the error reporting
  1985. function <code>yyerror</code> to print an error message (usually but not
  1986. always <code>"syntax error"</code>).  It is up to the programmer to supply
  1987. <code>yyerror</code> (see <a href="#Interface">Parser C-Language Interface</a>), so
  1988. here is the definition we will use:
  1989.  
  1990. <pre class="example">     #include <stdio.h>
  1991.      
  1992.      /* Called by yyparse on error.  */
  1993.      void
  1994.      yyerror (char const *s)
  1995.      {
  1996.        printf ("%s\n", s);
  1997.      }
  1998. </pre>
  1999.    <p>After <code>yyerror</code> returns, the Bison parser may recover from the error
  2000. and continue parsing if the grammar contains a suitable error rule
  2001. (see <a href="#Error-Recovery">Error Recovery</a>).  Otherwise, <code>yyparse</code> returns nonzero.  We
  2002. have not written any error rules in this example, so any invalid input will
  2003. cause the calculator program to exit.  This is not clean behavior for a
  2004. real calculator, but it is adequate for the first example.
  2005.  
  2006. <div class="node">
  2007. <p><hr>
  2008. <a name="Rpcalc-Gen"></a>
  2009. Next: <a rel="next" accesskey="n" href="#Rpcalc-Compile">Rpcalc Compile</a>,
  2010. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Error">Rpcalc Error</a>,
  2011. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  2012.  
  2013. </div>
  2014.  
  2015. <h4 class="subsection">2.1.6 Running Bison to Make the Parser</h4>
  2016.  
  2017. <p><a name="index-running-Bison-_0028introduction_0029-55"></a>
  2018. Before running Bison to produce a parser, we need to decide how to
  2019. arrange all the source code in one or more source files.  For such a
  2020. simple example, the easiest thing is to put everything in one file.  The
  2021. definitions of <code>yylex</code>, <code>yyerror</code> and <code>main</code> go at the
  2022. end, in the epilogue of the file
  2023. (see <a href="#Grammar-Layout">The Overall Layout of a Bison Grammar</a>).
  2024.  
  2025.    <p>For a large project, you would probably have several source files, and use
  2026. <code>make</code> to arrange to recompile them.
  2027.  
  2028.    <p>With all the source in a single file, you use the following command to
  2029. convert it into a parser file:
  2030.  
  2031. <pre class="example">     bison <var>file_name</var>.y
  2032. </pre>
  2033.    <p class="noindent">In this example the file was called <samp><span class="file">rpcalc.y</span></samp> (for “Reverse Polish
  2034. <span class="sc">calc</span>ulator”).  Bison produces a file named <samp><var>file_name</var><span class="file">.tab.c</span></samp>,
  2035. removing the `<samp><span class="samp">.y</span></samp>' from the original file name.  The file output by
  2036. Bison contains the source code for <code>yyparse</code>.  The additional
  2037. functions in the input file (<code>yylex</code>, <code>yyerror</code> and <code>main</code>)
  2038. are copied verbatim to the output.
  2039.  
  2040. <div class="node">
  2041. <p><hr>
  2042. <a name="Rpcalc-Compile"></a>
  2043. Previous: <a rel="previous" accesskey="p" href="#Rpcalc-Gen">Rpcalc Gen</a>,
  2044. Up: <a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>
  2045.  
  2046. </div>
  2047.  
  2048. <h4 class="subsection">2.1.7 Compiling the Parser File</h4>
  2049.  
  2050. <p><a name="index-compiling-the-parser-56"></a>
  2051. Here is how to compile and run the parser file:
  2052.  
  2053. <pre class="example">     # <span class="roman">List files in current directory.</span>
  2054.      $ <kbd>ls</kbd>
  2055.      rpcalc.tab.c  rpcalc.y
  2056.      
  2057.      # <span class="roman">Compile the Bison parser.</span>
  2058.      # <span class="roman">`<samp>-lm</samp>' tells compiler to search math library for </span><code>pow</code><span class="roman">.</span>
  2059.      $ <kbd>cc -lm -o rpcalc rpcalc.tab.c</kbd>
  2060.      
  2061.      # <span class="roman">List files again.</span>
  2062.      $ <kbd>ls</kbd>
  2063.      rpcalc  rpcalc.tab.c  rpcalc.y
  2064. </pre>
  2065.    <p>The file <samp><span class="file">rpcalc</span></samp> now contains the executable code.  Here is an
  2066. example session using <code>rpcalc</code>.
  2067.  
  2068. <pre class="example">     $ <kbd>rpcalc</kbd>
  2069.      <kbd>4 9 +</kbd>
  2070.      13
  2071.      <kbd>3 7 + 3 4 5 *+-</kbd>
  2072.      -13
  2073.      <kbd>3 7 + 3 4 5 * + - n</kbd>              <span class="roman">Note the unary minus, `<samp>n</samp>'</span>
  2074.      13
  2075.      <kbd>5 6 / 4 n +</kbd>
  2076.      -3.166666667
  2077.      <kbd>3 4 ^</kbd>                            <span class="roman">Exponentiation</span>
  2078.      81
  2079.      <kbd>^D</kbd>                               <span class="roman">End-of-file indicator</span>
  2080.      $
  2081. </pre>
  2082.    <div class="node">
  2083. <p><hr>
  2084. <a name="Infix-Calc"></a>
  2085. Next: <a rel="next" accesskey="n" href="#Simple-Error-Recovery">Simple Error Recovery</a>,
  2086. Previous: <a rel="previous" accesskey="p" href="#RPN-Calc">RPN Calc</a>,
  2087. Up: <a rel="up" accesskey="u" href="#Examples">Examples</a>
  2088.  
  2089. </div>
  2090.  
  2091. <h3 class="section">2.2 Infix Notation Calculator: <code>calc</code></h3>
  2092.  
  2093. <p><a name="index-infix-notation-calculator-57"></a><a name="index-g_t_0040code_007bcalc_007d-58"></a><a name="index-calculator_002c-infix-notation-59"></a>
  2094. We now modify rpcalc to handle infix operators instead of postfix.  Infix
  2095. notation involves the concept of operator precedence and the need for
  2096. parentheses nested to arbitrary depth.  Here is the Bison code for
  2097. <samp><span class="file">calc.y</span></samp>, an infix desk-top calculator.
  2098.  
  2099. <pre class="example">     /* Infix notation calculator.  */
  2100.      
  2101.      %{
  2102.        #define YYSTYPE double
  2103.        #include <math.h>
  2104.        #include <stdio.h>
  2105.        int yylex (void);
  2106.        void yyerror (char const *);
  2107.      %}
  2108.      
  2109.      /* Bison declarations.  */
  2110.      %token NUM
  2111.      %left '-' '+'
  2112.      %left '*' '/'
  2113.      %left NEG     /* negation--unary minus */
  2114.      %right '^'    /* exponentiation */
  2115.      
  2116.      %% /* The grammar follows.  */
  2117.      input:    /* empty */
  2118.              | input line
  2119.      ;
  2120.      
  2121.      line:     '\n'
  2122.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  2123.      ;
  2124.      
  2125.      exp:      NUM                { $$ = $1;         }
  2126.              | exp '+' exp        { $$ = $1 + $3;    }
  2127.              | exp '-' exp        { $$ = $1 - $3;    }
  2128.              | exp '*' exp        { $$ = $1 * $3;    }
  2129.              | exp '/' exp        { $$ = $1 / $3;    }
  2130.              | '-' exp  %prec NEG { $$ = -$2;        }
  2131.              | exp '^' exp        { $$ = pow ($1, $3); }
  2132.              | '(' exp ')'        { $$ = $2;         }
  2133.      ;
  2134.      %%
  2135. </pre>
  2136.    <p class="noindent">The functions <code>yylex</code>, <code>yyerror</code> and <code>main</code> can be the
  2137. same as before.
  2138.  
  2139.    <p>There are two important new features shown in this code.
  2140.  
  2141.    <p>In the second section (Bison declarations), <code>%left</code> declares token
  2142. types and says they are left-associative operators.  The declarations
  2143. <code>%left</code> and <code>%right</code> (right associativity) take the place of
  2144. <code>%token</code> which is used to declare a token type name without
  2145. associativity.  (These tokens are single-character literals, which
  2146. ordinarily don't need to be declared.  We declare them here to specify
  2147. the associativity.)
  2148.  
  2149.    <p>Operator precedence is determined by the line ordering of the
  2150. declarations; the higher the line number of the declaration (lower on
  2151. the page or screen), the higher the precedence.  Hence, exponentiation
  2152. has the highest precedence, unary minus (<code>NEG</code>) is next, followed
  2153. by `<samp><span class="samp">*</span></samp>' and `<samp><span class="samp">/</span></samp>', and so on.  See <a href="#Precedence">Operator Precedence</a>.
  2154.  
  2155.    <p>The other important new feature is the <code>%prec</code> in the grammar
  2156. section for the unary minus operator.  The <code>%prec</code> simply instructs
  2157. Bison that the rule `<samp><span class="samp">| '-' exp</span></samp>' has the same precedence as
  2158. <code>NEG</code>—in this case the next-to-highest.  See <a href="#Contextual-Precedence">Context-Dependent Precedence</a>.
  2159.  
  2160.    <p>Here is a sample run of <samp><span class="file">calc.y</span></samp>:
  2161.  
  2162. <pre class="example">     $ <kbd>calc</kbd>
  2163.      <kbd>4 + 4.5 - (34/(8*3+-3))</kbd>
  2164.      6.880952381
  2165.      <kbd>-56 + 2</kbd>
  2166.      -54
  2167.      <kbd>3 ^ 2</kbd>
  2168.      9
  2169. </pre>
  2170.    <div class="node">
  2171. <p><hr>
  2172. <a name="Simple-Error-Recovery"></a>
  2173. Next: <a rel="next" accesskey="n" href="#Location-Tracking-Calc">Location Tracking Calc</a>,
  2174. Previous: <a rel="previous" accesskey="p" href="#Infix-Calc">Infix Calc</a>,
  2175. Up: <a rel="up" accesskey="u" href="#Examples">Examples</a>
  2176.  
  2177. </div>
  2178.  
  2179. <h3 class="section">2.3 Simple Error Recovery</h3>
  2180.  
  2181. <p><a name="index-error-recovery_002c-simple-60"></a>
  2182. Up to this point, this manual has not addressed the issue of <dfn>error
  2183. recovery</dfn>—how to continue parsing after the parser detects a syntax
  2184. error.  All we have handled is error reporting with <code>yyerror</code>. 
  2185. Recall that by default <code>yyparse</code> returns after calling
  2186. <code>yyerror</code>.  This means that an erroneous input line causes the
  2187. calculator program to exit.  Now we show how to rectify this deficiency.
  2188.  
  2189.    <p>The Bison language itself includes the reserved word <code>error</code>, which
  2190. may be included in the grammar rules.  In the example below it has
  2191. been added to one of the alternatives for <code>line</code>:
  2192.  
  2193. <pre class="example">     line:     '\n'
  2194.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  2195.              | error '\n' { yyerrok;                  }
  2196.      ;
  2197. </pre>
  2198.    <p>This addition to the grammar allows for simple error recovery in the
  2199. event of a syntax error.  If an expression that cannot be evaluated is
  2200. read, the error will be recognized by the third rule for <code>line</code>,
  2201. and parsing will continue.  (The <code>yyerror</code> function is still called
  2202. upon to print its message as well.)  The action executes the statement
  2203. <code>yyerrok</code>, a macro defined automatically by Bison; its meaning is
  2204. that error recovery is complete (see <a href="#Error-Recovery">Error Recovery</a>).  Note the
  2205. difference between <code>yyerrok</code> and <code>yyerror</code>; neither one is a
  2206. misprint.
  2207.  
  2208.    <p>This form of error recovery deals with syntax errors.  There are other
  2209. kinds of errors; for example, division by zero, which raises an exception
  2210. signal that is normally fatal.  A real calculator program must handle this
  2211. signal and use <code>longjmp</code> to return to <code>main</code> and resume parsing
  2212. input lines; it would also have to discard the rest of the current line of
  2213. input.  We won't discuss this issue further because it is not specific to
  2214. Bison programs.
  2215.  
  2216. <div class="node">
  2217. <p><hr>
  2218. <a name="Location-Tracking-Calc"></a>
  2219. Next: <a rel="next" accesskey="n" href="#Multi_002dfunction-Calc">Multi-function Calc</a>,
  2220. Previous: <a rel="previous" accesskey="p" href="#Simple-Error-Recovery">Simple Error Recovery</a>,
  2221. Up: <a rel="up" accesskey="u" href="#Examples">Examples</a>
  2222.  
  2223. </div>
  2224.  
  2225. <h3 class="section">2.4 Location Tracking Calculator: <code>ltcalc</code></h3>
  2226.  
  2227. <p><a name="index-location-tracking-calculator-61"></a><a name="index-g_t_0040code_007bltcalc_007d-62"></a><a name="index-calculator_002c-location-tracking-63"></a>
  2228. This example extends the infix notation calculator with location
  2229. tracking.  This feature will be used to improve the error messages.  For
  2230. the sake of clarity, this example is a simple integer calculator, since
  2231. most of the work needed to use locations will be done in the lexical
  2232. analyzer.
  2233.  
  2234. <ul class="menu">
  2235. <li><a accesskey="1" href="#Ltcalc-Decls">Decls</a>:   Bison and C declarations for ltcalc. 
  2236. <li><a accesskey="2" href="#Ltcalc-Rules">Rules</a>:   Grammar rules for ltcalc, with explanations. 
  2237. <li><a accesskey="3" href="#Ltcalc-Lexer">Lexer</a>:   The lexical analyzer. 
  2238. </ul>
  2239.  
  2240. <div class="node">
  2241. <p><hr>
  2242. <a name="Ltcalc-Decls"></a>
  2243. Next: <a rel="next" accesskey="n" href="#Ltcalc-Rules">Ltcalc Rules</a>,
  2244. Up: <a rel="up" accesskey="u" href="#Location-Tracking-Calc">Location Tracking Calc</a>
  2245.  
  2246. </div>
  2247.  
  2248. <h4 class="subsection">2.4.1 Declarations for <code>ltcalc</code></h4>
  2249.  
  2250. <p>The C and Bison declarations for the location tracking calculator are
  2251. the same as the declarations for the infix notation calculator.
  2252.  
  2253. <pre class="example">     /* Location tracking calculator.  */
  2254.      
  2255.      %{
  2256.        #define YYSTYPE int
  2257.        #include <math.h>
  2258.        int yylex (void);
  2259.        void yyerror (char const *);
  2260.      %}
  2261.      
  2262.      /* Bison declarations.  */
  2263.      %token NUM
  2264.      
  2265.      %left '-' '+'
  2266.      %left '*' '/'
  2267.      %left NEG
  2268.      %right '^'
  2269.      
  2270.      %% /* The grammar follows.  */
  2271. </pre>
  2272.    <p class="noindent">Note there are no declarations specific to locations.  Defining a data
  2273. type for storing locations is not needed: we will use the type provided
  2274. by default (see <a href="#Location-Type">Data Types of Locations</a>), which is a
  2275. four member structure with the following integer fields:
  2276. <code>first_line</code>, <code>first_column</code>, <code>last_line</code> and
  2277. <code>last_column</code>.
  2278.  
  2279. <div class="node">
  2280. <p><hr>
  2281. <a name="Ltcalc-Rules"></a>
  2282. Next: <a rel="next" accesskey="n" href="#Ltcalc-Lexer">Ltcalc Lexer</a>,
  2283. Previous: <a rel="previous" accesskey="p" href="#Ltcalc-Decls">Ltcalc Decls</a>,
  2284. Up: <a rel="up" accesskey="u" href="#Location-Tracking-Calc">Location Tracking Calc</a>
  2285.  
  2286. </div>
  2287.  
  2288. <h4 class="subsection">2.4.2 Grammar Rules for <code>ltcalc</code></h4>
  2289.  
  2290. <p>Whether handling locations or not has no effect on the syntax of your
  2291. language.  Therefore, grammar rules for this example will be very close
  2292. to those of the previous example: we will only modify them to benefit
  2293. from the new information.
  2294.  
  2295.    <p>Here, we will use locations to report divisions by zero, and locate the
  2296. wrong expressions or subexpressions.
  2297.  
  2298. <pre class="example">     input   : /* empty */
  2299.              | input line
  2300.      ;
  2301.      
  2302.      line    : '\n'
  2303.              | exp '\n' { printf ("%d\n", $1); }
  2304.      ;
  2305.      
  2306.      exp     : NUM           { $$ = $1; }
  2307.              | exp '+' exp   { $$ = $1 + $3; }
  2308.              | exp '-' exp   { $$ = $1 - $3; }
  2309.              | exp '*' exp   { $$ = $1 * $3; }
  2310.              | exp '/' exp
  2311.                  {
  2312.                    if ($3)
  2313.                      $$ = $1 / $3;
  2314.                    else
  2315.                      {
  2316.                        $$ = 1;
  2317.                        fprintf (stderr, "%d.%d-%d.%d: division by zero",
  2318.                                 @3.first_line, @3.first_column,
  2319.                                 @3.last_line, @3.last_column);
  2320.                      }
  2321.                  }
  2322.              | '-' exp %preg NEG     { $$ = -$2; }
  2323.              | exp '^' exp           { $$ = pow ($1, $3); }
  2324.              | '(' exp ')'           { $$ = $2; }
  2325. </pre>
  2326.    <p>This code shows how to reach locations inside of semantic actions, by
  2327. using the pseudo-variables <code>@</code><var>n</var> for rule components, and the
  2328. pseudo-variable <code>@$</code> for groupings.
  2329.  
  2330.    <p>We don't need to assign a value to <code>@$</code>: the output parser does it
  2331. automatically.  By default, before executing the C code of each action,
  2332. <code>@$</code> is set to range from the beginning of <code>@1</code> to the end
  2333. of <code>@</code><var>n</var>, for a rule with <var>n</var> components.  This behavior
  2334. can be redefined (see <a href="#Location-Default-Action">Default Action for Locations</a>), and for very specific rules, <code>@$</code> can be computed by
  2335. hand.
  2336.  
  2337. <div class="node">
  2338. <p><hr>
  2339. <a name="Ltcalc-Lexer"></a>
  2340. Previous: <a rel="previous" accesskey="p" href="#Ltcalc-Rules">Ltcalc Rules</a>,
  2341. Up: <a rel="up" accesskey="u" href="#Location-Tracking-Calc">Location Tracking Calc</a>
  2342.  
  2343. </div>
  2344.  
  2345. <h4 class="subsection">2.4.3 The <code>ltcalc</code> Lexical Analyzer.</h4>
  2346.  
  2347. <p>Until now, we relied on Bison's defaults to enable location
  2348. tracking.  The next step is to rewrite the lexical analyzer, and make it
  2349. able to feed the parser with the token locations, as it already does for
  2350. semantic values.
  2351.  
  2352.    <p>To this end, we must take into account every single character of the
  2353. input text, to avoid the computed locations of being fuzzy or wrong:
  2354.  
  2355. <pre class="example">     int
  2356.      yylex (void)
  2357.      {
  2358.        int c;
  2359.      
  2360.        /* Skip white space.  */
  2361.        while ((c = getchar ()) == ' ' || c == '\t')
  2362.          ++yylloc.last_column;
  2363.      
  2364.        /* Step.  */
  2365.        yylloc.first_line = yylloc.last_line;
  2366.        yylloc.first_column = yylloc.last_column;
  2367.      
  2368.        /* Process numbers.  */
  2369.        if (isdigit (c))
  2370.          {
  2371.            yylval = c - '0';
  2372.            ++yylloc.last_column;
  2373.            while (isdigit (c = getchar ()))
  2374.              {
  2375.                ++yylloc.last_column;
  2376.                yylval = yylval * 10 + c - '0';
  2377.              }
  2378.            ungetc (c, stdin);
  2379.            return NUM;
  2380.          }
  2381.      
  2382.        /* Return end-of-input.  */
  2383.        if (c == EOF)
  2384.          return 0;
  2385.      
  2386.        /* Return a single char, and update location.  */
  2387.        if (c == '\n')
  2388.          {
  2389.            ++yylloc.last_line;
  2390.            yylloc.last_column = 0;
  2391.          }
  2392.        else
  2393.          ++yylloc.last_column;
  2394.        return c;
  2395.      }
  2396. </pre>
  2397.    <p>Basically, the lexical analyzer performs the same processing as before:
  2398. it skips blanks and tabs, and reads numbers or single-character tokens. 
  2399. In addition, it updates <code>yylloc</code>, the global variable (of type
  2400. <code>YYLTYPE</code>) containing the token's location.
  2401.  
  2402.    <p>Now, each time this function returns a token, the parser has its number
  2403. as well as its semantic value, and its location in the text.  The last
  2404. needed change is to initialize <code>yylloc</code>, for example in the
  2405. controlling function:
  2406.  
  2407. <pre class="example">     int
  2408.      main (void)
  2409.      {
  2410.        yylloc.first_line = yylloc.last_line = 1;
  2411.        yylloc.first_column = yylloc.last_column = 0;
  2412.        return yyparse ();
  2413.      }
  2414. </pre>
  2415.    <p>Remember that computing locations is not a matter of syntax.  Every
  2416. character must be associated to a location update, whether it is in
  2417. valid input, in comments, in literal strings, and so on.
  2418.  
  2419. <div class="node">
  2420. <p><hr>
  2421. <a name="Multi-function-Calc"></a>
  2422. <a name="Multi_002dfunction-Calc"></a>
  2423. Next: <a rel="next" accesskey="n" href="#Exercises">Exercises</a>,
  2424. Previous: <a rel="previous" accesskey="p" href="#Location-Tracking-Calc">Location Tracking Calc</a>,
  2425. Up: <a rel="up" accesskey="u" href="#Examples">Examples</a>
  2426.  
  2427. </div>
  2428.  
  2429. <h3 class="section">2.5 Multi-Function Calculator: <code>mfcalc</code></h3>
  2430.  
  2431. <p><a name="index-multi_002dfunction-calculator-64"></a><a name="index-g_t_0040code_007bmfcalc_007d-65"></a><a name="index-calculator_002c-multi_002dfunction-66"></a>
  2432. Now that the basics of Bison have been discussed, it is time to move on to
  2433. a more advanced problem.  The above calculators provided only five
  2434. functions, `<samp><span class="samp">+</span></samp>', `<samp><span class="samp">-</span></samp>', `<samp><span class="samp">*</span></samp>', `<samp><span class="samp">/</span></samp>' and `<samp><span class="samp">^</span></samp>'.  It would
  2435. be nice to have a calculator that provides other mathematical functions such
  2436. as <code>sin</code>, <code>cos</code>, etc.
  2437.  
  2438.    <p>It is easy to add new operators to the infix calculator as long as they are
  2439. only single-character literals.  The lexical analyzer <code>yylex</code> passes
  2440. back all nonnumber characters as tokens, so new grammar rules suffice for
  2441. adding a new operator.  But we want something more flexible: built-in
  2442. functions whose syntax has this form:
  2443.  
  2444. <pre class="example">     <var>function_name</var> (<var>argument</var>)
  2445. </pre>
  2446.    <p class="noindent">At the same time, we will add memory to the calculator, by allowing you
  2447. to create named variables, store values in them, and use them later. 
  2448. Here is a sample session with the multi-function calculator:
  2449.  
  2450. <pre class="example">     $ <kbd>mfcalc</kbd>
  2451.      <kbd>pi = 3.141592653589</kbd>
  2452.      3.1415926536
  2453.      <kbd>sin(pi)</kbd>
  2454.      0.0000000000
  2455.      <kbd>alpha = beta1 = 2.3</kbd>
  2456.      2.3000000000
  2457.      <kbd>alpha</kbd>
  2458.      2.3000000000
  2459.      <kbd>ln(alpha)</kbd>
  2460.      0.8329091229
  2461.      <kbd>exp(ln(beta1))</kbd>
  2462.      2.3000000000
  2463.      $
  2464. </pre>
  2465.    <p>Note that multiple assignment and nested function calls are permitted.
  2466.  
  2467. <ul class="menu">
  2468. <li><a accesskey="1" href="#Mfcalc-Decl">Decl</a>:       Bison declarations for multi-function calculator. 
  2469. <li><a accesskey="2" href="#Mfcalc-Rules">Rules</a>:     Grammar rules for the calculator. 
  2470. <li><a accesskey="3" href="#Mfcalc-Symtab">Symtab</a>:   Symbol table management subroutines. 
  2471. </ul>
  2472.  
  2473. <div class="node">
  2474. <p><hr>
  2475. <a name="Mfcalc-Decl"></a>
  2476. Next: <a rel="next" accesskey="n" href="#Mfcalc-Rules">Mfcalc Rules</a>,
  2477. Up: <a rel="up" accesskey="u" href="#Multi_002dfunction-Calc">Multi-function Calc</a>
  2478.  
  2479. </div>
  2480.  
  2481. <h4 class="subsection">2.5.1 Declarations for <code>mfcalc</code></h4>
  2482.  
  2483. <p>Here are the C and Bison declarations for the multi-function calculator.
  2484.  
  2485. <pre class="smallexample">     %{
  2486.        #include <math.h>  /* For math functions, cos(), sin(), etc.  */
  2487.        #include "calc.h"  /* Contains definition of `symrec'.  */
  2488.        int yylex (void);
  2489.        void yyerror (char const *);
  2490.      %}
  2491.      %union {
  2492.        double    val;   /* For returning numbers.  */
  2493.        symrec  *tptr;   /* For returning symbol-table pointers.  */
  2494.      }
  2495.      %token <val>  NUM        /* Simple double precision number.  */
  2496.      %token <tptr> VAR FNCT   /* Variable and Function.  */
  2497.      %type  <val>  exp
  2498.      
  2499.      %right '='
  2500.      %left '-' '+'
  2501.      %left '*' '/'
  2502.      %left NEG     /* negation--unary minus */
  2503.      %right '^'    /* exponentiation */
  2504.      %% /* The grammar follows.  */
  2505. </pre>
  2506.    <p>The above grammar introduces only two new features of the Bison language. 
  2507. These features allow semantic values to have various data types
  2508. (see <a href="#Multiple-Types">More Than One Value Type</a>).
  2509.  
  2510.    <p>The <code>%union</code> declaration specifies the entire list of possible types;
  2511. this is instead of defining <code>YYSTYPE</code>.  The allowable types are now
  2512. double-floats (for <code>exp</code> and <code>NUM</code>) and pointers to entries in
  2513. the symbol table.  See <a href="#Union-Decl">The Collection of Value Types</a>.
  2514.  
  2515.    <p>Since values can now have various types, it is necessary to associate a
  2516. type with each grammar symbol whose semantic value is used.  These symbols
  2517. are <code>NUM</code>, <code>VAR</code>, <code>FNCT</code>, and <code>exp</code>.  Their
  2518. declarations are augmented with information about their data type (placed
  2519. between angle brackets).
  2520.  
  2521.    <p>The Bison construct <code>%type</code> is used for declaring nonterminal
  2522. symbols, just as <code>%token</code> is used for declaring token types.  We
  2523. have not used <code>%type</code> before because nonterminal symbols are
  2524. normally declared implicitly by the rules that define them.  But
  2525. <code>exp</code> must be declared explicitly so we can specify its value type. 
  2526. See <a href="#Type-Decl">Nonterminal Symbols</a>.
  2527.  
  2528. <div class="node">
  2529. <p><hr>
  2530. <a name="Mfcalc-Rules"></a>
  2531. Next: <a rel="next" accesskey="n" href="#Mfcalc-Symtab">Mfcalc Symtab</a>,
  2532. Previous: <a rel="previous" accesskey="p" href="#Mfcalc-Decl">Mfcalc Decl</a>,
  2533. Up: <a rel="up" accesskey="u" href="#Multi_002dfunction-Calc">Multi-function Calc</a>
  2534.  
  2535. </div>
  2536.  
  2537. <h4 class="subsection">2.5.2 Grammar Rules for <code>mfcalc</code></h4>
  2538.  
  2539. <p>Here are the grammar rules for the multi-function calculator. 
  2540. Most of them are copied directly from <code>calc</code>; three rules,
  2541. those which mention <code>VAR</code> or <code>FNCT</code>, are new.
  2542.  
  2543. <pre class="smallexample">     input:   /* empty */
  2544.              | input line
  2545.      ;
  2546.      
  2547.      line:
  2548.                '\n'
  2549.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  2550.              | error '\n' { yyerrok;                  }
  2551.      ;
  2552.      
  2553.      exp:      NUM                { $$ = $1;                         }
  2554.              | VAR                { $$ = $1->value.var;              }
  2555.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  2556.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  2557.              | exp '+' exp        { $$ = $1 + $3;                    }
  2558.              | exp '-' exp        { $$ = $1 - $3;                    }
  2559.              | exp '*' exp        { $$ = $1 * $3;                    }
  2560.              | exp '/' exp        { $$ = $1 / $3;                    }
  2561.              | '-' exp  %prec NEG { $$ = -$2;                        }
  2562.              | exp '^' exp        { $$ = pow ($1, $3);               }
  2563.              | '(' exp ')'        { $$ = $2;                         }
  2564.      ;
  2565.      /* End of grammar.  */
  2566.      %%
  2567. </pre>
  2568.    <div class="node">
  2569. <p><hr>
  2570. <a name="Mfcalc-Symtab"></a>
  2571. Previous: <a rel="previous" accesskey="p" href="#Mfcalc-Rules">Mfcalc Rules</a>,
  2572. Up: <a rel="up" accesskey="u" href="#Multi_002dfunction-Calc">Multi-function Calc</a>
  2573.  
  2574. </div>
  2575.  
  2576. <h4 class="subsection">2.5.3 The <code>mfcalc</code> Symbol Table</h4>
  2577.  
  2578. <p><a name="index-symbol-table-example-67"></a>
  2579. The multi-function calculator requires a symbol table to keep track of the
  2580. names and meanings of variables and functions.  This doesn't affect the
  2581. grammar rules (except for the actions) or the Bison declarations, but it
  2582. requires some additional C functions for support.
  2583.  
  2584.    <p>The symbol table itself consists of a linked list of records.  Its
  2585. definition, which is kept in the header <samp><span class="file">calc.h</span></samp>, is as follows.  It
  2586. provides for either functions or variables to be placed in the table.
  2587.  
  2588. <pre class="smallexample">     /* Function type.  */
  2589.      typedef double (*func_t) (double);
  2590.      
  2591.      /* Data type for links in the chain of symbols.  */
  2592.      struct symrec
  2593.      {
  2594.        char *name;  /* name of symbol */
  2595.        int type;    /* type of symbol: either VAR or FNCT */
  2596.        union
  2597.        {
  2598.          double var;      /* value of a VAR */
  2599.          func_t fnctptr;  /* value of a FNCT */
  2600.        } value;
  2601.        struct symrec *next;  /* link field */
  2602.      };
  2603.      
  2604.      typedef struct symrec symrec;
  2605.      
  2606.      /* The symbol table: a chain of `struct symrec'.  */
  2607.      extern symrec *sym_table;
  2608.      
  2609.      symrec *putsym (char const *, func_t);
  2610.      symrec *getsym (char const *);
  2611. </pre>
  2612.    <p>The new version of <code>main</code> includes a call to <code>init_table</code>, a
  2613. function that initializes the symbol table.  Here it is, and
  2614. <code>init_table</code> as well:
  2615.  
  2616. <pre class="smallexample">     #include <stdio.h>
  2617.      
  2618.      /* Called by yyparse on error.  */
  2619.      void
  2620.      yyerror (char const *s)
  2621.      {
  2622.        printf ("%s\n", s);
  2623.      }
  2624.      
  2625.      struct init
  2626.      {
  2627.        char const *fname;
  2628.        double (*fnct) (double);
  2629.      };
  2630.      
  2631.      struct init const arith_fncts[] =
  2632.      {
  2633.        "sin",  sin,
  2634.        "cos",  cos,
  2635.        "atan", atan,
  2636.        "ln",   log,
  2637.        "exp",  exp,
  2638.        "sqrt", sqrt,
  2639.        0, 0
  2640.      };
  2641.      
  2642.      /* The symbol table: a chain of `struct symrec'.  */
  2643.      symrec *sym_table;
  2644.      
  2645.      /* Put arithmetic functions in table.  */
  2646.      void
  2647.      init_table (void)
  2648.      {
  2649.        int i;
  2650.        symrec *ptr;
  2651.        for (i = 0; arith_fncts[i].fname != 0; i++)
  2652.          {
  2653.            ptr = putsym (arith_fncts[i].fname, FNCT);
  2654.            ptr->value.fnctptr = arith_fncts[i].fnct;
  2655.          }
  2656.      }
  2657.      
  2658.      int
  2659.      main (void)
  2660.      {
  2661.        init_table ();
  2662.        return yyparse ();
  2663.      }
  2664. </pre>
  2665.    <p>By simply editing the initialization list and adding the necessary include
  2666. files, you can add additional functions to the calculator.
  2667.  
  2668.    <p>Two important functions allow look-up and installation of symbols in the
  2669. symbol table.  The function <code>putsym</code> is passed a name and the type
  2670. (<code>VAR</code> or <code>FNCT</code>) of the object to be installed.  The object is
  2671. linked to the front of the list, and a pointer to the object is returned. 
  2672. The function <code>getsym</code> is passed the name of the symbol to look up.  If
  2673. found, a pointer to that symbol is returned; otherwise zero is returned.
  2674.  
  2675. <pre class="smallexample">     symrec *
  2676.      putsym (char const *sym_name, int sym_type)
  2677.      {
  2678.        symrec *ptr;
  2679.        ptr = (symrec *) malloc (sizeof (symrec));
  2680.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  2681.        strcpy (ptr->name,sym_name);
  2682.        ptr->type = sym_type;
  2683.        ptr->value.var = 0; /* Set value to 0 even if fctn.  */
  2684.        ptr->next = (struct symrec *)sym_table;
  2685.        sym_table = ptr;
  2686.        return ptr;
  2687.      }
  2688.      
  2689.      symrec *
  2690.      getsym (char const *sym_name)
  2691.      {
  2692.        symrec *ptr;
  2693.        for (ptr = sym_table; ptr != (symrec *) 0;
  2694.             ptr = (symrec *)ptr->next)
  2695.          if (strcmp (ptr->name,sym_name) == 0)
  2696.            return ptr;
  2697.        return 0;
  2698.      }
  2699. </pre>
  2700.    <p>The function <code>yylex</code> must now recognize variables, numeric values, and
  2701. the single-character arithmetic operators.  Strings of alphanumeric
  2702. characters with a leading non-digit are recognized as either variables or
  2703. functions depending on what the symbol table says about them.
  2704.  
  2705.    <p>The string is passed to <code>getsym</code> for look up in the symbol table.  If
  2706. the name appears in the table, a pointer to its location and its type
  2707. (<code>VAR</code> or <code>FNCT</code>) is returned to <code>yyparse</code>.  If it is not
  2708. already in the table, then it is installed as a <code>VAR</code> using
  2709. <code>putsym</code>.  Again, a pointer and its type (which must be <code>VAR</code>) is
  2710. returned to <code>yyparse</code>.
  2711.  
  2712.    <p>No change is needed in the handling of numeric values and arithmetic
  2713. operators in <code>yylex</code>.
  2714.  
  2715. <pre class="smallexample">     #include <ctype.h>
  2716.      
  2717.      int
  2718.      yylex (void)
  2719.      {
  2720.        int c;
  2721.      
  2722.        /* Ignore white space, get first nonwhite character.  */
  2723.        while ((c = getchar ()) == ' ' || c == '\t');
  2724.      
  2725.        if (c == EOF)
  2726.          return 0;
  2727.      
  2728.        /* Char starts a number => parse the number.         */
  2729.        if (c == '.' || isdigit (c))
  2730.          {
  2731.            ungetc (c, stdin);
  2732.            scanf ("%lf", &yylval.val);
  2733.            return NUM;
  2734.          }
  2735.      
  2736.        /* Char starts an identifier => read the name.       */
  2737.        if (isalpha (c))
  2738.          {
  2739.            symrec *s;
  2740.            static char *symbuf = 0;
  2741.            static int length = 0;
  2742.            int i;
  2743.      
  2744.            /* Initially make the buffer long enough
  2745.               for a 40-character symbol name.  */
  2746.            if (length == 0)
  2747.              length = 40, symbuf = (char *)malloc (length + 1);
  2748.      
  2749.            i = 0;
  2750.            do
  2751.              {
  2752.                /* If buffer is full, make it bigger.        */
  2753.                if (i == length)
  2754.                  {
  2755.                    length *= 2;
  2756.                    symbuf = (char *) realloc (symbuf, length + 1);
  2757.                  }
  2758.                /* Add this character to the buffer.         */
  2759.                symbuf[i++] = c;
  2760.                /* Get another character.                    */
  2761.                c = getchar ();
  2762.              }
  2763.            while (isalnum (c));
  2764.      
  2765.            ungetc (c, stdin);
  2766.            symbuf[i] = '\0';
  2767.      
  2768.            s = getsym (symbuf);
  2769.            if (s == 0)
  2770.              s = putsym (symbuf, VAR);
  2771.            yylval.tptr = s;
  2772.            return s->type;
  2773.          }
  2774.      
  2775.        /* Any other character is a token by itself.        */
  2776.        return c;
  2777.      }
  2778. </pre>
  2779.    <p>This program is both powerful and flexible.  You may easily add new
  2780. functions, and it is a simple job to modify this code to install
  2781. predefined variables such as <code>pi</code> or <code>e</code> as well.
  2782.  
  2783. <div class="node">
  2784. <p><hr>
  2785. <a name="Exercises"></a>
  2786. Previous: <a rel="previous" accesskey="p" href="#Multi_002dfunction-Calc">Multi-function Calc</a>,
  2787. Up: <a rel="up" accesskey="u" href="#Examples">Examples</a>
  2788.  
  2789. </div>
  2790.  
  2791. <h3 class="section">2.6 Exercises</h3>
  2792.  
  2793. <p><a name="index-exercises-68"></a>
  2794.      <ol type=1 start=1>
  2795. <li>Add some new functions from <samp><span class="file">math.h</span></samp> to the initialization list.
  2796.  
  2797.      <li>Add another array that contains constants and their values.  Then
  2798. modify <code>init_table</code> to add these constants to the symbol table. 
  2799. It will be easiest to give the constants type <code>VAR</code>.
  2800.  
  2801.      <li>Make the program report an error if the user refers to an
  2802. uninitialized variable in any way except to store a value in it.
  2803.         </ol>
  2804.  
  2805. <div class="node">
  2806. <p><hr>
  2807. <a name="Grammar-File"></a>
  2808. Next: <a rel="next" accesskey="n" href="#Interface">Interface</a>,
  2809. Previous: <a rel="previous" accesskey="p" href="#Examples">Examples</a>,
  2810. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  2811.  
  2812. </div>
  2813.  
  2814. <h2 class="chapter">3 Bison Grammar Files</h2>
  2815.  
  2816. <p>Bison takes as input a context-free grammar specification and produces a
  2817. C-language function that recognizes correct instances of the grammar.
  2818.  
  2819.    <p>The Bison grammar input file conventionally has a name ending in `<samp><span class="samp">.y</span></samp>'. 
  2820. See <a href="#Invocation">Invoking Bison</a>.
  2821.  
  2822. <ul class="menu">
  2823. <li><a accesskey="1" href="#Grammar-Outline">Grammar Outline</a>:    Overall layout of the grammar file. 
  2824. <li><a accesskey="2" href="#Symbols">Symbols</a>:            Terminal and nonterminal symbols. 
  2825. <li><a accesskey="3" href="#Rules">Rules</a>:              How to write grammar rules. 
  2826. <li><a accesskey="4" href="#Recursion">Recursion</a>:          Writing recursive rules. 
  2827. <li><a accesskey="5" href="#Semantics">Semantics</a>:          Semantic values and actions. 
  2828. <li><a accesskey="6" href="#Locations">Locations</a>:          Locations and actions. 
  2829. <li><a accesskey="7" href="#Declarations">Declarations</a>:       All kinds of Bison declarations are described here. 
  2830. <li><a accesskey="8" href="#Multiple-Parsers">Multiple Parsers</a>:   Putting more than one Bison parser in one program. 
  2831. </ul>
  2832.  
  2833. <div class="node">
  2834. <p><hr>
  2835. <a name="Grammar-Outline"></a>
  2836. Next: <a rel="next" accesskey="n" href="#Symbols">Symbols</a>,
  2837. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  2838.  
  2839. </div>
  2840.  
  2841. <h3 class="section">3.1 Outline of a Bison Grammar</h3>
  2842.  
  2843. <p>A Bison grammar file has four main sections, shown here with the
  2844. appropriate delimiters:
  2845.  
  2846. <pre class="example">     %{
  2847.        <var>Prologue</var>
  2848.      %}
  2849.      
  2850.      <var>Bison declarations</var>
  2851.      
  2852.      %%
  2853.      <var>Grammar rules</var>
  2854.      %%
  2855.      
  2856.      <var>Epilogue</var>
  2857. </pre>
  2858.    <p>Comments enclosed in `<samp><span class="samp">/* ... */</span></samp>' may appear in any of the sections. 
  2859. As a <acronym>GNU</acronym> extension, `<samp><span class="samp">//</span></samp>' introduces a comment that
  2860. continues until end of line.
  2861.  
  2862. <ul class="menu">
  2863. <li><a accesskey="1" href="#Prologue">Prologue</a>:           Syntax and usage of the prologue. 
  2864. <li><a accesskey="2" href="#Bison-Declarations">Bison Declarations</a>:   Syntax and usage of the Bison declarations section. 
  2865. <li><a accesskey="3" href="#Grammar-Rules">Grammar Rules</a>:      Syntax and usage of the grammar rules section. 
  2866. <li><a accesskey="4" href="#Epilogue">Epilogue</a>:           Syntax and usage of the epilogue. 
  2867. </ul>
  2868.  
  2869. <div class="node">
  2870. <p><hr>
  2871. <a name="Prologue"></a>
  2872. Next: <a rel="next" accesskey="n" href="#Bison-Declarations">Bison Declarations</a>,
  2873. Up: <a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>
  2874.  
  2875. </div>
  2876.  
  2877. <h4 class="subsection">3.1.1 The prologue</h4>
  2878.  
  2879. <p><a name="index-declarations-section-69"></a><a name="index-Prologue-70"></a><a name="index-declarations-71"></a>
  2880. The <var>Prologue</var> section contains macro definitions and
  2881. declarations of functions and variables that are used in the actions in the
  2882. grammar rules.  These are copied to the beginning of the parser file so
  2883. that they precede the definition of <code>yyparse</code>.  You can use
  2884. `<samp><span class="samp">#include</span></samp>' to get the declarations from a header file.  If you don't
  2885. need any C declarations, you may omit the `<samp><span class="samp">%{</span></samp>' and `<samp><span class="samp">%}</span></samp>'
  2886. delimiters that bracket this section.
  2887.  
  2888.    <p>You may have more than one <var>Prologue</var> section, intermixed with the
  2889. <var>Bison declarations</var>.  This allows you to have C and Bison
  2890. declarations that refer to each other.  For example, the <code>%union</code>
  2891. declaration may use types defined in a header file, and you may wish to
  2892. prototype functions that take arguments of type <code>YYSTYPE</code>.  This
  2893. can be done with two <var>Prologue</var> blocks, one before and one after the
  2894. <code>%union</code> declaration.
  2895.  
  2896. <pre class="smallexample">     %{
  2897.        #include <stdio.h>
  2898.        #include "ptypes.h"
  2899.      %}
  2900.      
  2901.      %union {
  2902.        long n;
  2903.        tree t;  /* <code>tree</code><span class="roman"> is defined in <samp>ptypes.h</samp>.</span> */
  2904.      }
  2905.      
  2906.      %{
  2907.        static void print_token_value (FILE *, int, YYSTYPE);
  2908.        #define YYPRINT(F, N, L) print_token_value (F, N, L)
  2909.      %}
  2910.      
  2911.      ...
  2912. </pre>
  2913.    <div class="node">
  2914. <p><hr>
  2915. <a name="Bison-Declarations"></a>
  2916. Next: <a rel="next" accesskey="n" href="#Grammar-Rules">Grammar Rules</a>,
  2917. Previous: <a rel="previous" accesskey="p" href="#Prologue">Prologue</a>,
  2918. Up: <a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>
  2919.  
  2920. </div>
  2921.  
  2922. <h4 class="subsection">3.1.2 The Bison Declarations Section</h4>
  2923.  
  2924. <p><a name="index-Bison-declarations-_0028introduction_0029-72"></a><a name="index-declarations_002c-Bison-_0028introduction_0029-73"></a>
  2925. The <var>Bison declarations</var> section contains declarations that define
  2926. terminal and nonterminal symbols, specify precedence, and so on. 
  2927. In some simple grammars you may not need any declarations. 
  2928. See <a href="#Declarations">Bison Declarations</a>.
  2929.  
  2930. <div class="node">
  2931. <p><hr>
  2932. <a name="Grammar-Rules"></a>
  2933. Next: <a rel="next" accesskey="n" href="#Epilogue">Epilogue</a>,
  2934. Previous: <a rel="previous" accesskey="p" href="#Bison-Declarations">Bison Declarations</a>,
  2935. Up: <a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>
  2936.  
  2937. </div>
  2938.  
  2939. <h4 class="subsection">3.1.3 The Grammar Rules Section</h4>
  2940.  
  2941. <p><a name="index-grammar-rules-section-74"></a><a name="index-rules-section-for-grammar-75"></a>
  2942. The <dfn>grammar rules</dfn> section contains one or more Bison grammar
  2943. rules, and nothing else.  See <a href="#Rules">Syntax of Grammar Rules</a>.
  2944.  
  2945.    <p>There must always be at least one grammar rule, and the first
  2946. `<samp><span class="samp">%%</span></samp>' (which precedes the grammar rules) may never be omitted even
  2947. if it is the first thing in the file.
  2948.  
  2949. <div class="node">
  2950. <p><hr>
  2951. <a name="Epilogue"></a>
  2952. Previous: <a rel="previous" accesskey="p" href="#Grammar-Rules">Grammar Rules</a>,
  2953. Up: <a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>
  2954.  
  2955. </div>
  2956.  
  2957. <h4 class="subsection">3.1.4 The epilogue</h4>
  2958.  
  2959. <p><a name="index-additional-C-code-section-76"></a><a name="index-epilogue-77"></a><a name="index-C-code_002c-section-for-additional-78"></a>
  2960. The <var>Epilogue</var> is copied verbatim to the end of the parser file, just as
  2961. the <var>Prologue</var> is copied to the beginning.  This is the most convenient
  2962. place to put anything that you want to have in the parser file but which need
  2963. not come before the definition of <code>yyparse</code>.  For example, the
  2964. definitions of <code>yylex</code> and <code>yyerror</code> often go here.  Because
  2965. C requires functions to be declared before being used, you often need
  2966. to declare functions like <code>yylex</code> and <code>yyerror</code> in the Prologue,
  2967. even if you define them int he Epilogue. 
  2968. See <a href="#Interface">Parser C-Language Interface</a>.
  2969.  
  2970.    <p>If the last section is empty, you may omit the `<samp><span class="samp">%%</span></samp>' that separates it
  2971. from the grammar rules.
  2972.  
  2973.    <p>The Bison parser itself contains many macros and identifiers whose
  2974. names start with `<samp><span class="samp">yy</span></samp>' or `<samp><span class="samp">YY</span></samp>', so it is a
  2975. good idea to avoid using any such names (except those documented in this
  2976. manual) in the epilogue of the grammar file.
  2977.  
  2978. <div class="node">
  2979. <p><hr>
  2980. <a name="Symbols"></a>
  2981. Next: <a rel="next" accesskey="n" href="#Rules">Rules</a>,
  2982. Previous: <a rel="previous" accesskey="p" href="#Grammar-Outline">Grammar Outline</a>,
  2983. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  2984.  
  2985. </div>
  2986.  
  2987. <h3 class="section">3.2 Symbols, Terminal and Nonterminal</h3>
  2988.  
  2989. <p><a name="index-nonterminal-symbol-79"></a><a name="index-terminal-symbol-80"></a><a name="index-token-type-81"></a><a name="index-symbol-82"></a>
  2990. <dfn>Symbols</dfn> in Bison grammars represent the grammatical classifications
  2991. of the language.
  2992.  
  2993.    <p>A <dfn>terminal symbol</dfn> (also known as a <dfn>token type</dfn>) represents a
  2994. class of syntactically equivalent tokens.  You use the symbol in grammar
  2995. rules to mean that a token in that class is allowed.  The symbol is
  2996. represented in the Bison parser by a numeric code, and the <code>yylex</code>
  2997. function returns a token type code to indicate what kind of token has been
  2998. read.  You don't need to know what the code value is; you can use the
  2999. symbol to stand for it.
  3000.  
  3001.    <p>A <dfn>nonterminal symbol</dfn> stands for a class of syntactically equivalent
  3002. groupings.  The symbol name is used in writing grammar rules.  By convention,
  3003. it should be all lower case.
  3004.  
  3005.    <p>Symbol names can contain letters, digits (not at the beginning),
  3006. underscores and periods.  Periods make sense only in nonterminals.
  3007.  
  3008.    <p>There are three ways of writing terminal symbols in the grammar:
  3009.  
  3010.      <ul>
  3011. <li>A <dfn>named token type</dfn> is written with an identifier, like an
  3012. identifier in C.  By convention, it should be all upper case.  Each
  3013. such name must be defined with a Bison declaration such as
  3014. <code>%token</code>.  See <a href="#Token-Decl">Token Type Names</a>.
  3015.  
  3016.      <li><a name="index-character-token-83"></a><a name="index-literal-token-84"></a><a name="index-single_002dcharacter-literal-85"></a>A <dfn>character token type</dfn> (or <dfn>literal character token</dfn>) is
  3017. written in the grammar using the same syntax used in C for character
  3018. constants; for example, <code>'+'</code> is a character token type.  A
  3019. character token type doesn't need to be declared unless you need to
  3020. specify its semantic value data type (see <a href="#Value-Type">Data Types of Semantic Values</a>), associativity, or precedence (see <a href="#Precedence">Operator Precedence</a>).
  3021.  
  3022.      <p>By convention, a character token type is used only to represent a
  3023. token that consists of that particular character.  Thus, the token
  3024. type <code>'+'</code> is used to represent the character `<samp><span class="samp">+</span></samp>' as a
  3025. token.  Nothing enforces this convention, but if you depart from it,
  3026. your program will confuse other readers.
  3027.  
  3028.      <p>All the usual escape sequences used in character literals in C can be
  3029. used in Bison as well, but you must not use the null character as a
  3030. character literal because its numeric code, zero, signifies
  3031. end-of-input (see <a href="#Calling-Convention">Calling Convention for <code>yylex</code></a>).  Also, unlike standard C, trigraphs have no
  3032. special meaning in Bison character literals, nor is backslash-newline
  3033. allowed.
  3034.  
  3035.      <li><a name="index-string-token-86"></a><a name="index-literal-string-token-87"></a><a name="index-multicharacter-literal-88"></a>A <dfn>literal string token</dfn> is written like a C string constant; for
  3036. example, <code>"<="</code> is a literal string token.  A literal string token
  3037. doesn't need to be declared unless you need to specify its semantic
  3038. value data type (see <a href="#Value-Type">Value Type</a>), associativity, or precedence
  3039. (see <a href="#Precedence">Precedence</a>).
  3040.  
  3041.      <p>You can associate the literal string token with a symbolic name as an
  3042. alias, using the <code>%token</code> declaration (see <a href="#Token-Decl">Token Declarations</a>).  If you don't do that, the lexical analyzer has to
  3043. retrieve the token number for the literal string token from the
  3044. <code>yytname</code> table (see <a href="#Calling-Convention">Calling Convention</a>).
  3045.  
  3046.      <p><strong>Warning</strong>: literal string tokens do not work in Yacc.
  3047.  
  3048.      <p>By convention, a literal string token is used only to represent a token
  3049. that consists of that particular string.  Thus, you should use the token
  3050. type <code>"<="</code> to represent the string `<samp><span class="samp"><=</span></samp>' as a token.  Bison
  3051. does not enforce this convention, but if you depart from it, people who
  3052. read your program will be confused.
  3053.  
  3054.      <p>All the escape sequences used in string literals in C can be used in
  3055. Bison as well.  However, unlike Standard C, trigraphs have no special
  3056. meaning in Bison string literals, nor is backslash-newline allowed.  A
  3057. literal string token must contain two or more characters; for a token
  3058. containing just one character, use a character token (see above). 
  3059. </ul>
  3060.  
  3061.    <p>How you choose to write a terminal symbol has no effect on its
  3062. grammatical meaning.  That depends only on where it appears in rules and
  3063. on when the parser function returns that symbol.
  3064.  
  3065.    <p>The value returned by <code>yylex</code> is always one of the terminal
  3066. symbols, except that a zero or negative value signifies end-of-input. 
  3067. Whichever way you write the token type in the grammar rules, you write
  3068. it the same way in the definition of <code>yylex</code>.  The numeric code
  3069. for a character token type is simply the positive numeric code of the
  3070. character, so <code>yylex</code> can use the identical value to generate the
  3071. requisite code, though you may need to convert it to <code>unsigned
  3072. char</code> to avoid sign-extension on hosts where <code>char</code> is signed. 
  3073. Each named token type becomes a C macro in
  3074. the parser file, so <code>yylex</code> can use the name to stand for the code. 
  3075. (This is why periods don't make sense in terminal symbols.) 
  3076. See <a href="#Calling-Convention">Calling Convention for <code>yylex</code></a>.
  3077.  
  3078.    <p>If <code>yylex</code> is defined in a separate file, you need to arrange for the
  3079. token-type macro definitions to be available there.  Use the `<samp><span class="samp">-d</span></samp>'
  3080. option when you run Bison, so that it will write these macro definitions
  3081. into a separate header file <samp><var>name</var><span class="file">.tab.h</span></samp> which you can include
  3082. in the other source files that need it.  See <a href="#Invocation">Invoking Bison</a>.
  3083.  
  3084.    <p>If you want to write a grammar that is portable to any Standard C
  3085. host, you must use only non-null character tokens taken from the basic
  3086. execution character set of Standard C.  This set consists of the ten
  3087. digits, the 52 lower- and upper-case English letters, and the
  3088. characters in the following C-language string:
  3089.  
  3090. <pre class="example">     "\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_{|}~"
  3091. </pre>
  3092.    <p>The <code>yylex</code> function and Bison must use a consistent character
  3093. set and encoding for character tokens.  For example, if you run Bison in an
  3094. <acronym>ASCII</acronym> environment, but then compile and run the resulting program
  3095. in an environment that uses an incompatible character set like
  3096. <acronym>EBCDIC</acronym>, the resulting program may not work because the
  3097. tables generated by Bison will assume <acronym>ASCII</acronym> numeric values for
  3098. character tokens.  It is standard
  3099. practice for software distributions to contain C source files that
  3100. were generated by Bison in an <acronym>ASCII</acronym> environment, so installers on
  3101. platforms that are incompatible with <acronym>ASCII</acronym> must rebuild those
  3102. files before compiling them.
  3103.  
  3104.    <p>The symbol <code>error</code> is a terminal symbol reserved for error recovery
  3105. (see <a href="#Error-Recovery">Error Recovery</a>); you shouldn't use it for any other purpose. 
  3106. In particular, <code>yylex</code> should never return this value.  The default
  3107. value of the error token is 256, unless you explicitly assigned 256 to
  3108. one of your tokens with a <code>%token</code> declaration.
  3109.  
  3110. <div class="node">
  3111. <p><hr>
  3112. <a name="Rules"></a>
  3113. Next: <a rel="next" accesskey="n" href="#Recursion">Recursion</a>,
  3114. Previous: <a rel="previous" accesskey="p" href="#Symbols">Symbols</a>,
  3115. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  3116.  
  3117. </div>
  3118.  
  3119. <h3 class="section">3.3 Syntax of Grammar Rules</h3>
  3120.  
  3121. <p><a name="index-rule-syntax-89"></a><a name="index-grammar-rule-syntax-90"></a><a name="index-syntax-of-grammar-rules-91"></a>
  3122. A Bison grammar rule has the following general form:
  3123.  
  3124. <pre class="example">     <var>result</var>: <var>components</var>...
  3125.              ;
  3126. </pre>
  3127.    <p class="noindent">where <var>result</var> is the nonterminal symbol that this rule describes,
  3128. and <var>components</var> are various terminal and nonterminal symbols that
  3129. are put together by this rule (see <a href="#Symbols">Symbols</a>).
  3130.  
  3131.    <p>For example,
  3132.  
  3133. <pre class="example">     exp:      exp '+' exp
  3134.              ;
  3135. </pre>
  3136.    <p class="noindent">says that two groupings of type <code>exp</code>, with a `<samp><span class="samp">+</span></samp>' token in between,
  3137. can be combined into a larger grouping of type <code>exp</code>.
  3138.  
  3139.    <p>White space in rules is significant only to separate symbols.  You can add
  3140. extra white space as you wish.
  3141.  
  3142.    <p>Scattered among the components can be <var>actions</var> that determine
  3143. the semantics of the rule.  An action looks like this:
  3144.  
  3145. <pre class="example">     {<var>C statements</var>}
  3146. </pre>
  3147.    <p class="noindent">Usually there is only one action and it follows the components. 
  3148. See <a href="#Actions">Actions</a>.
  3149.  
  3150.    <p><a name="index-g_t_007c-92"></a>Multiple rules for the same <var>result</var> can be written separately or can
  3151. be joined with the vertical-bar character `<samp><span class="samp">|</span></samp>' as follows:
  3152.  
  3153. <p class="noindent">They are still considered distinct rules even when joined in this way.
  3154.  
  3155.    <p>If <var>components</var> in a rule is empty, it means that <var>result</var> can
  3156. match the empty string.  For example, here is how to define a
  3157. comma-separated sequence of zero or more <code>exp</code> groupings:
  3158.  
  3159. <pre class="example">     expseq:   /* empty */
  3160.              | expseq1
  3161.              ;
  3162.      
  3163.      expseq1:  exp
  3164.              | expseq1 ',' exp
  3165.              ;
  3166. </pre>
  3167.    <p class="noindent">It is customary to write a comment `<samp><span class="samp">/* empty */</span></samp>' in each rule
  3168. with no components.
  3169.  
  3170. <div class="node">
  3171. <p><hr>
  3172. <a name="Recursion"></a>
  3173. Next: <a rel="next" accesskey="n" href="#Semantics">Semantics</a>,
  3174. Previous: <a rel="previous" accesskey="p" href="#Rules">Rules</a>,
  3175. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  3176.  
  3177. </div>
  3178.  
  3179. <h3 class="section">3.4 Recursive Rules</h3>
  3180.  
  3181. <p><a name="index-recursive-rule-93"></a>
  3182. A rule is called <dfn>recursive</dfn> when its <var>result</var> nonterminal appears
  3183. also on its right hand side.  Nearly all Bison grammars need to use
  3184. recursion, because that is the only way to define a sequence of any number
  3185. of a particular thing.  Consider this recursive definition of a
  3186. comma-separated sequence of one or more expressions:
  3187.  
  3188. <pre class="example">     expseq1:  exp
  3189.              | expseq1 ',' exp
  3190.              ;
  3191. </pre>
  3192.    <p><a name="index-left-recursion-94"></a><a name="index-right-recursion-95"></a>Since the recursive use of <code>expseq1</code> is the leftmost symbol in the
  3193. right hand side, we call this <dfn>left recursion</dfn>.  By contrast, here
  3194. the same construct is defined using <dfn>right recursion</dfn>:
  3195.  
  3196. <pre class="example">     expseq1:  exp
  3197.              | exp ',' expseq1
  3198.              ;
  3199. </pre>
  3200.    <p class="noindent">Any kind of sequence can be defined using either left recursion or right
  3201. recursion, but you should always use left recursion, because it can
  3202. parse a sequence of any number of elements with bounded stack space. 
  3203. Right recursion uses up space on the Bison stack in proportion to the
  3204. number of elements in the sequence, because all the elements must be
  3205. shifted onto the stack before the rule can be applied even once. 
  3206. See <a href="#Algorithm">The Bison Parser Algorithm</a>, for further explanation
  3207. of this.
  3208.  
  3209.    <p><a name="index-mutual-recursion-96"></a><dfn>Indirect</dfn> or <dfn>mutual</dfn> recursion occurs when the result of the
  3210. rule does not appear directly on its right hand side, but does appear
  3211. in rules for other nonterminals which do appear on its right hand
  3212. side.
  3213.  
  3214.    <p>For example:
  3215.  
  3216. <pre class="example">     expr:     primary
  3217.              | primary '+' primary
  3218.              ;
  3219.      
  3220.      primary:  constant
  3221.              | '(' expr ')'
  3222.              ;
  3223. </pre>
  3224.    <p class="noindent">defines two mutually-recursive nonterminals, since each refers to the
  3225. other.
  3226.  
  3227. <div class="node">
  3228. <p><hr>
  3229. <a name="Semantics"></a>
  3230. Next: <a rel="next" accesskey="n" href="#Locations">Locations</a>,
  3231. Previous: <a rel="previous" accesskey="p" href="#Recursion">Recursion</a>,
  3232. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  3233.  
  3234. </div>
  3235.  
  3236. <h3 class="section">3.5 Defining Language Semantics</h3>
  3237.  
  3238. <p><a name="index-defining-language-semantics-97"></a><a name="index-language-semantics_002c-defining-98"></a>
  3239. The grammar rules for a language determine only the syntax.  The semantics
  3240. are determined by the semantic values associated with various tokens and
  3241. groupings, and by the actions taken when various groupings are recognized.
  3242.  
  3243.    <p>For example, the calculator calculates properly because the value
  3244. associated with each expression is the proper number; it adds properly
  3245. because the action for the grouping `<samp><var>x</var><span class="samp"> + </span><var>y</var></samp>'<!-- /@w --> is to add
  3246. the numbers associated with <var>x</var> and <var>y</var>.
  3247.  
  3248. <ul class="menu">
  3249. <li><a accesskey="1" href="#Value-Type">Value Type</a>:         Specifying one data type for all semantic values. 
  3250. <li><a accesskey="2" href="#Multiple-Types">Multiple Types</a>:     Specifying several alternative data types. 
  3251. <li><a accesskey="3" href="#Actions">Actions</a>:            An action is the semantic definition of a grammar rule. 
  3252. <li><a accesskey="4" href="#Action-Types">Action Types</a>:       Specifying data types for actions to operate on. 
  3253. <li><a accesskey="5" href="#Mid_002dRule-Actions">Mid-Rule Actions</a>:   Most actions go at the end of a rule. 
  3254.                       This says when, why and how to use the exceptional
  3255.                         action in the middle of a rule. 
  3256. </ul>
  3257.  
  3258. <div class="node">
  3259. <p><hr>
  3260. <a name="Value-Type"></a>
  3261. Next: <a rel="next" accesskey="n" href="#Multiple-Types">Multiple Types</a>,
  3262. Up: <a rel="up" accesskey="u" href="#Semantics">Semantics</a>
  3263.  
  3264. </div>
  3265.  
  3266. <h4 class="subsection">3.5.1 Data Types of Semantic Values</h4>
  3267.  
  3268. <p><a name="index-semantic-value-type-99"></a><a name="index-value-type_002c-semantic-100"></a><a name="index-data-types-of-semantic-values-101"></a><a name="index-default-data-type-102"></a>
  3269. In a simple program it may be sufficient to use the same data type for
  3270. the semantic values of all language constructs.  This was true in the
  3271. <acronym>RPN</acronym> and infix calculator examples (see <a href="#RPN-Calc">Reverse Polish Notation Calculator</a>).
  3272.  
  3273.    <p>Bison's default is to use type <code>int</code> for all semantic values.  To
  3274. specify some other type, define <code>YYSTYPE</code> as a macro, like this:
  3275.  
  3276. <pre class="example">     #define YYSTYPE double
  3277. </pre>
  3278.    <p class="noindent">This macro definition must go in the prologue of the grammar file
  3279. (see <a href="#Grammar-Outline">Outline of a Bison Grammar</a>).
  3280.  
  3281. <div class="node">
  3282. <p><hr>
  3283. <a name="Multiple-Types"></a>
  3284. Next: <a rel="next" accesskey="n" href="#Actions">Actions</a>,
  3285. Previous: <a rel="previous" accesskey="p" href="#Value-Type">Value Type</a>,
  3286. Up: <a rel="up" accesskey="u" href="#Semantics">Semantics</a>
  3287.  
  3288. </div>
  3289.  
  3290. <h4 class="subsection">3.5.2 More Than One Value Type</h4>
  3291.  
  3292. <p>In most programs, you will need different data types for different kinds
  3293. of tokens and groupings.  For example, a numeric constant may need type
  3294. <code>int</code> or <code>long</code>, while a string constant needs type <code>char *</code>,
  3295. and an identifier might need a pointer to an entry in the symbol table.
  3296.  
  3297.    <p>To use more than one data type for semantic values in one parser, Bison
  3298. requires you to do two things:
  3299.  
  3300.      <ul>
  3301. <li>Specify the entire collection of possible data types, with the
  3302. <code>%union</code> Bison declaration (see <a href="#Union-Decl">The Collection of Value Types</a>).
  3303.  
  3304.      <li>Choose one of those types for each symbol (terminal or nonterminal) for
  3305. which semantic values are used.  This is done for tokens with the
  3306. <code>%token</code> Bison declaration (see <a href="#Token-Decl">Token Type Names</a>)
  3307. and for groupings with the <code>%type</code> Bison declaration (see <a href="#Type-Decl">Nonterminal Symbols</a>). 
  3308. </ul>
  3309.  
  3310. <div class="node">
  3311. <p><hr>
  3312. <a name="Actions"></a>
  3313. Next: <a rel="next" accesskey="n" href="#Action-Types">Action Types</a>,
  3314. Previous: <a rel="previous" accesskey="p" href="#Multiple-Types">Multiple Types</a>,
  3315. Up: <a rel="up" accesskey="u" href="#Semantics">Semantics</a>
  3316.  
  3317. </div>
  3318.  
  3319. <h4 class="subsection">3.5.3 Actions</h4>
  3320.  
  3321. <p><a name="index-action-103"></a><a name="index-g_t_0024_0024-104"></a><a name="index-g_t_0024_0040var_007bn_007d-105"></a>
  3322. An action accompanies a syntactic rule and contains C code to be executed
  3323. each time an instance of that rule is recognized.  The task of most actions
  3324. is to compute a semantic value for the grouping built by the rule from the
  3325. semantic values associated with tokens or smaller groupings.
  3326.  
  3327.    <p>An action consists of C statements surrounded by braces, much like a
  3328. compound statement in C.  An action can contain any sequence of C
  3329. statements.  Bison does not look for trigraphs, though, so if your C
  3330. code uses trigraphs you should ensure that they do not affect the
  3331. nesting of braces or the boundaries of comments, strings, or character
  3332. literals.
  3333.  
  3334.    <p>An action can be placed at any position in the rule;
  3335. it is executed at that position.  Most rules have just one action at the
  3336. end of the rule, following all the components.  Actions in the middle of
  3337. a rule are tricky and used only for special purposes (see <a href="#Mid_002dRule-Actions">Actions in Mid-Rule</a>).
  3338.  
  3339.    <p>The C code in an action can refer to the semantic values of the components
  3340. matched by the rule with the construct <code>$</code><var>n</var>, which stands for
  3341. the value of the <var>n</var>th component.  The semantic value for the grouping
  3342. being constructed is <code>$$</code>.  (Bison translates both of these constructs
  3343. into array element references when it copies the actions into the parser
  3344. file.)
  3345.  
  3346.    <p>Here is a typical example:
  3347.  
  3348. <pre class="example">     exp:    ...
  3349.              | exp '+' exp
  3350.                  { $$ = $1 + $3; }
  3351. </pre>
  3352.    <p class="noindent">This rule constructs an <code>exp</code> from two smaller <code>exp</code> groupings
  3353. connected by a plus-sign token.  In the action, <code>$1</code> and <code>$3</code>
  3354. refer to the semantic values of the two component <code>exp</code> groupings,
  3355. which are the first and third symbols on the right hand side of the rule. 
  3356. The sum is stored into <code>$$</code> so that it becomes the semantic value of
  3357. the addition-expression just recognized by the rule.  If there were a
  3358. useful semantic value associated with the `<samp><span class="samp">+</span></samp>' token, it could be
  3359. referred to as <code>$2</code>.
  3360.  
  3361.    <p>Note that the vertical-bar character `<samp><span class="samp">|</span></samp>' is really a rule
  3362. separator, and actions are attached to a single rule.  This is a
  3363. difference with tools like Flex, for which `<samp><span class="samp">|</span></samp>' stands for either
  3364. “or”, or “the same action as that of the next rule”.  In the
  3365. following example, the action is triggered only when `<samp><span class="samp">b</span></samp>' is found:
  3366.  
  3367. <pre class="example">     a-or-b: 'a'|'b'   { a_or_b_found = 1; };
  3368. </pre>
  3369.    <p><a name="index-default-action-106"></a>If you don't specify an action for a rule, Bison supplies a default:
  3370. <code>$$ = $1</code>.<!-- /@w -->  Thus, the value of the first symbol in the rule
  3371. becomes the value of the whole rule.  Of course, the default action is
  3372. valid only if the two data types match.  There is no meaningful default
  3373. action for an empty rule; every empty rule must have an explicit action
  3374. unless the rule's value does not matter.
  3375.  
  3376.    <p><code>$</code><var>n</var> with <var>n</var> zero or negative is allowed for reference
  3377. to tokens and groupings on the stack <em>before</em> those that match the
  3378. current rule.  This is a very risky practice, and to use it reliably
  3379. you must be certain of the context in which the rule is applied.  Here
  3380. is a case in which you can use this reliably:
  3381.  
  3382. <pre class="example">     foo:      expr bar '+' expr  { ... }
  3383.              | expr bar '-' expr  { ... }
  3384.              ;
  3385.      
  3386.      bar:      /* empty */
  3387.              { previous_expr = $0; }
  3388.              ;
  3389. </pre>
  3390.    <p>As long as <code>bar</code> is used only in the fashion shown here, <code>$0</code>
  3391. always refers to the <code>expr</code> which precedes <code>bar</code> in the
  3392. definition of <code>foo</code>.
  3393.  
  3394. <div class="node">
  3395. <p><hr>
  3396. <a name="Action-Types"></a>
  3397. Next: <a rel="next" accesskey="n" href="#Mid_002dRule-Actions">Mid-Rule Actions</a>,
  3398. Previous: <a rel="previous" accesskey="p" href="#Actions">Actions</a>,
  3399. Up: <a rel="up" accesskey="u" href="#Semantics">Semantics</a>
  3400.  
  3401. </div>
  3402.  
  3403. <h4 class="subsection">3.5.4 Data Types of Values in Actions</h4>
  3404.  
  3405. <p><a name="index-action-data-types-107"></a><a name="index-data-types-in-actions-108"></a>
  3406. If you have chosen a single data type for semantic values, the <code>$$</code>
  3407. and <code>$</code><var>n</var> constructs always have that data type.
  3408.  
  3409.    <p>If you have used <code>%union</code> to specify a variety of data types, then you
  3410. must declare a choice among these types for each terminal or nonterminal
  3411. symbol that can have a semantic value.  Then each time you use <code>$$</code> or
  3412. <code>$</code><var>n</var>, its data type is determined by which symbol it refers to
  3413. in the rule.  In this example,
  3414.  
  3415. <pre class="example">     exp:    ...
  3416.              | exp '+' exp
  3417.                  { $$ = $1 + $3; }
  3418. </pre>
  3419.    <p class="noindent"><code>$1</code> and <code>$3</code> refer to instances of <code>exp</code>, so they all
  3420. have the data type declared for the nonterminal symbol <code>exp</code>.  If
  3421. <code>$2</code> were used, it would have the data type declared for the
  3422. terminal symbol <code>'+'</code>, whatever that might be.
  3423.  
  3424.    <p>Alternatively, you can specify the data type when you refer to the value,
  3425. by inserting `<samp><span class="samp"><</span><var>type</var><span class="samp">></span></samp>' after the `<samp><span class="samp">$</span></samp>' at the beginning of the
  3426. reference.  For example, if you have defined types as shown here:
  3427.  
  3428. <pre class="example">     %union {
  3429.        int itype;
  3430.        double dtype;
  3431.      }
  3432. </pre>
  3433.    <p class="noindent">then you can write <code>$<itype>1</code> to refer to the first subunit of the
  3434. rule as an integer, or <code>$<dtype>1</code> to refer to it as a double.
  3435.  
  3436. <div class="node">
  3437. <p><hr>
  3438. <a name="Mid-Rule-Actions"></a>
  3439. <a name="Mid_002dRule-Actions"></a>
  3440. Previous: <a rel="previous" accesskey="p" href="#Action-Types">Action Types</a>,
  3441. Up: <a rel="up" accesskey="u" href="#Semantics">Semantics</a>
  3442.  
  3443. </div>
  3444.  
  3445. <h4 class="subsection">3.5.5 Actions in Mid-Rule</h4>
  3446.  
  3447. <p><a name="index-actions-in-mid_002drule-109"></a><a name="index-mid_002drule-actions-110"></a>
  3448. Occasionally it is useful to put an action in the middle of a rule. 
  3449. These actions are written just like usual end-of-rule actions, but they
  3450. are executed before the parser even recognizes the following components.
  3451.  
  3452.    <p>A mid-rule action may refer to the components preceding it using
  3453. <code>$</code><var>n</var>, but it may not refer to subsequent components because
  3454. it is run before they are parsed.
  3455.  
  3456.    <p>The mid-rule action itself counts as one of the components of the rule. 
  3457. This makes a difference when there is another action later in the same rule
  3458. (and usually there is another at the end): you have to count the actions
  3459. along with the symbols when working out which number <var>n</var> to use in
  3460. <code>$</code><var>n</var>.
  3461.  
  3462.    <p>The mid-rule action can also have a semantic value.  The action can set
  3463. its value with an assignment to <code>$$</code>, and actions later in the rule
  3464. can refer to the value using <code>$</code><var>n</var>.  Since there is no symbol
  3465. to name the action, there is no way to declare a data type for the value
  3466. in advance, so you must use the `<samp><span class="samp">$<...></span><var>n</var></samp>' construct to
  3467. specify a data type each time you refer to this value.
  3468.  
  3469.    <p>There is no way to set the value of the entire rule with a mid-rule
  3470. action, because assignments to <code>$$</code> do not have that effect.  The
  3471. only way to set the value for the entire rule is with an ordinary action
  3472. at the end of the rule.
  3473.  
  3474.    <p>Here is an example from a hypothetical compiler, handling a <code>let</code>
  3475. statement that looks like `<samp><span class="samp">let (</span><var>variable</var><span class="samp">) </span><var>statement</var></samp>' and
  3476. serves to create a variable named <var>variable</var> temporarily for the
  3477. duration of <var>statement</var>.  To parse this construct, we must put
  3478. <var>variable</var> into the symbol table while <var>statement</var> is parsed, then
  3479. remove it afterward.  Here is how it is done:
  3480.  
  3481. <pre class="example">     stmt:   LET '(' var ')'
  3482.                      { $<context>$ = push_context ();
  3483.                        declare_variable ($3); }
  3484.              stmt    { $$ = $6;
  3485.                        pop_context ($<context>5); }
  3486. </pre>
  3487.    <p class="noindent">As soon as `<samp><span class="samp">let (</span><var>variable</var><span class="samp">)</span></samp>' has been recognized, the first
  3488. action is run.  It saves a copy of the current semantic context (the
  3489. list of accessible variables) as its semantic value, using alternative
  3490. <code>context</code> in the data-type union.  Then it calls
  3491. <code>declare_variable</code> to add the new variable to that list.  Once the
  3492. first action is finished, the embedded statement <code>stmt</code> can be
  3493. parsed.  Note that the mid-rule action is component number 5, so the
  3494. `<samp><span class="samp">stmt</span></samp>' is component number 6.
  3495.  
  3496.    <p>After the embedded statement is parsed, its semantic value becomes the
  3497. value of the entire <code>let</code>-statement.  Then the semantic value from the
  3498. earlier action is used to restore the prior list of variables.  This
  3499. removes the temporary <code>let</code>-variable from the list so that it won't
  3500. appear to exist while the rest of the program is parsed.
  3501.  
  3502.    <p>Taking action before a rule is completely recognized often leads to
  3503. conflicts since the parser must commit to a parse in order to execute the
  3504. action.  For example, the following two rules, without mid-rule actions,
  3505. can coexist in a working parser because the parser can shift the open-brace
  3506. token and look at what follows before deciding whether there is a
  3507. declaration or not:
  3508.  
  3509. <pre class="example">     compound: '{' declarations statements '}'
  3510.              | '{' statements '}'
  3511.              ;
  3512. </pre>
  3513.    <p class="noindent">But when we add a mid-rule action as follows, the rules become nonfunctional:
  3514.  
  3515. <pre class="example">     compound: { prepare_for_local_variables (); }
  3516.                '{' declarations statements '}'
  3517.              | '{' statements '}'
  3518.              ;
  3519. </pre>
  3520.    <p class="noindent">Now the parser is forced to decide whether to run the mid-rule action
  3521. when it has read no farther than the open-brace.  In other words, it
  3522. must commit to using one rule or the other, without sufficient
  3523. information to do it correctly.  (The open-brace token is what is called
  3524. the <dfn>look-ahead</dfn> token at this time, since the parser is still
  3525. deciding what to do about it.  See <a href="#Look_002dAhead">Look-Ahead Tokens</a>.)
  3526.  
  3527.    <p>You might think that you could correct the problem by putting identical
  3528. actions into the two rules, like this:
  3529.  
  3530. <pre class="example">     compound: { prepare_for_local_variables (); }
  3531.                '{' declarations statements '}'
  3532.              | { prepare_for_local_variables (); }
  3533.                '{' statements '}'
  3534.              ;
  3535. </pre>
  3536.    <p class="noindent">But this does not help, because Bison does not realize that the two actions
  3537. are identical.  (Bison never tries to understand the C code in an action.)
  3538.  
  3539.    <p>If the grammar is such that a declaration can be distinguished from a
  3540. statement by the first token (which is true in C), then one solution which
  3541. does work is to put the action after the open-brace, like this:
  3542.  
  3543. <pre class="example">     compound: '{' { prepare_for_local_variables (); }
  3544.                declarations statements '}'
  3545.              | '{' statements '}'
  3546.              ;
  3547. </pre>
  3548.    <p class="noindent">Now the first token of the following declaration or statement,
  3549. which would in any case tell Bison which rule to use, can still do so.
  3550.  
  3551.    <p>Another solution is to bury the action inside a nonterminal symbol which
  3552. serves as a subroutine:
  3553.  
  3554. <pre class="example">     subroutine: /* empty */
  3555.                { prepare_for_local_variables (); }
  3556.              ;
  3557.      
  3558.      compound: subroutine
  3559.                '{' declarations statements '}'
  3560.              | subroutine
  3561.                '{' statements '}'
  3562.              ;
  3563. </pre>
  3564.    <p class="noindent">Now Bison can execute the action in the rule for <code>subroutine</code> without
  3565. deciding which rule for <code>compound</code> it will eventually use.  Note that
  3566. the action is now at the end of its rule.  Any mid-rule action can be
  3567. converted to an end-of-rule action in this way, and this is what Bison
  3568. actually does to implement mid-rule actions.
  3569.  
  3570. <div class="node">
  3571. <p><hr>
  3572. <a name="Locations"></a>
  3573. Next: <a rel="next" accesskey="n" href="#Declarations">Declarations</a>,
  3574. Previous: <a rel="previous" accesskey="p" href="#Semantics">Semantics</a>,
  3575. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  3576.  
  3577. </div>
  3578.  
  3579. <h3 class="section">3.6 Tracking Locations</h3>
  3580.  
  3581. <p><a name="index-location-111"></a><a name="index-textual-position-112"></a><a name="index-position_002c-textual-113"></a>
  3582. Though grammar rules and semantic actions are enough to write a fully
  3583. functional parser, it can be useful to process some additional information,
  3584. especially symbol locations.
  3585.  
  3586. <!-- (terminal or not) ? -->
  3587. <p>The way locations are handled is defined by providing a data type, and
  3588. actions to take when rules are matched.
  3589.  
  3590. <ul class="menu">
  3591. <li><a accesskey="1" href="#Location-Type">Location Type</a>:                Specifying a data type for locations. 
  3592. <li><a accesskey="2" href="#Actions-and-Locations">Actions and Locations</a>:        Using locations in actions. 
  3593. <li><a accesskey="3" href="#Location-Default-Action">Location Default Action</a>:      Defining a general way to compute locations. 
  3594. </ul>
  3595.  
  3596. <div class="node">
  3597. <p><hr>
  3598. <a name="Location-Type"></a>
  3599. Next: <a rel="next" accesskey="n" href="#Actions-and-Locations">Actions and Locations</a>,
  3600. Up: <a rel="up" accesskey="u" href="#Locations">Locations</a>
  3601.  
  3602. </div>
  3603.  
  3604. <h4 class="subsection">3.6.1 Data Type of Locations</h4>
  3605.  
  3606. <p><a name="index-data-type-of-locations-114"></a><a name="index-default-location-type-115"></a>
  3607. Defining a data type for locations is much simpler than for semantic values,
  3608. since all tokens and groupings always use the same type.
  3609.  
  3610.    <p>The type of locations is specified by defining a macro called <code>YYLTYPE</code>. 
  3611. When <code>YYLTYPE</code> is not defined, Bison uses a default structure type with
  3612. four members:
  3613.  
  3614. <pre class="example">     typedef struct YYLTYPE
  3615.      {
  3616.        int first_line;
  3617.        int first_column;
  3618.        int last_line;
  3619.        int last_column;
  3620.      } YYLTYPE;
  3621. </pre>
  3622.    <div class="node">
  3623. <p><hr>
  3624. <a name="Actions-and-Locations"></a>
  3625. Next: <a rel="next" accesskey="n" href="#Location-Default-Action">Location Default Action</a>,
  3626. Previous: <a rel="previous" accesskey="p" href="#Location-Type">Location Type</a>,
  3627. Up: <a rel="up" accesskey="u" href="#Locations">Locations</a>
  3628.  
  3629. </div>
  3630.  
  3631. <h4 class="subsection">3.6.2 Actions and Locations</h4>
  3632.  
  3633. <p><a name="index-location-actions-116"></a><a name="index-actions_002c-location-117"></a><a name="index-g_t_0040_0040_0024-118"></a><a name="index-g_t_0040_0040_0040var_007bn_007d-119"></a>
  3634. Actions are not only useful for defining language semantics, but also for
  3635. describing the behavior of the output parser with locations.
  3636.  
  3637.    <p>The most obvious way for building locations of syntactic groupings is very
  3638. similar to the way semantic values are computed.  In a given rule, several
  3639. constructs can be used to access the locations of the elements being matched. 
  3640. The location of the <var>n</var>th component of the right hand side is
  3641. <code>@</code><var>n</var>, while the location of the left hand side grouping is
  3642. <code>@$</code>.
  3643.  
  3644.    <p>Here is a basic example using the default data type for locations:
  3645.  
  3646. <pre class="example">     exp:    ...
  3647.              | exp '/' exp
  3648.                  {
  3649.                    @$.first_column = @1.first_column;
  3650.                    @$.first_line = @1.first_line;
  3651.                    @$.last_column = @3.last_column;
  3652.                    @$.last_line = @3.last_line;
  3653.                    if ($3)
  3654.                      $$ = $1 / $3;
  3655.                    else
  3656.                      {
  3657.                        $$ = 1;
  3658.                        printf("Division by zero, l%d,c%d-l%d,c%d",
  3659.                               @3.first_line, @3.first_column,
  3660.                               @3.last_line, @3.last_column);
  3661.                      }
  3662.                  }
  3663. </pre>
  3664.    <p>As for semantic values, there is a default action for locations that is
  3665. run each time a rule is matched.  It sets the beginning of <code>@$</code> to the
  3666. beginning of the first symbol, and the end of <code>@$</code> to the end of the
  3667. last symbol.
  3668.  
  3669.    <p>With this default action, the location tracking can be fully automatic.  The
  3670. example above simply rewrites this way:
  3671.  
  3672. <pre class="example">     exp:    ...
  3673.              | exp '/' exp
  3674.                  {
  3675.                    if ($3)
  3676.                      $$ = $1 / $3;
  3677.                    else
  3678.                      {
  3679.                        $$ = 1;
  3680.                        printf("Division by zero, l%d,c%d-l%d,c%d",
  3681.                               @3.first_line, @3.first_column,
  3682.                               @3.last_line, @3.last_column);
  3683.                      }
  3684.                  }
  3685. </pre>
  3686.    <div class="node">
  3687. <p><hr>
  3688. <a name="Location-Default-Action"></a>
  3689. Previous: <a rel="previous" accesskey="p" href="#Actions-and-Locations">Actions and Locations</a>,
  3690. Up: <a rel="up" accesskey="u" href="#Locations">Locations</a>
  3691.  
  3692. </div>
  3693.  
  3694. <h4 class="subsection">3.6.3 Default Action for Locations</h4>
  3695.  
  3696. <p><a name="index-YYLLOC_005fDEFAULT-120"></a>
  3697. Actually, actions are not the best place to compute locations.  Since
  3698. locations are much more general than semantic values, there is room in
  3699. the output parser to redefine the default action to take for each
  3700. rule.  The <code>YYLLOC_DEFAULT</code> macro is invoked each time a rule is
  3701. matched, before the associated action is run.  It is also invoked
  3702. while processing a syntax error, to compute the error's location.
  3703.  
  3704.    <p>Most of the time, this macro is general enough to suppress location
  3705. dedicated code from semantic actions.
  3706.  
  3707.    <p>The <code>YYLLOC_DEFAULT</code> macro takes three parameters.  The first one is
  3708. the location of the grouping (the result of the computation).  When a
  3709. rule is matched, the second parameter is an array holding locations of
  3710. all right hand side elements of the rule being matched, and the third
  3711. parameter is the size of the rule's right hand side.  When processing
  3712. a syntax error, the second parameter is an array holding locations of
  3713. the symbols that were discarded during error processing, and the third
  3714. parameter is the number of discarded symbols.
  3715.  
  3716.    <p>By default, <code>YYLLOC_DEFAULT</code> is defined this way for simple
  3717. <acronym>LALR</acronym>(1) parsers:
  3718.  
  3719. <pre class="example">     #define YYLLOC_DEFAULT(Current, Rhs, N)          \
  3720.        Current.first_line   = Rhs[1].first_line;      \
  3721.        Current.first_column = Rhs[1].first_column;    \
  3722.        Current.last_line    = Rhs[N].last_line;       \
  3723.        Current.last_column  = Rhs[N].last_column;
  3724. </pre>
  3725.    <p class="noindent">and like this for <acronym>GLR</acronym> parsers:
  3726.  
  3727. <pre class="example">     #define YYLLOC_DEFAULT(Current, Rhs, N)          \
  3728.        Current.first_line   = YYRHSLOC(Rhs,1).first_line;      \
  3729.        Current.first_column = YYRHSLOC(Rhs,1).first_column;    \
  3730.        Current.last_line    = YYRHSLOC(Rhs,N).last_line;       \
  3731.        Current.last_column  = YYRHSLOC(Rhs,N).last_column;
  3732. </pre>
  3733.    <p>When defining <code>YYLLOC_DEFAULT</code>, you should consider that:
  3734.  
  3735.      <ul>
  3736. <li>All arguments are free of side-effects.  However, only the first one (the
  3737. result) should be modified by <code>YYLLOC_DEFAULT</code>.
  3738.  
  3739.      <li>For consistency with semantic actions, valid indexes for the location
  3740. array range from 1 to <var>n</var>. 
  3741. </ul>
  3742.  
  3743. <div class="node">
  3744. <p><hr>
  3745. <a name="Declarations"></a>
  3746. Next: <a rel="next" accesskey="n" href="#Multiple-Parsers">Multiple Parsers</a>,
  3747. Previous: <a rel="previous" accesskey="p" href="#Locations">Locations</a>,
  3748. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  3749.  
  3750. </div>
  3751.  
  3752. <h3 class="section">3.7 Bison Declarations</h3>
  3753.  
  3754. <p><a name="index-declarations_002c-Bison-121"></a><a name="index-Bison-declarations-122"></a>
  3755. The <dfn>Bison declarations</dfn> section of a Bison grammar defines the symbols
  3756. used in formulating the grammar and the data types of semantic values. 
  3757. See <a href="#Symbols">Symbols</a>.
  3758.  
  3759.    <p>All token type names (but not single-character literal tokens such as
  3760. <code>'+'</code> and <code>'*'</code>) must be declared.  Nonterminal symbols must be
  3761. declared if you need to specify which data type to use for the semantic
  3762. value (see <a href="#Multiple-Types">More Than One Value Type</a>).
  3763.  
  3764.    <p>The first rule in the file also specifies the start symbol, by default. 
  3765. If you want some other symbol to be the start symbol, you must declare
  3766. it explicitly (see <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>).
  3767.  
  3768. <ul class="menu">
  3769. <li><a accesskey="1" href="#Token-Decl">Token Decl</a>:         Declaring terminal symbols. 
  3770. <li><a accesskey="2" href="#Precedence-Decl">Precedence Decl</a>:    Declaring terminals with precedence and associativity. 
  3771. <li><a accesskey="3" href="#Union-Decl">Union Decl</a>:         Declaring the set of all semantic value types. 
  3772. <li><a accesskey="4" href="#Type-Decl">Type Decl</a>:          Declaring the choice of type for a nonterminal symbol. 
  3773. <li><a accesskey="5" href="#Destructor-Decl">Destructor Decl</a>:    Declaring how symbols are freed. 
  3774. <li><a accesskey="6" href="#Expect-Decl">Expect Decl</a>:        Suppressing warnings about shift/reduce conflicts. 
  3775. <li><a accesskey="7" href="#Start-Decl">Start Decl</a>:         Specifying the start symbol. 
  3776. <li><a accesskey="8" href="#Pure-Decl">Pure Decl</a>:          Requesting a reentrant parser. 
  3777. <li><a accesskey="9" href="#Decl-Summary">Decl Summary</a>:       Table of all Bison declarations. 
  3778. </ul>
  3779.  
  3780. <div class="node">
  3781. <p><hr>
  3782. <a name="Token-Decl"></a>
  3783. Next: <a rel="next" accesskey="n" href="#Precedence-Decl">Precedence Decl</a>,
  3784. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  3785.  
  3786. </div>
  3787.  
  3788. <h4 class="subsection">3.7.1 Token Type Names</h4>
  3789.  
  3790. <p><a name="index-declaring-token-type-names-123"></a><a name="index-token-type-names_002c-declaring-124"></a><a name="index-declaring-literal-string-tokens-125"></a><a name="index-g_t_0025token-126"></a>
  3791. The basic way to declare a token type name (terminal symbol) is as follows:
  3792.  
  3793. <pre class="example">     %token <var>name</var>
  3794. </pre>
  3795.    <p>Bison will convert this into a <code>#define</code> directive in
  3796. the parser, so that the function <code>yylex</code> (if it is in this file)
  3797. can use the name <var>name</var> to stand for this token type's code.
  3798.  
  3799.    <p>Alternatively, you can use <code>%left</code>, <code>%right</code>, or
  3800. <code>%nonassoc</code> instead of <code>%token</code>, if you wish to specify
  3801. associativity and precedence.  See <a href="#Precedence-Decl">Operator Precedence</a>.
  3802.  
  3803.    <p>You can explicitly specify the numeric code for a token type by appending
  3804. an integer value in the field immediately following the token name:
  3805.  
  3806. <pre class="example">     %token NUM 300
  3807. </pre>
  3808.    <p class="noindent">It is generally best, however, to let Bison choose the numeric codes for
  3809. all token types.  Bison will automatically select codes that don't conflict
  3810. with each other or with normal characters.
  3811.  
  3812.    <p>In the event that the stack type is a union, you must augment the
  3813. <code>%token</code> or other token declaration to include the data type
  3814. alternative delimited by angle-brackets (see <a href="#Multiple-Types">More Than One Value Type</a>).
  3815.  
  3816.    <p>For example:
  3817.  
  3818. <pre class="example">     %union {              /* define stack type */
  3819.        double val;
  3820.        symrec *tptr;
  3821.      }
  3822.      %token <val> NUM      /* define token NUM and its type */
  3823. </pre>
  3824.    <p>You can associate a literal string token with a token type name by
  3825. writing the literal string at the end of a <code>%token</code>
  3826. declaration which declares the name.  For example:
  3827.  
  3828. <pre class="example">     %token arrow "=>"
  3829. </pre>
  3830.    <p class="noindent">For example, a grammar for the C language might specify these names with
  3831. equivalent literal string tokens:
  3832.  
  3833. <pre class="example">     %token  <operator>  OR      "||"
  3834.      %token  <operator>  LE 134  "<="
  3835.      %left  OR  "<="
  3836. </pre>
  3837.    <p class="noindent">Once you equate the literal string and the token name, you can use them
  3838. interchangeably in further declarations or the grammar rules.  The
  3839. <code>yylex</code> function can use the token name or the literal string to
  3840. obtain the token type code number (see <a href="#Calling-Convention">Calling Convention</a>).
  3841.  
  3842. <div class="node">
  3843. <p><hr>
  3844. <a name="Precedence-Decl"></a>
  3845. Next: <a rel="next" accesskey="n" href="#Union-Decl">Union Decl</a>,
  3846. Previous: <a rel="previous" accesskey="p" href="#Token-Decl">Token Decl</a>,
  3847. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  3848.  
  3849. </div>
  3850.  
  3851. <h4 class="subsection">3.7.2 Operator Precedence</h4>
  3852.  
  3853. <p><a name="index-precedence-declarations-127"></a><a name="index-declaring-operator-precedence-128"></a><a name="index-operator-precedence_002c-declaring-129"></a>
  3854. Use the <code>%left</code>, <code>%right</code> or <code>%nonassoc</code> declaration to
  3855. declare a token and specify its precedence and associativity, all at
  3856. once.  These are called <dfn>precedence declarations</dfn>. 
  3857. See <a href="#Precedence">Operator Precedence</a>, for general information on
  3858. operator precedence.
  3859.  
  3860.    <p>The syntax of a precedence declaration is the same as that of
  3861. <code>%token</code>: either
  3862.  
  3863. <pre class="example">     %left <var>symbols</var>...
  3864. </pre>
  3865.    <p class="noindent">or
  3866.  
  3867. <pre class="example">     %left <<var>type</var>> <var>symbols</var>...
  3868. </pre>
  3869.    <p>And indeed any of these declarations serves the purposes of <code>%token</code>. 
  3870. But in addition, they specify the associativity and relative precedence for
  3871. all the <var>symbols</var>:
  3872.  
  3873.      <ul>
  3874. <li>The associativity of an operator <var>op</var> determines how repeated uses
  3875. of the operator nest: whether `<samp><var>x</var> <var>op</var> <var>y</var> <var>op</var>
  3876. <var>z</var></samp>' is parsed by grouping <var>x</var> with <var>y</var> first or by
  3877. grouping <var>y</var> with <var>z</var> first.  <code>%left</code> specifies
  3878. left-associativity (grouping <var>x</var> with <var>y</var> first) and
  3879. <code>%right</code> specifies right-associativity (grouping <var>y</var> with
  3880. <var>z</var> first).  <code>%nonassoc</code> specifies no associativity, which
  3881. means that `<samp><var>x</var> <var>op</var> <var>y</var> <var>op</var> <var>z</var></samp>' is
  3882. considered a syntax error.
  3883.  
  3884.      <li>The precedence of an operator determines how it nests with other operators. 
  3885. All the tokens declared in a single precedence declaration have equal
  3886. precedence and nest together according to their associativity. 
  3887. When two tokens declared in different precedence declarations associate,
  3888. the one declared later has the higher precedence and is grouped first. 
  3889. </ul>
  3890.  
  3891. <div class="node">
  3892. <p><hr>
  3893. <a name="Union-Decl"></a>
  3894. Next: <a rel="next" accesskey="n" href="#Type-Decl">Type Decl</a>,
  3895. Previous: <a rel="previous" accesskey="p" href="#Precedence-Decl">Precedence Decl</a>,
  3896. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  3897.  
  3898. </div>
  3899.  
  3900. <h4 class="subsection">3.7.3 The Collection of Value Types</h4>
  3901.  
  3902. <p><a name="index-declaring-value-types-130"></a><a name="index-value-types_002c-declaring-131"></a><a name="index-g_t_0025union-132"></a>
  3903. The <code>%union</code> declaration specifies the entire collection of possible
  3904. data types for semantic values.  The keyword <code>%union</code> is followed by a
  3905. pair of braces containing the same thing that goes inside a <code>union</code> in
  3906. C.
  3907.  
  3908.    <p>For example:
  3909.  
  3910. <pre class="example">     %union {
  3911.        double val;
  3912.        symrec *tptr;
  3913.      }
  3914. </pre>
  3915.    <p class="noindent">This says that the two alternative types are <code>double</code> and <code>symrec
  3916. *</code>.  They are given names <code>val</code> and <code>tptr</code>; these names are used
  3917. in the <code>%token</code> and <code>%type</code> declarations to pick one of the types
  3918. for a terminal or nonterminal symbol (see <a href="#Type-Decl">Nonterminal Symbols</a>).
  3919.  
  3920.    <p>As an extension to <acronym>POSIX</acronym>, a tag is allowed after the
  3921. <code>union</code>.  For example:
  3922.  
  3923. <pre class="example">     %union value {
  3924.        double val;
  3925.        symrec *tptr;
  3926.      }
  3927. </pre>
  3928.    <p>specifies the union tag <code>value</code>, so the corresponding C type is
  3929. <code>union value</code>.  If you do not specify a tag, it defaults to
  3930. <code>YYSTYPE</code>.
  3931.  
  3932.    <p>Note that, unlike making a <code>union</code> declaration in C, you need not write
  3933. a semicolon after the closing brace.
  3934.  
  3935. <div class="node">
  3936. <p><hr>
  3937. <a name="Type-Decl"></a>
  3938. Next: <a rel="next" accesskey="n" href="#Destructor-Decl">Destructor Decl</a>,
  3939. Previous: <a rel="previous" accesskey="p" href="#Union-Decl">Union Decl</a>,
  3940. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  3941.  
  3942. </div>
  3943.  
  3944. <h4 class="subsection">3.7.4 Nonterminal Symbols</h4>
  3945.  
  3946. <p><a name="index-declaring-value-types_002c-nonterminals-133"></a><a name="index-value-types_002c-nonterminals_002c-declaring-134"></a><a name="index-g_t_0025type-135"></a>
  3947. When you use <code>%union</code> to specify multiple value types, you must
  3948. declare the value type of each nonterminal symbol for which values are
  3949. used.  This is done with a <code>%type</code> declaration, like this:
  3950.  
  3951. <pre class="example">     %type <<var>type</var>> <var>nonterminal</var>...
  3952. </pre>
  3953.    <p class="noindent">Here <var>nonterminal</var> is the name of a nonterminal symbol, and
  3954. <var>type</var> is the name given in the <code>%union</code> to the alternative
  3955. that you want (see <a href="#Union-Decl">The Collection of Value Types</a>).  You
  3956. can give any number of nonterminal symbols in the same <code>%type</code>
  3957. declaration, if they have the same value type.  Use spaces to separate
  3958. the symbol names.
  3959.  
  3960.    <p>You can also declare the value type of a terminal symbol.  To do this,
  3961. use the same <code><</code><var>type</var><code>></code> construction in a declaration for the
  3962. terminal symbol.  All kinds of token declarations allow
  3963. <code><</code><var>type</var><code>></code>.
  3964.  
  3965. <div class="node">
  3966. <p><hr>
  3967. <a name="Destructor-Decl"></a>
  3968. Next: <a rel="next" accesskey="n" href="#Expect-Decl">Expect Decl</a>,
  3969. Previous: <a rel="previous" accesskey="p" href="#Type-Decl">Type Decl</a>,
  3970. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  3971.  
  3972. </div>
  3973.  
  3974. <h4 class="subsection">3.7.5 Freeing Discarded Symbols</h4>
  3975.  
  3976. <p><a name="index-freeing-discarded-symbols-136"></a><a name="index-g_t_0025destructor-137"></a>
  3977. Some symbols can be discarded by the parser, typically during error
  3978. recovery (see <a href="#Error-Recovery">Error Recovery</a>).  Basically, during error recovery,
  3979. embarrassing symbols already pushed on the stack, and embarrassing
  3980. tokens coming from the rest of the file are thrown away until the parser
  3981. falls on its feet.  If these symbols convey heap based information, this
  3982. memory is lost.  While this behavior is tolerable for batch parsers,
  3983. such as in compilers, it is unacceptable for parsers that can
  3984. possibility “never end” such as shells, or implementations of
  3985. communication protocols.
  3986.  
  3987.    <p>The <code>%destructor</code> directive allows for the definition of code that
  3988. is called when a symbol is thrown away.
  3989.  
  3990. <div class="defun">
  3991. — Directive: <b>%destructor</b><var> { code } symbols<a name="index-g_t_0025destructor-138"></a></var><br>
  3992. <blockquote><p><a name="index-g_t_0025destructor-139"></a>Declare that the <var>code</var> must be invoked for each of the
  3993. <var>symbols</var> that will be discarded by the parser.  The <var>code</var>
  3994. should use <code>$$</code> to designate the semantic value associated to the
  3995. <var>symbols</var>.  The additional parser parameters are also avaible
  3996. (see <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>).
  3997.  
  3998.         <p><strong>Warning:</strong> as of Bison 1.875, this feature is still considered as
  3999. experimental, as there was not enough user feedback.  In particular,
  4000. the syntax might still change. 
  4001. </p></blockquote></div>
  4002.  
  4003.    <p>For instance:
  4004.  
  4005. <pre class="smallexample">     %union
  4006.      {
  4007.        char *string;
  4008.      }
  4009.      %token <string> STRING
  4010.      %type  <string> string
  4011.      %destructor { free ($$); } STRING string
  4012. </pre>
  4013.    <p class="noindent">guarantees that when a <code>STRING</code> or a <code>string</code> will be discarded,
  4014. its associated memory will be freed.
  4015.  
  4016.    <p>Note that in the future, Bison might also consider that right hand side
  4017. members that are not mentioned in the action can be destroyed.  For
  4018. instance, in:
  4019.  
  4020. <pre class="smallexample">     comment: "/*" STRING "*/";
  4021. </pre>
  4022.    <p class="noindent">the parser is entitled to destroy the semantic value of the
  4023. <code>string</code>.  Of course, this will not apply to the default action;
  4024. compare:
  4025.  
  4026. <pre class="smallexample">     typeless: string;  // $$ = $1 does not apply; $1 is destroyed.
  4027.      typefull: string;  // $$ = $1 applies, $1 is not destroyed.
  4028. </pre>
  4029.    <div class="node">
  4030. <p><hr>
  4031. <a name="Expect-Decl"></a>
  4032. Next: <a rel="next" accesskey="n" href="#Start-Decl">Start Decl</a>,
  4033. Previous: <a rel="previous" accesskey="p" href="#Destructor-Decl">Destructor Decl</a>,
  4034. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  4035.  
  4036. </div>
  4037.  
  4038. <h4 class="subsection">3.7.6 Suppressing Conflict Warnings</h4>
  4039.  
  4040. <p><a name="index-suppressing-conflict-warnings-140"></a><a name="index-preventing-warnings-about-conflicts-141"></a><a name="index-warnings_002c-preventing-142"></a><a name="index-conflicts_002c-suppressing-warnings-of-143"></a><a name="index-g_t_0025expect-144"></a>
  4041. Bison normally warns if there are any conflicts in the grammar
  4042. (see <a href="#Shift_002fReduce">Shift/Reduce Conflicts</a>), but most real grammars
  4043. have harmless shift/reduce conflicts which are resolved in a predictable
  4044. way and would be difficult to eliminate.  It is desirable to suppress
  4045. the warning about these conflicts unless the number of conflicts
  4046. changes.  You can do this with the <code>%expect</code> declaration.
  4047.  
  4048.    <p>The declaration looks like this:
  4049.  
  4050. <pre class="example">     %expect <var>n</var>
  4051. </pre>
  4052.    <p>Here <var>n</var> is a decimal integer.  The declaration says there should be
  4053. no warning if there are <var>n</var> shift/reduce conflicts and no
  4054. reduce/reduce conflicts.  An error, instead of the usual warning, is
  4055. given if there are either more or fewer conflicts, or if there are any
  4056. reduce/reduce conflicts.
  4057.  
  4058.    <p>In general, using <code>%expect</code> involves these steps:
  4059.  
  4060.      <ul>
  4061. <li>Compile your grammar without <code>%expect</code>.  Use the `<samp><span class="samp">-v</span></samp>' option
  4062. to get a verbose list of where the conflicts occur.  Bison will also
  4063. print the number of conflicts.
  4064.  
  4065.      <li>Check each of the conflicts to make sure that Bison's default
  4066. resolution is what you really want.  If not, rewrite the grammar and
  4067. go back to the beginning.
  4068.  
  4069.      <li>Add an <code>%expect</code> declaration, copying the number <var>n</var> from the
  4070. number which Bison printed. 
  4071. </ul>
  4072.  
  4073.    <p>Now Bison will stop annoying you about the conflicts you have checked, but
  4074. it will warn you again if changes in the grammar result in additional
  4075. conflicts.
  4076.  
  4077. <div class="node">
  4078. <p><hr>
  4079. <a name="Start-Decl"></a>
  4080. Next: <a rel="next" accesskey="n" href="#Pure-Decl">Pure Decl</a>,
  4081. Previous: <a rel="previous" accesskey="p" href="#Expect-Decl">Expect Decl</a>,
  4082. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  4083.  
  4084. </div>
  4085.  
  4086. <h4 class="subsection">3.7.7 The Start-Symbol</h4>
  4087.  
  4088. <p><a name="index-declaring-the-start-symbol-145"></a><a name="index-start-symbol_002c-declaring-146"></a><a name="index-default-start-symbol-147"></a><a name="index-g_t_0025start-148"></a>
  4089. Bison assumes by default that the start symbol for the grammar is the first
  4090. nonterminal specified in the grammar specification section.  The programmer
  4091. may override this restriction with the <code>%start</code> declaration as follows:
  4092.  
  4093. <pre class="example">     %start <var>symbol</var>
  4094. </pre>
  4095.    <div class="node">
  4096. <p><hr>
  4097. <a name="Pure-Decl"></a>
  4098. Next: <a rel="next" accesskey="n" href="#Decl-Summary">Decl Summary</a>,
  4099. Previous: <a rel="previous" accesskey="p" href="#Start-Decl">Start Decl</a>,
  4100. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  4101.  
  4102. </div>
  4103.  
  4104. <h4 class="subsection">3.7.8 A Pure (Reentrant) Parser</h4>
  4105.  
  4106. <p><a name="index-reentrant-parser-149"></a><a name="index-pure-parser-150"></a><a name="index-g_t_0025pure_002dparser-151"></a>
  4107. A <dfn>reentrant</dfn> program is one which does not alter in the course of
  4108. execution; in other words, it consists entirely of <dfn>pure</dfn> (read-only)
  4109. code.  Reentrancy is important whenever asynchronous execution is possible;
  4110. for example, a non-reentrant program may not be safe to call from a signal
  4111. handler.  In systems with multiple threads of control, a non-reentrant
  4112. program must be called only within interlocks.
  4113.  
  4114.    <p>Normally, Bison generates a parser which is not reentrant.  This is
  4115. suitable for most uses, and it permits compatibility with Yacc.  (The
  4116. standard Yacc interfaces are inherently nonreentrant, because they use
  4117. statically allocated variables for communication with <code>yylex</code>,
  4118. including <code>yylval</code> and <code>yylloc</code>.)
  4119.  
  4120.    <p>Alternatively, you can generate a pure, reentrant parser.  The Bison
  4121. declaration <code>%pure-parser</code> says that you want the parser to be
  4122. reentrant.  It looks like this:
  4123.  
  4124. <pre class="example">     %pure-parser
  4125. </pre>
  4126.    <p>The result is that the communication variables <code>yylval</code> and
  4127. <code>yylloc</code> become local variables in <code>yyparse</code>, and a different
  4128. calling convention is used for the lexical analyzer function
  4129. <code>yylex</code>.  See <a href="#Pure-Calling">Calling Conventions for Pure Parsers</a>, for the details of this.  The variable <code>yynerrs</code> also
  4130. becomes local in <code>yyparse</code> (see <a href="#Error-Reporting">The Error Reporting Function <code>yyerror</code></a>).  The convention for calling
  4131. <code>yyparse</code> itself is unchanged.
  4132.  
  4133.    <p>Whether the parser is pure has nothing to do with the grammar rules. 
  4134. You can generate either a pure parser or a nonreentrant parser from any
  4135. valid grammar.
  4136.  
  4137. <div class="node">
  4138. <p><hr>
  4139. <a name="Decl-Summary"></a>
  4140. Previous: <a rel="previous" accesskey="p" href="#Pure-Decl">Pure Decl</a>,
  4141. Up: <a rel="up" accesskey="u" href="#Declarations">Declarations</a>
  4142.  
  4143. </div>
  4144.  
  4145. <h4 class="subsection">3.7.9 Bison Declaration Summary</h4>
  4146.  
  4147. <p><a name="index-Bison-declaration-summary-152"></a><a name="index-declaration-summary-153"></a><a name="index-summary_002c-Bison-declaration-154"></a>
  4148. Here is a summary of the declarations used to define a grammar:
  4149.  
  4150. <div class="defun">
  4151. — Directive: <b>%union</b><var><a name="index-g_t_0025union-155"></a></var><br>
  4152. <blockquote><p>Declare the collection of data types that semantic values may have
  4153. (see <a href="#Union-Decl">The Collection of Value Types</a>). 
  4154. </p></blockquote></div>
  4155.  
  4156. <div class="defun">
  4157. — Directive: <b>%token</b><var><a name="index-g_t_0025token-156"></a></var><br>
  4158. <blockquote><p>Declare a terminal symbol (token type name) with no precedence
  4159. or associativity specified (see <a href="#Token-Decl">Token Type Names</a>). 
  4160. </p></blockquote></div>
  4161.  
  4162. <div class="defun">
  4163. — Directive: <b>%right</b><var><a name="index-g_t_0025right-157"></a></var><br>
  4164. <blockquote><p>Declare a terminal symbol (token type name) that is right-associative
  4165. (see <a href="#Precedence-Decl">Operator Precedence</a>). 
  4166. </p></blockquote></div>
  4167.  
  4168. <div class="defun">
  4169. — Directive: <b>%left</b><var><a name="index-g_t_0025left-158"></a></var><br>
  4170. <blockquote><p>Declare a terminal symbol (token type name) that is left-associative
  4171. (see <a href="#Precedence-Decl">Operator Precedence</a>). 
  4172. </p></blockquote></div>
  4173.  
  4174. <div class="defun">
  4175. — Directive: <b>%nonassoc</b><var><a name="index-g_t_0025nonassoc-159"></a></var><br>
  4176. <blockquote><p>Declare a terminal symbol (token type name) that is nonassociative
  4177. (using it in a way that would be associative is a syntax error)
  4178. </p></blockquote></div>
  4179.    (see <a href="#Precedence-Decl">Operator Precedence</a>).
  4180.  
  4181. <div class="defun">
  4182. — Directive: <b>%type</b><var><a name="index-g_t_0025type-160"></a></var><br>
  4183. <blockquote><p>Declare the type of semantic values for a nonterminal symbol
  4184. (see <a href="#Type-Decl">Nonterminal Symbols</a>). 
  4185. </p></blockquote></div>
  4186.  
  4187. <div class="defun">
  4188. — Directive: <b>%start</b><var><a name="index-g_t_0025start-161"></a></var><br>
  4189. <blockquote><p>Specify the grammar's start symbol (see <a href="#Start-Decl">The Start-Symbol</a>). 
  4190. </p></blockquote></div>
  4191.  
  4192. <div class="defun">
  4193. — Directive: <b>%expect</b><var><a name="index-g_t_0025expect-162"></a></var><br>
  4194. <blockquote><p>Declare the expected number of shift-reduce conflicts
  4195. (see <a href="#Expect-Decl">Suppressing Conflict Warnings</a>). 
  4196. </p></blockquote></div>
  4197.  
  4198.    <pre class="sp">
  4199.  
  4200. </pre>
  4201. In order to change the behavior of <samp><span class="command">bison</span></samp>, use the following
  4202. directives:
  4203.  
  4204. <div class="defun">
  4205. — Directive: <b>%debug</b><var><a name="index-g_t_0025debug-163"></a></var><br>
  4206. <blockquote><p>In the parser file, define the macro <code>YYDEBUG</code> to 1 if it is not
  4207. already defined, so that the debugging facilities are compiled. 
  4208. </p></blockquote></div>
  4209.    See <a href="#Tracing">Tracing Your Parser</a>.
  4210.  
  4211. <div class="defun">
  4212. — Directive: <b>%defines</b><var><a name="index-g_t_0025defines-164"></a></var><br>
  4213. <blockquote><p>Write an extra output file containing macro definitions for the token
  4214. type names defined in the grammar and the semantic value type
  4215. <code>YYSTYPE</code>, as well as a few <code>extern</code> variable declarations.
  4216.  
  4217.         <p>If the parser output file is named <samp><var>name</var><span class="file">.c</span></samp> then this file
  4218. is named <samp><var>name</var><span class="file">.h</span></samp>.
  4219.  
  4220.         <p>This output file is essential if you wish to put the definition of
  4221. <code>yylex</code> in a separate source file, because <code>yylex</code> needs to
  4222. be able to refer to token type codes and the variable
  4223. <code>yylval</code>.  See <a href="#Token-Values">Semantic Values of Tokens</a>. 
  4224. </p></blockquote></div>
  4225.  
  4226. <div class="defun">
  4227. — Directive: <b>%destructor</b><var><a name="index-g_t_0025destructor-165"></a></var><br>
  4228. <blockquote><p>Specifying how the parser should reclaim the memory associated to
  4229. discarded symbols. See <a href="#Destructor-Decl">Freeing Discarded Symbols</a>. 
  4230. </p></blockquote></div>
  4231.  
  4232. <div class="defun">
  4233. — Directive: <b>%file-prefix="</b><var>prefix"<a name="index-g_t_0025file_002dprefix_003d_0022-166"></a></var><br>
  4234. <blockquote><p>Specify a prefix to use for all Bison output file names.  The names are
  4235. chosen as if the input file were named <samp><var>prefix</var><span class="file">.y</span></samp>. 
  4236. </p></blockquote></div>
  4237.  
  4238. <div class="defun">
  4239. — Directive: <b>%locations</b><var><a name="index-g_t_0025locations-167"></a></var><br>
  4240. <blockquote><p>Generate the code processing the locations (see <a href="#Action-Features">Special Features for Use in Actions</a>).  This mode is enabled as soon as
  4241. the grammar uses the special `<samp><span class="samp">@</span><var>n</var></samp>' tokens, but if your
  4242. grammar does not use it, using `<samp><span class="samp">%locations</span></samp>' allows for more
  4243. accurate syntax error messages. 
  4244. </p></blockquote></div>
  4245.  
  4246. <div class="defun">
  4247. — Directive: <b>%name-prefix="</b><var>prefix"<a name="index-g_t_0025name_002dprefix_003d_0022-168"></a></var><br>
  4248. <blockquote><p>Rename the external symbols used in the parser so that they start with
  4249. <var>prefix</var> instead of `<samp><span class="samp">yy</span></samp>'.  The precise list of symbols renamed
  4250. is <code>yyparse</code>, <code>yylex</code>, <code>yyerror</code>, <code>yynerrs</code>,
  4251. <code>yylval</code>, <code>yylloc</code>, <code>yychar</code>, <code>yydebug</code>, and
  4252. possible <code>yylloc</code>.  For example, if you use
  4253. `<samp><span class="samp">%name-prefix="c_"</span></samp>', the names become <code>c_parse</code>, <code>c_lex</code>,
  4254. and so on.  See <a href="#Multiple-Parsers">Multiple Parsers in the Same Program</a>. 
  4255. </p></blockquote></div>
  4256.  
  4257. <div class="defun">
  4258. — Directive: <b>%no-parser</b><var><a name="index-g_t_0025no_002dparser-169"></a></var><br>
  4259. <blockquote><p>Do not include any C code in the parser file; generate tables only.  The
  4260. parser file contains just <code>#define</code> directives and static variable
  4261. declarations.
  4262.  
  4263.         <p>This option also tells Bison to write the C code for the grammar actions
  4264. into a file named <samp><var>filename</var><span class="file">.act</span></samp>, in the form of a
  4265. brace-surrounded body fit for a <code>switch</code> statement. 
  4266. </p></blockquote></div>
  4267.  
  4268. <div class="defun">
  4269. — Directive: <b>%no-lines</b><var><a name="index-g_t_0025no_002dlines-170"></a></var><br>
  4270. <blockquote><p>Don't generate any <code>#line</code> preprocessor commands in the parser
  4271. file.  Ordinarily Bison writes these commands in the parser file so that
  4272. the C compiler and debuggers will associate errors and object code with
  4273. your source file (the grammar file).  This directive causes them to
  4274. associate errors with the parser file, treating it an independent source
  4275. file in its own right. 
  4276. </p></blockquote></div>
  4277.  
  4278. <div class="defun">
  4279. — Directive: <b>%output="</b><var>filename"<a name="index-g_t_0025output_003d_0022-171"></a></var><br>
  4280. <blockquote><p>Specify the <var>filename</var> for the parser file. 
  4281. </p></blockquote></div>
  4282.  
  4283. <div class="defun">
  4284. — Directive: <b>%pure-parser</b><var><a name="index-g_t_0025pure_002dparser-172"></a></var><br>
  4285. <blockquote><p>Request a pure (reentrant) parser program (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>). 
  4286. </p></blockquote></div>
  4287.  
  4288. <div class="defun">
  4289. — Directive: <b>%token-table</b><var><a name="index-g_t_0025token_002dtable-173"></a></var><br>
  4290. <blockquote><p>Generate an array of token names in the parser file.  The name of the
  4291. array is <code>yytname</code>; <code>yytname[</code><var>i</var><code>]</code> is the name of the
  4292. token whose internal Bison token code number is <var>i</var>.  The first
  4293. three elements of <code>yytname</code> correspond to the predefined tokens
  4294. <code>"$end"</code>,
  4295. <code>"error"</code>, and <code>"$undefined"</code>; after these come the symbols
  4296. defined in the grammar file.
  4297.  
  4298.         <p>For single-character literal tokens and literal string tokens, the name
  4299. in the table includes the single-quote or double-quote characters: for
  4300. example, <code>"'+'"</code> is a single-character literal and <code>"\"<=\""</code>
  4301. is a literal string token.  All the characters of the literal string
  4302. token appear verbatim in the string found in the table; even
  4303. double-quote characters are not escaped.  For example, if the token
  4304. consists of three characters `<samp><span class="samp">*"*</span></samp>', its string in <code>yytname</code>
  4305. contains `<samp><span class="samp">"*"*"</span></samp>'.  (In C, that would be written as
  4306. <code>"\"*\"*\""</code>).
  4307.  
  4308.         <p>When you specify <code>%token-table</code>, Bison also generates macro
  4309. definitions for macros <code>YYNTOKENS</code>, <code>YYNNTS</code>, and
  4310. <code>YYNRULES</code>, and <code>YYNSTATES</code>:
  4311.  
  4312.           <dl>
  4313. <dt><code>YYNTOKENS</code><dd>The highest token number, plus one. 
  4314. <br><dt><code>YYNNTS</code><dd>The number of nonterminal symbols. 
  4315. <br><dt><code>YYNRULES</code><dd>The number of grammar rules,
  4316. <br><dt><code>YYNSTATES</code><dd>The number of parser states (see <a href="#Parser-States">Parser States</a>). 
  4317. </dl>
  4318.         </p></blockquote></div>
  4319.  
  4320. <div class="defun">
  4321. — Directive: <b>%verbose</b><var><a name="index-g_t_0025verbose-174"></a></var><br>
  4322. <blockquote><p>Write an extra output file containing verbose descriptions of the
  4323. parser states and what is done for each type of look-ahead token in
  4324. that state.  See <a href="#Understanding">Understanding Your Parser</a>, for more
  4325. information. 
  4326. </p></blockquote></div>
  4327.  
  4328. <div class="defun">
  4329. — Directive: <b>%yacc</b><var><a name="index-g_t_0025yacc-175"></a></var><br>
  4330. <blockquote><p>Pretend the option <samp><span class="option">--yacc</span></samp> was given, i.e., imitate Yacc,
  4331. including its naming conventions.  See <a href="#Bison-Options">Bison Options</a>, for more. 
  4332. </p></blockquote></div>
  4333.  
  4334. <div class="node">
  4335. <p><hr>
  4336. <a name="Multiple-Parsers"></a>
  4337. Previous: <a rel="previous" accesskey="p" href="#Declarations">Declarations</a>,
  4338. Up: <a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>
  4339.  
  4340. </div>
  4341.  
  4342. <h3 class="section">3.8 Multiple Parsers in the Same Program</h3>
  4343.  
  4344. <p>Most programs that use Bison parse only one language and therefore contain
  4345. only one Bison parser.  But what if you want to parse more than one
  4346. language with the same program?  Then you need to avoid a name conflict
  4347. between different definitions of <code>yyparse</code>, <code>yylval</code>, and so on.
  4348.  
  4349.    <p>The easy way to do this is to use the option `<samp><span class="samp">-p </span><var>prefix</var></samp>'
  4350. (see <a href="#Invocation">Invoking Bison</a>).  This renames the interface
  4351. functions and variables of the Bison parser to start with <var>prefix</var>
  4352. instead of `<samp><span class="samp">yy</span></samp>'.  You can use this to give each parser distinct
  4353. names that do not conflict.
  4354.  
  4355.    <p>The precise list of symbols renamed is <code>yyparse</code>, <code>yylex</code>,
  4356. <code>yyerror</code>, <code>yynerrs</code>, <code>yylval</code>, <code>yylloc</code>,
  4357. <code>yychar</code> and <code>yydebug</code>.  For example, if you use `<samp><span class="samp">-p c</span></samp>',
  4358. the names become <code>cparse</code>, <code>clex</code>, and so on.
  4359.  
  4360.    <p><strong>All the other variables and macros associated with Bison are not
  4361. renamed.</strong> These others are not global; there is no conflict if the same
  4362. name is used in different parsers.  For example, <code>YYSTYPE</code> is not
  4363. renamed, but defining this in different ways in different parsers causes
  4364. no trouble (see <a href="#Value-Type">Data Types of Semantic Values</a>).
  4365.  
  4366.    <p>The `<samp><span class="samp">-p</span></samp>' option works by adding macro definitions to the beginning
  4367. of the parser source file, defining <code>yyparse</code> as
  4368. <var>prefix</var><code>parse</code>, and so on.  This effectively substitutes one
  4369. name for the other in the entire parser file.
  4370.  
  4371. <div class="node">
  4372. <p><hr>
  4373. <a name="Interface"></a>
  4374. Next: <a rel="next" accesskey="n" href="#Algorithm">Algorithm</a>,
  4375. Previous: <a rel="previous" accesskey="p" href="#Grammar-File">Grammar File</a>,
  4376. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  4377.  
  4378. </div>
  4379.  
  4380. <h2 class="chapter">4 Parser C-Language Interface</h2>
  4381.  
  4382. <p><a name="index-C_002dlanguage-interface-176"></a><a name="index-interface-177"></a>
  4383. The Bison parser is actually a C function named <code>yyparse</code>.  Here we
  4384. describe the interface conventions of <code>yyparse</code> and the other
  4385. functions that it needs to use.
  4386.  
  4387.    <p>Keep in mind that the parser uses many C identifiers starting with
  4388. `<samp><span class="samp">yy</span></samp>' and `<samp><span class="samp">YY</span></samp>' for internal purposes.  If you use such an
  4389. identifier (aside from those in this manual) in an action or in epilogue
  4390. in the grammar file, you are likely to run into trouble.
  4391.  
  4392. <ul class="menu">
  4393. <li><a accesskey="1" href="#Parser-Function">Parser Function</a>:    How to call <code>yyparse</code> and what it returns. 
  4394. <li><a accesskey="2" href="#Lexical">Lexical</a>:            You must supply a function <code>yylex</code>
  4395.                         which reads tokens. 
  4396. <li><a accesskey="3" href="#Error-Reporting">Error Reporting</a>:    You must supply a function <code>yyerror</code>. 
  4397. <li><a accesskey="4" href="#Action-Features">Action Features</a>:    Special features for use in actions. 
  4398. </ul>
  4399.  
  4400. <div class="node">
  4401. <p><hr>
  4402. <a name="Parser-Function"></a>
  4403. Next: <a rel="next" accesskey="n" href="#Lexical">Lexical</a>,
  4404. Up: <a rel="up" accesskey="u" href="#Interface">Interface</a>
  4405.  
  4406. </div>
  4407.  
  4408. <h3 class="section">4.1 The Parser Function <code>yyparse</code></h3>
  4409.  
  4410. <p><a name="index-yyparse-178"></a>
  4411. You call the function <code>yyparse</code> to cause parsing to occur.  This
  4412. function reads tokens, executes actions, and ultimately returns when it
  4413. encounters end-of-input or an unrecoverable syntax error.  You can also
  4414. write an action which directs <code>yyparse</code> to return immediately
  4415. without reading further.
  4416.  
  4417. <div class="defun">
  4418. — Function: int <b>yyparse</b> (<var>void</var>)<var><a name="index-yyparse-179"></a></var><br>
  4419. <blockquote><p>The value returned by <code>yyparse</code> is 0 if parsing was successful (return
  4420. is due to end-of-input).
  4421.  
  4422.         <p>The value is 1 if parsing failed (return is due to a syntax error). 
  4423. </p></blockquote></div>
  4424.  
  4425.    <p>In an action, you can cause immediate return from <code>yyparse</code> by using
  4426. these macros:
  4427.  
  4428. <div class="defun">
  4429. — Macro: <b>YYACCEPT</b><var><a name="index-YYACCEPT-180"></a></var><br>
  4430. <blockquote><p><a name="index-YYACCEPT-181"></a>Return immediately with value 0 (to report success). 
  4431. </p></blockquote></div>
  4432.  
  4433. <div class="defun">
  4434. — Macro: <b>YYABORT</b><var><a name="index-YYABORT-182"></a></var><br>
  4435. <blockquote><p><a name="index-YYABORT-183"></a>Return immediately with value 1 (to report failure). 
  4436. </p></blockquote></div>
  4437.  
  4438. <!-- For now, do not document %lex-param and %parse-param, since it's -->
  4439. <!-- not clear that the current behavior is stable enough.  For example, -->
  4440. <!-- we may need to add %error-param. -->
  4441. <div class="node">
  4442. <p><hr>
  4443. <a name="Lexical"></a>
  4444. Next: <a rel="next" accesskey="n" href="#Error-Reporting">Error Reporting</a>,
  4445. Previous: <a rel="previous" accesskey="p" href="#Parser-Function">Parser Function</a>,
  4446. Up: <a rel="up" accesskey="u" href="#Interface">Interface</a>
  4447.  
  4448. </div>
  4449.  
  4450. <h3 class="section">4.2 The Lexical Analyzer Function <code>yylex</code></h3>
  4451.  
  4452. <p><a name="index-yylex-184"></a><a name="index-lexical-analyzer-185"></a>
  4453. The <dfn>lexical analyzer</dfn> function, <code>yylex</code>, recognizes tokens from
  4454. the input stream and returns them to the parser.  Bison does not create
  4455. this function automatically; you must write it so that <code>yyparse</code> can
  4456. call it.  The function is sometimes referred to as a lexical scanner.
  4457.  
  4458.    <p>In simple programs, <code>yylex</code> is often defined at the end of the Bison
  4459. grammar file.  If <code>yylex</code> is defined in a separate source file, you
  4460. need to arrange for the token-type macro definitions to be available there. 
  4461. To do this, use the `<samp><span class="samp">-d</span></samp>' option when you run Bison, so that it will
  4462. write these macro definitions into a separate header file
  4463. <samp><var>name</var><span class="file">.tab.h</span></samp> which you can include in the other source files
  4464. that need it.  See <a href="#Invocation">Invoking Bison</a>.
  4465.  
  4466. <ul class="menu">
  4467. <li><a accesskey="1" href="#Calling-Convention">Calling Convention</a>:   How <code>yyparse</code> calls <code>yylex</code>. 
  4468. <li><a accesskey="2" href="#Token-Values">Token Values</a>:       How <code>yylex</code> must return the semantic value
  4469.                         of the token it has read. 
  4470. <li><a accesskey="3" href="#Token-Positions">Token Positions</a>:    How <code>yylex</code> must return the text position
  4471.                         (line number, etc.) of the token, if the
  4472.                         actions want that. 
  4473. <li><a accesskey="4" href="#Pure-Calling">Pure Calling</a>:       How the calling convention differs
  4474.                         in a pure parser (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>). 
  4475. </ul>
  4476.  
  4477. <div class="node">
  4478. <p><hr>
  4479. <a name="Calling-Convention"></a>
  4480. Next: <a rel="next" accesskey="n" href="#Token-Values">Token Values</a>,
  4481. Up: <a rel="up" accesskey="u" href="#Lexical">Lexical</a>
  4482.  
  4483. </div>
  4484.  
  4485. <h4 class="subsection">4.2.1 Calling Convention for <code>yylex</code></h4>
  4486.  
  4487. <p>The value that <code>yylex</code> returns must be the positive numeric code
  4488. for the type of token it has just found; a zero or negative value
  4489. signifies end-of-input.
  4490.  
  4491.    <p>When a token is referred to in the grammar rules by a name, that name
  4492. in the parser file becomes a C macro whose definition is the proper
  4493. numeric code for that token type.  So <code>yylex</code> can use the name
  4494. to indicate that type.  See <a href="#Symbols">Symbols</a>.
  4495.  
  4496.    <p>When a token is referred to in the grammar rules by a character literal,
  4497. the numeric code for that character is also the code for the token type. 
  4498. So <code>yylex</code> can simply return that character code, possibly converted
  4499. to <code>unsigned char</code> to avoid sign-extension.  The null character
  4500. must not be used this way, because its code is zero and that
  4501. signifies end-of-input.
  4502.  
  4503.    <p>Here is an example showing these things:
  4504.  
  4505. <pre class="example">     int
  4506.      yylex (void)
  4507.      {
  4508.        ...
  4509.        if (c == EOF)    /* Detect end-of-input.  */
  4510.          return 0;
  4511.        ...
  4512.        if (c == '+' || c == '-')
  4513.          return c;      /* Assume token type for `+' is '+'.  */
  4514.        ...
  4515.        return INT;      /* Return the type of the token.  */
  4516.        ...
  4517.      }
  4518. </pre>
  4519.    <p class="noindent">This interface has been designed so that the output from the <code>lex</code>
  4520. utility can be used without change as the definition of <code>yylex</code>.
  4521.  
  4522.    <p>If the grammar uses literal string tokens, there are two ways that
  4523. <code>yylex</code> can determine the token type codes for them:
  4524.  
  4525.      <ul>
  4526. <li>If the grammar defines symbolic token names as aliases for the
  4527. literal string tokens, <code>yylex</code> can use these symbolic names like
  4528. all others.  In this case, the use of the literal string tokens in
  4529. the grammar file has no effect on <code>yylex</code>.
  4530.  
  4531.      <li><code>yylex</code> can find the multicharacter token in the <code>yytname</code>
  4532. table.  The index of the token in the table is the token type's code. 
  4533. The name of a multicharacter token is recorded in <code>yytname</code> with a
  4534. double-quote, the token's characters, and another double-quote.  The
  4535. token's characters are not escaped in any way; they appear verbatim in
  4536. the contents of the string in the table.
  4537.  
  4538.      <p>Here's code for looking up a token in <code>yytname</code>, assuming that the
  4539. characters of the token are stored in <code>token_buffer</code>.
  4540.  
  4541.      <pre class="smallexample">          for (i = 0; i < YYNTOKENS; i++)
  4542.             {
  4543.               if (yytname[i] != 0
  4544.                   && yytname[i][0] == '"'
  4545.                   && ! strncmp (yytname[i] + 1, token_buffer,
  4546.                                 strlen (token_buffer))
  4547.                   && yytname[i][strlen (token_buffer) + 1] == '"'
  4548.                   && yytname[i][strlen (token_buffer) + 2] == 0)
  4549.                 break;
  4550.             }
  4551.      </pre>
  4552.      <p>The <code>yytname</code> table is generated only if you use the
  4553. <code>%token-table</code> declaration.  See <a href="#Decl-Summary">Decl Summary</a>. 
  4554. </ul>
  4555.  
  4556. <div class="node">
  4557. <p><hr>
  4558. <a name="Token-Values"></a>
  4559. Next: <a rel="next" accesskey="n" href="#Token-Positions">Token Positions</a>,
  4560. Previous: <a rel="previous" accesskey="p" href="#Calling-Convention">Calling Convention</a>,
  4561. Up: <a rel="up" accesskey="u" href="#Lexical">Lexical</a>
  4562.  
  4563. </div>
  4564.  
  4565. <h4 class="subsection">4.2.2 Semantic Values of Tokens</h4>
  4566.  
  4567. <p><a name="index-yylval-186"></a>In an ordinary (non-reentrant) parser, the semantic value of the token must
  4568. be stored into the global variable <code>yylval</code>.  When you are using
  4569. just one data type for semantic values, <code>yylval</code> has that type. 
  4570. Thus, if the type is <code>int</code> (the default), you might write this in
  4571. <code>yylex</code>:
  4572.  
  4573. <pre class="example">       ...
  4574.        yylval = value;  /* Put value onto Bison stack.  */
  4575.        return INT;      /* Return the type of the token.  */
  4576.        ...
  4577. </pre>
  4578.    <p>When you are using multiple data types, <code>yylval</code>'s type is a union
  4579. made from the <code>%union</code> declaration (see <a href="#Union-Decl">The Collection of Value Types</a>).  So when you store a token's value, you
  4580. must use the proper member of the union.  If the <code>%union</code>
  4581. declaration looks like this:
  4582.  
  4583. <pre class="example">     %union {
  4584.        int intval;
  4585.        double val;
  4586.        symrec *tptr;
  4587.      }
  4588. </pre>
  4589.    <p class="noindent">then the code in <code>yylex</code> might look like this:
  4590.  
  4591. <pre class="example">       ...
  4592.        yylval.intval = value; /* Put value onto Bison stack.  */
  4593.        return INT;            /* Return the type of the token.  */
  4594.        ...
  4595. </pre>
  4596.    <div class="node">
  4597. <p><hr>
  4598. <a name="Token-Positions"></a>
  4599. Next: <a rel="next" accesskey="n" href="#Pure-Calling">Pure Calling</a>,
  4600. Previous: <a rel="previous" accesskey="p" href="#Token-Values">Token Values</a>,
  4601. Up: <a rel="up" accesskey="u" href="#Lexical">Lexical</a>
  4602.  
  4603. </div>
  4604.  
  4605. <h4 class="subsection">4.2.3 Textual Positions of Tokens</h4>
  4606.  
  4607. <p><a name="index-yylloc-187"></a>If you are using the `<samp><span class="samp">@</span><var>n</var></samp>'-feature (see <a href="#Locations">Tracking Locations</a>) in actions to keep track of the
  4608. textual locations of tokens and groupings, then you must provide this
  4609. information in <code>yylex</code>.  The function <code>yyparse</code> expects to
  4610. find the textual location of a token just parsed in the global variable
  4611. <code>yylloc</code>.  So <code>yylex</code> must store the proper data in that
  4612. variable.
  4613.  
  4614.    <p>By default, the value of <code>yylloc</code> is a structure and you need only
  4615. initialize the members that are going to be used by the actions.  The
  4616. four members are called <code>first_line</code>, <code>first_column</code>,
  4617. <code>last_line</code> and <code>last_column</code>.  Note that the use of this
  4618. feature makes the parser noticeably slower.
  4619.  
  4620.    <p><a name="index-YYLTYPE-188"></a>The data type of <code>yylloc</code> has the name <code>YYLTYPE</code>.
  4621.  
  4622. <div class="node">
  4623. <p><hr>
  4624. <a name="Pure-Calling"></a>
  4625. Previous: <a rel="previous" accesskey="p" href="#Token-Positions">Token Positions</a>,
  4626. Up: <a rel="up" accesskey="u" href="#Lexical">Lexical</a>
  4627.  
  4628. </div>
  4629.  
  4630. <h4 class="subsection">4.2.4 Calling Conventions for Pure Parsers</h4>
  4631.  
  4632. <p>When you use the Bison declaration <code>%pure-parser</code> to request a
  4633. pure, reentrant parser, the global communication variables <code>yylval</code>
  4634. and <code>yylloc</code> cannot be used.  (See <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>.)  In such parsers the two global variables are replaced by
  4635. pointers passed as arguments to <code>yylex</code>.  You must declare them as
  4636. shown here, and pass the information back by storing it through those
  4637. pointers.
  4638.  
  4639. <pre class="example">     int
  4640.      yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
  4641.      {
  4642.        ...
  4643.        *lvalp = value;  /* Put value onto Bison stack.  */
  4644.        return INT;      /* Return the type of the token.  */
  4645.        ...
  4646.      }
  4647. </pre>
  4648.    <p>If the grammar file does not use the `<samp><span class="samp">@</span></samp>' constructs to refer to
  4649. textual positions, then the type <code>YYLTYPE</code> will not be defined.  In
  4650. this case, omit the second argument; <code>yylex</code> will be called with
  4651. only one argument.
  4652.  
  4653. <div class="node">
  4654. <p><hr>
  4655. <a name="Error-Reporting"></a>
  4656. Next: <a rel="next" accesskey="n" href="#Action-Features">Action Features</a>,
  4657. Previous: <a rel="previous" accesskey="p" href="#Lexical">Lexical</a>,
  4658. Up: <a rel="up" accesskey="u" href="#Interface">Interface</a>
  4659.  
  4660. </div>
  4661.  
  4662. <h3 class="section">4.3 The Error Reporting Function <code>yyerror</code></h3>
  4663.  
  4664. <p><a name="index-error-reporting-function-189"></a><a name="index-yyerror-190"></a><a name="index-parse-error-191"></a><a name="index-syntax-error-192"></a>
  4665. The Bison parser detects a <dfn>syntax error</dfn> or <dfn>parse error</dfn>
  4666. whenever it reads a token which cannot satisfy any syntax rule.  An
  4667. action in the grammar can also explicitly proclaim an error, using the
  4668. macro <code>YYERROR</code> (see <a href="#Action-Features">Special Features for Use in Actions</a>).
  4669.  
  4670.    <p>The Bison parser expects to report the error by calling an error
  4671. reporting function named <code>yyerror</code>, which you must supply.  It is
  4672. called by <code>yyparse</code> whenever a syntax error is found, and it
  4673. receives one argument.  For a syntax error, the string is normally
  4674. <code>"syntax error"</code><!-- /@w -->.
  4675.  
  4676.    <p><a name="index-g_t_0025error_002dverbose-193"></a>If you invoke the directive <code>%error-verbose</code> in the Bison
  4677. declarations section (see <a href="#Bison-Declarations">The Bison Declarations Section</a>), then Bison provides a more verbose and specific error message
  4678. string instead of just plain <code>"syntax error"</code><!-- /@w -->.
  4679.  
  4680.    <p>The parser can detect one other kind of error: stack overflow.  This
  4681. happens when the input contains constructions that are very deeply
  4682. nested.  It isn't likely you will encounter this, since the Bison
  4683. parser extends its stack automatically up to a very large limit.  But
  4684. if overflow happens, <code>yyparse</code> calls <code>yyerror</code> in the usual
  4685. fashion, except that the argument string is <code>"parser stack overflow"</code><!-- /@w -->.
  4686.  
  4687.    <p>The following definition suffices in simple programs:
  4688.  
  4689. <pre class="example">     void
  4690.      yyerror (char const *s)
  4691.      {
  4692.        fprintf (stderr, "%s\n", s);
  4693.      }
  4694. </pre>
  4695.    <p>After <code>yyerror</code> returns to <code>yyparse</code>, the latter will attempt
  4696. error recovery if you have written suitable error recovery grammar rules
  4697. (see <a href="#Error-Recovery">Error Recovery</a>).  If recovery is impossible, <code>yyparse</code> will
  4698. immediately return 1.
  4699.  
  4700.    <p>Obviously, in location tracking pure parsers, <code>yyerror</code> should have
  4701. an access to the current location.  This is indeed the case for the GLR
  4702. parsers, but not for the Yacc parser, for historical reasons.  I.e., if
  4703. `<samp><span class="samp">%locations %pure-parser</span></samp>' is passed then the prototypes for
  4704. <code>yyerror</code> are:
  4705.  
  4706. <pre class="example">     void yyerror (char const *msg);                 /* Yacc parsers.  */
  4707.      void yyerror (YYLTYPE *locp, char const *msg);  /* GLR parsers.   */
  4708. </pre>
  4709.    <p class="noindent">The prototypes are only indications of how the code produced by Bison
  4710. uses <code>yyerror</code>.  Bison-generated code always ignores the returned
  4711. value, so <code>yyerror</code> can return any type, including <code>void</code>. 
  4712. Also, <code>yyerror</code> can be a variadic function; that is why the
  4713. message is always passed last.
  4714.  
  4715.    <p>Traditionally <code>yyerror</code> returns an <code>int</code> that is always
  4716. ignored, but this is purely for historical reasons, and <code>void</code> is
  4717. preferable since it more accurately describes the return type for
  4718. <code>yyerror</code>.
  4719.  
  4720.    <p><a name="index-yynerrs-194"></a>The variable <code>yynerrs</code> contains the number of syntax errors
  4721. encountered so far.  Normally this variable is global; but if you
  4722. request a pure parser (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>)
  4723. then it is a local variable which only the actions can access.
  4724.  
  4725. <div class="node">
  4726. <p><hr>
  4727. <a name="Action-Features"></a>
  4728. Previous: <a rel="previous" accesskey="p" href="#Error-Reporting">Error Reporting</a>,
  4729. Up: <a rel="up" accesskey="u" href="#Interface">Interface</a>
  4730.  
  4731. </div>
  4732.  
  4733. <h3 class="section">4.4 Special Features for Use in Actions</h3>
  4734.  
  4735. <p><a name="index-summary_002c-action-features-195"></a><a name="index-action-features-summary-196"></a>
  4736. Here is a table of Bison constructs, variables and macros that
  4737. are useful in actions.
  4738.  
  4739. <div class="defun">
  4740. — Variable: <b>$$</b><var><a name="index-g_t_0024_0024-197"></a></var><br>
  4741. <blockquote><p>Acts like a variable that contains the semantic value for the
  4742. grouping made by the current rule.  See <a href="#Actions">Actions</a>. 
  4743. </p></blockquote></div>
  4744.  
  4745. <div class="defun">
  4746. — Variable: <b>$</b><var>n<a name="index-g_t_0024-198"></a></var><br>
  4747. <blockquote><p>Acts like a variable that contains the semantic value for the
  4748. <var>n</var>th component of the current rule.  See <a href="#Actions">Actions</a>. 
  4749. </p></blockquote></div>
  4750.  
  4751. <div class="defun">
  4752. — Variable: <b>$<</b><var>typealt>$<a name="index-g_t_0024_003c-199"></a></var><br>
  4753. <blockquote><p>Like <code>$$</code> but specifies alternative <var>typealt</var> in the union
  4754. specified by the <code>%union</code> declaration.  See <a href="#Action-Types">Data Types of Values in Actions</a>. 
  4755. </p></blockquote></div>
  4756.  
  4757. <div class="defun">
  4758. — Variable: <b>$<</b><var>typealt>n<a name="index-g_t_0024_003c-200"></a></var><br>
  4759. <blockquote><p>Like <code>$</code><var>n</var> but specifies alternative <var>typealt</var> in the
  4760. union specified by the <code>%union</code> declaration. 
  4761. See <a href="#Action-Types">Data Types of Values in Actions</a>. 
  4762. </p></blockquote></div>
  4763.  
  4764. <div class="defun">
  4765. — Macro: <b>YYABORT;</b><var><a name="index-YYABORT_003b-201"></a></var><br>
  4766. <blockquote><p>Return immediately from <code>yyparse</code>, indicating failure. 
  4767. See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
  4768. </p></blockquote></div>
  4769.  
  4770. <div class="defun">
  4771. — Macro: <b>YYACCEPT;</b><var><a name="index-YYACCEPT_003b-202"></a></var><br>
  4772. <blockquote><p>Return immediately from <code>yyparse</code>, indicating success. 
  4773. See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
  4774. </p></blockquote></div>
  4775.  
  4776. <div class="defun">
  4777. — Macro: <b>YYBACKUP</b> (<var>token, value</var>)<var>;<a name="index-YYBACKUP-203"></a></var><br>
  4778. <blockquote><p><a name="index-YYBACKUP-204"></a>Unshift a token.  This macro is allowed only for rules that reduce
  4779. a single value, and only when there is no look-ahead token. 
  4780. It is also disallowed in <acronym>GLR</acronym> parsers. 
  4781. It installs a look-ahead token with token type <var>token</var> and
  4782. semantic value <var>value</var>; then it discards the value that was
  4783. going to be reduced by this rule.
  4784.  
  4785.         <p>If the macro is used when it is not valid, such as when there is
  4786. a look-ahead token already, then it reports a syntax error with
  4787. a message `<samp><span class="samp">cannot back up</span></samp>' and performs ordinary error
  4788. recovery.
  4789.  
  4790.         <p>In either case, the rest of the action is not executed. 
  4791. </p></blockquote></div>
  4792.  
  4793. <div class="defun">
  4794. — Macro: <b>YYEMPTY</b><var><a name="index-YYEMPTY-205"></a></var><br>
  4795. <blockquote><p><a name="index-YYEMPTY-206"></a>Value stored in <code>yychar</code> when there is no look-ahead token. 
  4796. </p></blockquote></div>
  4797.  
  4798. <div class="defun">
  4799. — Macro: <b>YYERROR;</b><var><a name="index-YYERROR_003b-207"></a></var><br>
  4800. <blockquote><p><a name="index-YYERROR-208"></a>Cause an immediate syntax error.  This statement initiates error
  4801. recovery just as if the parser itself had detected an error; however, it
  4802. does not call <code>yyerror</code>, and does not print any message.  If you
  4803. want to print an error message, call <code>yyerror</code> explicitly before
  4804. the `<samp><span class="samp">YYERROR;</span></samp>' statement.  See <a href="#Error-Recovery">Error Recovery</a>. 
  4805. </p></blockquote></div>
  4806.  
  4807. <div class="defun">
  4808. — Macro: <b>YYRECOVERING</b><var><a name="index-YYRECOVERING-209"></a></var><br>
  4809. <blockquote><p>This macro stands for an expression that has the value 1 when the parser
  4810. is recovering from a syntax error, and 0 the rest of the time. 
  4811. See <a href="#Error-Recovery">Error Recovery</a>. 
  4812. </p></blockquote></div>
  4813.  
  4814. <div class="defun">
  4815. — Variable: <b>yychar</b><var><a name="index-yychar-210"></a></var><br>
  4816. <blockquote><p>Variable containing the current look-ahead token.  (In a pure parser,
  4817. this is actually a local variable within <code>yyparse</code>.)  When there is
  4818. no look-ahead token, the value <code>YYEMPTY</code> is stored in the variable. 
  4819. See <a href="#Look_002dAhead">Look-Ahead Tokens</a>. 
  4820. </p></blockquote></div>
  4821.  
  4822. <div class="defun">
  4823. — Macro: <b>yyclearin;</b><var><a name="index-yyclearin_003b-211"></a></var><br>
  4824. <blockquote><p>Discard the current look-ahead token.  This is useful primarily in
  4825. error rules.  See <a href="#Error-Recovery">Error Recovery</a>. 
  4826. </p></blockquote></div>
  4827.  
  4828. <div class="defun">
  4829. — Macro: <b>yyerrok;</b><var><a name="index-yyerrok_003b-212"></a></var><br>
  4830. <blockquote><p>Resume generating error messages immediately for subsequent syntax
  4831. errors.  This is useful primarily in error rules. 
  4832. See <a href="#Error-Recovery">Error Recovery</a>. 
  4833. </p></blockquote></div>
  4834.  
  4835. <div class="defun">
  4836. — Value: <b>@$</b><var><a name="index-g_t_0040_0040_0024-213"></a></var><br>
  4837. <blockquote><p><a name="index-g_t_0040_0040_0024-214"></a>Acts like a structure variable containing information on the textual position
  4838. of the grouping made by the current rule.  See <a href="#Locations">Tracking Locations</a>.
  4839.  
  4840.      <!-- Check if those paragraphs are still useful or not. -->
  4841. <!-- @example -->
  4842. <!-- struct @{ -->
  4843. <!-- int first_line, last_line; -->
  4844. <!-- int first_column, last_column; -->
  4845. <!-- @}; -->
  4846. <!-- @end example -->
  4847. <!-- Thus, to get the starting line number of the third component, you would -->
  4848. <!-- use @samp{@@3.first_line}. -->
  4849. <!-- In order for the members of this structure to contain valid information, -->
  4850. <!-- you must make @code{yylex} supply this information about each token. -->
  4851. <!-- If you need only certain members, then @code{yylex} need only fill in -->
  4852. <!-- those members. -->
  4853. <!-- The use of this feature makes the parser noticeably slower. -->
  4854. </blockquote></div>
  4855.  
  4856. <div class="defun">
  4857. — Value: <b>@</b><var>n</var><var><a name="index-g_t_0040_0040_0040var_007bn_007d-215"></a></var><br>
  4858. <blockquote><p><a name="index-g_t_0040_0040_0040var_007bn_007d-216"></a>Acts like a structure variable containing information on the textual position
  4859. of the <var>n</var>th component of the current rule.  See <a href="#Locations">Tracking Locations</a>. 
  4860. </p></blockquote></div>
  4861.  
  4862. <div class="node">
  4863. <p><hr>
  4864. <a name="Algorithm"></a>
  4865. Next: <a rel="next" accesskey="n" href="#Error-Recovery">Error Recovery</a>,
  4866. Previous: <a rel="previous" accesskey="p" href="#Interface">Interface</a>,
  4867. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  4868.  
  4869. </div>
  4870.  
  4871. <h2 class="chapter">5 The Bison Parser Algorithm</h2>
  4872.  
  4873. <p><a name="index-Bison-parser-algorithm-217"></a><a name="index-algorithm-of-parser-218"></a><a name="index-shifting-219"></a><a name="index-reduction-220"></a><a name="index-parser-stack-221"></a><a name="index-stack_002c-parser-222"></a>
  4874. As Bison reads tokens, it pushes them onto a stack along with their
  4875. semantic values.  The stack is called the <dfn>parser stack</dfn>.  Pushing a
  4876. token is traditionally called <dfn>shifting</dfn>.
  4877.  
  4878.    <p>For example, suppose the infix calculator has read `<samp><span class="samp">1 + 5 *</span></samp>', with a
  4879. `<samp><span class="samp">3</span></samp>' to come.  The stack will have four elements, one for each token
  4880. that was shifted.
  4881.  
  4882.    <p>But the stack does not always have an element for each token read.  When
  4883. the last <var>n</var> tokens and groupings shifted match the components of a
  4884. grammar rule, they can be combined according to that rule.  This is called
  4885. <dfn>reduction</dfn>.  Those tokens and groupings are replaced on the stack by a
  4886. single grouping whose symbol is the result (left hand side) of that rule. 
  4887. Running the rule's action is part of the process of reduction, because this
  4888. is what computes the semantic value of the resulting grouping.
  4889.  
  4890.    <p>For example, if the infix calculator's parser stack contains this:
  4891.  
  4892. <pre class="example">     1 + 5 * 3
  4893. </pre>
  4894.    <p class="noindent">and the next input token is a newline character, then the last three
  4895. elements can be reduced to 15 via the rule:
  4896.  
  4897. <pre class="example">     expr: expr '*' expr;
  4898. </pre>
  4899.    <p class="noindent">Then the stack contains just these three elements:
  4900.  
  4901. <pre class="example">     1 + 15
  4902. </pre>
  4903.    <p class="noindent">At this point, another reduction can be made, resulting in the single value
  4904. 16.  Then the newline token can be shifted.
  4905.  
  4906.    <p>The parser tries, by shifts and reductions, to reduce the entire input down
  4907. to a single grouping whose symbol is the grammar's start-symbol
  4908. (see <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>).
  4909.  
  4910.    <p>This kind of parser is known in the literature as a bottom-up parser.
  4911.  
  4912. <ul class="menu">
  4913. <li><a accesskey="1" href="#Look_002dAhead">Look-Ahead</a>:         Parser looks one token ahead when deciding what to do. 
  4914. <li><a accesskey="2" href="#Shift_002fReduce">Shift/Reduce</a>:       Conflicts: when either shifting or reduction is valid. 
  4915. <li><a accesskey="3" href="#Precedence">Precedence</a>:         Operator precedence works by resolving conflicts. 
  4916. <li><a accesskey="4" href="#Contextual-Precedence">Contextual Precedence</a>:   When an operator's precedence depends on context. 
  4917. <li><a accesskey="5" href="#Parser-States">Parser States</a>:      The parser is a finite-state-machine with stack. 
  4918. <li><a accesskey="6" href="#Reduce_002fReduce">Reduce/Reduce</a>:      When two rules are applicable in the same situation. 
  4919. <li><a accesskey="7" href="#Mystery-Conflicts">Mystery Conflicts</a>:   Reduce/reduce conflicts that look unjustified. 
  4920. <li><a accesskey="8" href="#Generalized-LR-Parsing">Generalized LR Parsing</a>:   Parsing arbitrary context-free grammars. 
  4921. <li><a accesskey="9" href="#Stack-Overflow">Stack Overflow</a>:     What happens when stack gets full.  How to avoid it. 
  4922. </ul>
  4923.  
  4924. <div class="node">
  4925. <p><hr>
  4926. <a name="Look-Ahead"></a>
  4927. <a name="Look_002dAhead"></a>
  4928. Next: <a rel="next" accesskey="n" href="#Shift_002fReduce">Shift/Reduce</a>,
  4929. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  4930.  
  4931. </div>
  4932.  
  4933. <h3 class="section">5.1 Look-Ahead Tokens</h3>
  4934.  
  4935. <p><a name="index-look_002dahead-token-223"></a>
  4936. The Bison parser does <em>not</em> always reduce immediately as soon as the
  4937. last <var>n</var> tokens and groupings match a rule.  This is because such a
  4938. simple strategy is inadequate to handle most languages.  Instead, when a
  4939. reduction is possible, the parser sometimes “looks ahead” at the next
  4940. token in order to decide what to do.
  4941.  
  4942.    <p>When a token is read, it is not immediately shifted; first it becomes the
  4943. <dfn>look-ahead token</dfn>, which is not on the stack.  Now the parser can
  4944. perform one or more reductions of tokens and groupings on the stack, while
  4945. the look-ahead token remains off to the side.  When no more reductions
  4946. should take place, the look-ahead token is shifted onto the stack.  This
  4947. does not mean that all possible reductions have been done; depending on the
  4948. token type of the look-ahead token, some rules may choose to delay their
  4949. application.
  4950.  
  4951.    <p>Here is a simple case where look-ahead is needed.  These three rules define
  4952. expressions which contain binary addition operators and postfix unary
  4953. factorial operators (`<samp><span class="samp">!</span></samp>'), and allow parentheses for grouping.
  4954.  
  4955. <pre class="example">     expr:     term '+' expr
  4956.              | term
  4957.              ;
  4958.      
  4959.      term:     '(' expr ')'
  4960.              | term '!'
  4961.              | NUMBER
  4962.              ;
  4963. </pre>
  4964.    <p>Suppose that the tokens `<samp><span class="samp">1 + 2</span></samp>'<!-- /@w --> have been read and shifted; what
  4965. should be done?  If the following token is `<samp><span class="samp">)</span></samp>', then the first three
  4966. tokens must be reduced to form an <code>expr</code>.  This is the only valid
  4967. course, because shifting the `<samp><span class="samp">)</span></samp>' would produce a sequence of symbols
  4968. <code>term ')'</code><!-- /@w -->, and no rule allows this.
  4969.  
  4970.    <p>If the following token is `<samp><span class="samp">!</span></samp>', then it must be shifted immediately so
  4971. that `<samp><span class="samp">2 !</span></samp>'<!-- /@w --> can be reduced to make a <code>term</code>.  If instead the
  4972. parser were to reduce before shifting, `<samp><span class="samp">1 + 2</span></samp>'<!-- /@w --> would become an
  4973. <code>expr</code>.  It would then be impossible to shift the `<samp><span class="samp">!</span></samp>' because
  4974. doing so would produce on the stack the sequence of symbols <code>expr
  4975. '!'</code>.  No rule allows that sequence.
  4976.  
  4977.    <p><a name="index-yychar-224"></a>The current look-ahead token is stored in the variable <code>yychar</code>. 
  4978. See <a href="#Action-Features">Special Features for Use in Actions</a>.
  4979.  
  4980. <div class="node">
  4981. <p><hr>
  4982. <a name="Shift%2fReduce"></a>
  4983. <a name="Shift_002fReduce"></a>
  4984. Next: <a rel="next" accesskey="n" href="#Precedence">Precedence</a>,
  4985. Previous: <a rel="previous" accesskey="p" href="#Look_002dAhead">Look-Ahead</a>,
  4986. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  4987.  
  4988. </div>
  4989.  
  4990. <h3 class="section">5.2 Shift/Reduce Conflicts</h3>
  4991.  
  4992. <p><a name="index-conflicts-225"></a><a name="index-shift_002freduce-conflicts-226"></a><a name="index-dangling-_0040code_007belse_007d-227"></a><a name="index-g_t_0040code_007belse_007d_002c-dangling-228"></a>
  4993. Suppose we are parsing a language which has if-then and if-then-else
  4994. statements, with a pair of rules like this:
  4995.  
  4996. <pre class="example">     if_stmt:
  4997.                IF expr THEN stmt
  4998.              | IF expr THEN stmt ELSE stmt
  4999.              ;
  5000. </pre>
  5001.    <p class="noindent">Here we assume that <code>IF</code>, <code>THEN</code> and <code>ELSE</code> are
  5002. terminal symbols for specific keyword tokens.
  5003.  
  5004.    <p>When the <code>ELSE</code> token is read and becomes the look-ahead token, the
  5005. contents of the stack (assuming the input is valid) are just right for
  5006. reduction by the first rule.  But it is also legitimate to shift the
  5007. <code>ELSE</code>, because that would lead to eventual reduction by the second
  5008. rule.
  5009.  
  5010.    <p>This situation, where either a shift or a reduction would be valid, is
  5011. called a <dfn>shift/reduce conflict</dfn>.  Bison is designed to resolve
  5012. these conflicts by choosing to shift, unless otherwise directed by
  5013. operator precedence declarations.  To see the reason for this, let's
  5014. contrast it with the other alternative.
  5015.  
  5016.    <p>Since the parser prefers to shift the <code>ELSE</code>, the result is to attach
  5017. the else-clause to the innermost if-statement, making these two inputs
  5018. equivalent:
  5019.  
  5020. <pre class="example">     if x then if y then win (); else lose;
  5021.      
  5022.      if x then do; if y then win (); else lose; end;
  5023. </pre>
  5024.    <p>But if the parser chose to reduce when possible rather than shift, the
  5025. result would be to attach the else-clause to the outermost if-statement,
  5026. making these two inputs equivalent:
  5027.  
  5028. <pre class="example">     if x then if y then win (); else lose;
  5029.      
  5030.      if x then do; if y then win (); end; else lose;
  5031. </pre>
  5032.    <p>The conflict exists because the grammar as written is ambiguous: either
  5033. parsing of the simple nested if-statement is legitimate.  The established
  5034. convention is that these ambiguities are resolved by attaching the
  5035. else-clause to the innermost if-statement; this is what Bison accomplishes
  5036. by choosing to shift rather than reduce.  (It would ideally be cleaner to
  5037. write an unambiguous grammar, but that is very hard to do in this case.) 
  5038. This particular ambiguity was first encountered in the specifications of
  5039. Algol 60 and is called the “dangling <code>else</code>” ambiguity.
  5040.  
  5041.    <p>To avoid warnings from Bison about predictable, legitimate shift/reduce
  5042. conflicts, use the <code>%expect </code><var>n</var> declaration.  There will be no
  5043. warning as long as the number of shift/reduce conflicts is exactly <var>n</var>. 
  5044. See <a href="#Expect-Decl">Suppressing Conflict Warnings</a>.
  5045.  
  5046.    <p>The definition of <code>if_stmt</code> above is solely to blame for the
  5047. conflict, but the conflict does not actually appear without additional
  5048. rules.  Here is a complete Bison input file that actually manifests the
  5049. conflict:
  5050.  
  5051. <pre class="example">     %token IF THEN ELSE variable
  5052.      %%
  5053.      stmt:     expr
  5054.              | if_stmt
  5055.              ;
  5056.      
  5057.      if_stmt:
  5058.                IF expr THEN stmt
  5059.              | IF expr THEN stmt ELSE stmt
  5060.              ;
  5061.      
  5062.      expr:     variable
  5063.              ;
  5064. </pre>
  5065.    <div class="node">
  5066. <p><hr>
  5067. <a name="Precedence"></a>
  5068. Next: <a rel="next" accesskey="n" href="#Contextual-Precedence">Contextual Precedence</a>,
  5069. Previous: <a rel="previous" accesskey="p" href="#Shift_002fReduce">Shift/Reduce</a>,
  5070. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5071.  
  5072. </div>
  5073.  
  5074. <h3 class="section">5.3 Operator Precedence</h3>
  5075.  
  5076. <p><a name="index-operator-precedence-229"></a><a name="index-precedence-of-operators-230"></a>
  5077. Another situation where shift/reduce conflicts appear is in arithmetic
  5078. expressions.  Here shifting is not always the preferred resolution; the
  5079. Bison declarations for operator precedence allow you to specify when to
  5080. shift and when to reduce.
  5081.  
  5082. <ul class="menu">
  5083. <li><a accesskey="1" href="#Why-Precedence">Why Precedence</a>:     An example showing why precedence is needed. 
  5084. <li><a accesskey="2" href="#Using-Precedence">Using Precedence</a>:   How to specify precedence in Bison grammars. 
  5085. <li><a accesskey="3" href="#Precedence-Examples">Precedence Examples</a>:   How these features are used in the previous example. 
  5086. <li><a accesskey="4" href="#How-Precedence">How Precedence</a>:     How they work. 
  5087. </ul>
  5088.  
  5089. <div class="node">
  5090. <p><hr>
  5091. <a name="Why-Precedence"></a>
  5092. Next: <a rel="next" accesskey="n" href="#Using-Precedence">Using Precedence</a>,
  5093. Up: <a rel="up" accesskey="u" href="#Precedence">Precedence</a>
  5094.  
  5095. </div>
  5096.  
  5097. <h4 class="subsection">5.3.1 When Precedence is Needed</h4>
  5098.  
  5099. <p>Consider the following ambiguous grammar fragment (ambiguous because the
  5100. input `<samp><span class="samp">1 - 2 * 3</span></samp>'<!-- /@w --> can be parsed in two different ways):
  5101.  
  5102. <pre class="example">     expr:     expr '-' expr
  5103.              | expr '*' expr
  5104.              | expr '<' expr
  5105.              | '(' expr ')'
  5106.              ...
  5107.              ;
  5108. </pre>
  5109.    <p class="noindent">Suppose the parser has seen the tokens `<samp><span class="samp">1</span></samp>', `<samp><span class="samp">-</span></samp>' and `<samp><span class="samp">2</span></samp>';
  5110. should it reduce them via the rule for the subtraction operator?  It
  5111. depends on the next token.  Of course, if the next token is `<samp><span class="samp">)</span></samp>', we
  5112. must reduce; shifting is invalid because no single rule can reduce the
  5113. token sequence `<samp><span class="samp">- 2 )</span></samp>'<!-- /@w --> or anything starting with that.  But if
  5114. the next token is `<samp><span class="samp">*</span></samp>' or `<samp><span class="samp"><</span></samp>', we have a choice: either
  5115. shifting or reduction would allow the parse to complete, but with
  5116. different results.
  5117.  
  5118.    <p>To decide which one Bison should do, we must consider the results.  If
  5119. the next operator token <var>op</var> is shifted, then it must be reduced
  5120. first in order to permit another opportunity to reduce the difference. 
  5121. The result is (in effect) `<samp><span class="samp">1 - (2 </span><var>op</var><span class="samp"> 3)</span></samp>'<!-- /@w -->.  On the other
  5122. hand, if the subtraction is reduced before shifting <var>op</var>, the result
  5123. is `<samp><span class="samp">(1 - 2) </span><var>op</var><span class="samp"> 3</span></samp>'<!-- /@w -->.  Clearly, then, the choice of shift or
  5124. reduce should depend on the relative precedence of the operators
  5125. `<samp><span class="samp">-</span></samp>' and <var>op</var>: `<samp><span class="samp">*</span></samp>' should be shifted first, but not
  5126. `<samp><span class="samp"><</span></samp>'.
  5127.  
  5128.    <p><a name="index-associativity-231"></a>What about input such as `<samp><span class="samp">1 - 2 - 5</span></samp>'<!-- /@w -->; should this be
  5129. `<samp><span class="samp">(1 - 2) - 5</span></samp>'<!-- /@w --> or should it be `<samp><span class="samp">1 - (2 - 5)</span></samp>'<!-- /@w -->?  For most
  5130. operators we prefer the former, which is called <dfn>left association</dfn>. 
  5131. The latter alternative, <dfn>right association</dfn>, is desirable for
  5132. assignment operators.  The choice of left or right association is a
  5133. matter of whether the parser chooses to shift or reduce when the stack
  5134. contains `<samp><span class="samp">1 - 2</span></samp>'<!-- /@w --> and the look-ahead token is `<samp><span class="samp">-</span></samp>': shifting
  5135. makes right-associativity.
  5136.  
  5137. <div class="node">
  5138. <p><hr>
  5139. <a name="Using-Precedence"></a>
  5140. Next: <a rel="next" accesskey="n" href="#Precedence-Examples">Precedence Examples</a>,
  5141. Previous: <a rel="previous" accesskey="p" href="#Why-Precedence">Why Precedence</a>,
  5142. Up: <a rel="up" accesskey="u" href="#Precedence">Precedence</a>
  5143.  
  5144. </div>
  5145.  
  5146. <h4 class="subsection">5.3.2 Specifying Operator Precedence</h4>
  5147.  
  5148. <p><a name="index-g_t_0025left-232"></a><a name="index-g_t_0025right-233"></a><a name="index-g_t_0025nonassoc-234"></a>
  5149. Bison allows you to specify these choices with the operator precedence
  5150. declarations <code>%left</code> and <code>%right</code>.  Each such declaration
  5151. contains a list of tokens, which are operators whose precedence and
  5152. associativity is being declared.  The <code>%left</code> declaration makes all
  5153. those operators left-associative and the <code>%right</code> declaration makes
  5154. them right-associative.  A third alternative is <code>%nonassoc</code>, which
  5155. declares that it is a syntax error to find the same operator twice “in a
  5156. row”.
  5157.  
  5158.    <p>The relative precedence of different operators is controlled by the
  5159. order in which they are declared.  The first <code>%left</code> or
  5160. <code>%right</code> declaration in the file declares the operators whose
  5161. precedence is lowest, the next such declaration declares the operators
  5162. whose precedence is a little higher, and so on.
  5163.  
  5164. <div class="node">
  5165. <p><hr>
  5166. <a name="Precedence-Examples"></a>
  5167. Next: <a rel="next" accesskey="n" href="#How-Precedence">How Precedence</a>,
  5168. Previous: <a rel="previous" accesskey="p" href="#Using-Precedence">Using Precedence</a>,
  5169. Up: <a rel="up" accesskey="u" href="#Precedence">Precedence</a>
  5170.  
  5171. </div>
  5172.  
  5173. <h4 class="subsection">5.3.3 Precedence Examples</h4>
  5174.  
  5175. <p>In our example, we would want the following declarations:
  5176.  
  5177. <pre class="example">     %left '<'
  5178.      %left '-'
  5179.      %left '*'
  5180. </pre>
  5181.    <p>In a more complete example, which supports other operators as well, we
  5182. would declare them in groups of equal precedence.  For example, <code>'+'</code> is
  5183. declared with <code>'-'</code>:
  5184.  
  5185. <pre class="example">     %left '<' '>' '=' NE LE GE
  5186.      %left '+' '-'
  5187.      %left '*' '/'
  5188. </pre>
  5189.    <p class="noindent">(Here <code>NE</code> and so on stand for the operators for “not equal”
  5190. and so on.  We assume that these tokens are more than one character long
  5191. and therefore are represented by names, not character literals.)
  5192.  
  5193. <div class="node">
  5194. <p><hr>
  5195. <a name="How-Precedence"></a>
  5196. Previous: <a rel="previous" accesskey="p" href="#Precedence-Examples">Precedence Examples</a>,
  5197. Up: <a rel="up" accesskey="u" href="#Precedence">Precedence</a>
  5198.  
  5199. </div>
  5200.  
  5201. <h4 class="subsection">5.3.4 How Precedence Works</h4>
  5202.  
  5203. <p>The first effect of the precedence declarations is to assign precedence
  5204. levels to the terminal symbols declared.  The second effect is to assign
  5205. precedence levels to certain rules: each rule gets its precedence from
  5206. the last terminal symbol mentioned in the components.  (You can also
  5207. specify explicitly the precedence of a rule.  See <a href="#Contextual-Precedence">Context-Dependent Precedence</a>.)
  5208.  
  5209.    <p>Finally, the resolution of conflicts works by comparing the precedence
  5210. of the rule being considered with that of the look-ahead token.  If the
  5211. token's precedence is higher, the choice is to shift.  If the rule's
  5212. precedence is higher, the choice is to reduce.  If they have equal
  5213. precedence, the choice is made based on the associativity of that
  5214. precedence level.  The verbose output file made by `<samp><span class="samp">-v</span></samp>'
  5215. (see <a href="#Invocation">Invoking Bison</a>) says how each conflict was
  5216. resolved.
  5217.  
  5218.    <p>Not all rules and not all tokens have precedence.  If either the rule or
  5219. the look-ahead token has no precedence, then the default is to shift.
  5220.  
  5221. <div class="node">
  5222. <p><hr>
  5223. <a name="Contextual-Precedence"></a>
  5224. Next: <a rel="next" accesskey="n" href="#Parser-States">Parser States</a>,
  5225. Previous: <a rel="previous" accesskey="p" href="#Precedence">Precedence</a>,
  5226. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5227.  
  5228. </div>
  5229.  
  5230. <h3 class="section">5.4 Context-Dependent Precedence</h3>
  5231.  
  5232. <p><a name="index-context_002ddependent-precedence-235"></a><a name="index-unary-operator-precedence-236"></a><a name="index-precedence_002c-context_002ddependent-237"></a><a name="index-precedence_002c-unary-operator-238"></a><a name="index-g_t_0025prec-239"></a>
  5233. Often the precedence of an operator depends on the context.  This sounds
  5234. outlandish at first, but it is really very common.  For example, a minus
  5235. sign typically has a very high precedence as a unary operator, and a
  5236. somewhat lower precedence (lower than multiplication) as a binary operator.
  5237.  
  5238.    <p>The Bison precedence declarations, <code>%left</code>, <code>%right</code> and
  5239. <code>%nonassoc</code>, can only be used once for a given token; so a token has
  5240. only one precedence declared in this way.  For context-dependent
  5241. precedence, you need to use an additional mechanism: the <code>%prec</code>
  5242. modifier for rules.
  5243.  
  5244.    <p>The <code>%prec</code> modifier declares the precedence of a particular rule by
  5245. specifying a terminal symbol whose precedence should be used for that rule. 
  5246. It's not necessary for that symbol to appear otherwise in the rule.  The
  5247. modifier's syntax is:
  5248.  
  5249. <pre class="example">     %prec <var>terminal-symbol</var>
  5250. </pre>
  5251.    <p class="noindent">and it is written after the components of the rule.  Its effect is to
  5252. assign the rule the precedence of <var>terminal-symbol</var>, overriding
  5253. the precedence that would be deduced for it in the ordinary way.  The
  5254. altered rule precedence then affects how conflicts involving that rule
  5255. are resolved (see <a href="#Precedence">Operator Precedence</a>).
  5256.  
  5257.    <p>Here is how <code>%prec</code> solves the problem of unary minus.  First, declare
  5258. a precedence for a fictitious terminal symbol named <code>UMINUS</code>.  There
  5259. are no tokens of this type, but the symbol serves to stand for its
  5260. precedence:
  5261.  
  5262. <pre class="example">     ...
  5263.      %left '+' '-'
  5264.      %left '*'
  5265.      %left UMINUS
  5266. </pre>
  5267.    <p>Now the precedence of <code>UMINUS</code> can be used in specific rules:
  5268.  
  5269. <pre class="example">     exp:    ...
  5270.              | exp '-' exp
  5271.              ...
  5272.              | '-' exp %prec UMINUS
  5273. </pre>
  5274.    <div class="node">
  5275. <p><hr>
  5276. <a name="Parser-States"></a>
  5277. Next: <a rel="next" accesskey="n" href="#Reduce_002fReduce">Reduce/Reduce</a>,
  5278. Previous: <a rel="previous" accesskey="p" href="#Contextual-Precedence">Contextual Precedence</a>,
  5279. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5280.  
  5281. </div>
  5282.  
  5283. <h3 class="section">5.5 Parser States</h3>
  5284.  
  5285. <p><a name="index-finite_002dstate-machine-240"></a><a name="index-parser-state-241"></a><a name="index-state-_0028of-parser_0029-242"></a>
  5286. The function <code>yyparse</code> is implemented using a finite-state machine. 
  5287. The values pushed on the parser stack are not simply token type codes; they
  5288. represent the entire sequence of terminal and nonterminal symbols at or
  5289. near the top of the stack.  The current state collects all the information
  5290. about previous input which is relevant to deciding what to do next.
  5291.  
  5292.    <p>Each time a look-ahead token is read, the current parser state together
  5293. with the type of look-ahead token are looked up in a table.  This table
  5294. entry can say, “Shift the look-ahead token.”  In this case, it also
  5295. specifies the new parser state, which is pushed onto the top of the
  5296. parser stack.  Or it can say, “Reduce using rule number <var>n</var>.”
  5297. This means that a certain number of tokens or groupings are taken off
  5298. the top of the stack, and replaced by one grouping.  In other words,
  5299. that number of states are popped from the stack, and one new state is
  5300. pushed.
  5301.  
  5302.    <p>There is one other alternative: the table can say that the look-ahead token
  5303. is erroneous in the current state.  This causes error processing to begin
  5304. (see <a href="#Error-Recovery">Error Recovery</a>).
  5305.  
  5306. <div class="node">
  5307. <p><hr>
  5308. <a name="Reduce%2fReduce"></a>
  5309. <a name="Reduce_002fReduce"></a>
  5310. Next: <a rel="next" accesskey="n" href="#Mystery-Conflicts">Mystery Conflicts</a>,
  5311. Previous: <a rel="previous" accesskey="p" href="#Parser-States">Parser States</a>,
  5312. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5313.  
  5314. </div>
  5315.  
  5316. <h3 class="section">5.6 Reduce/Reduce Conflicts</h3>
  5317.  
  5318. <p><a name="index-reduce_002freduce-conflict-243"></a><a name="index-conflicts_002c-reduce_002freduce-244"></a>
  5319. A reduce/reduce conflict occurs if there are two or more rules that apply
  5320. to the same sequence of input.  This usually indicates a serious error
  5321. in the grammar.
  5322.  
  5323.    <p>For example, here is an erroneous attempt to define a sequence
  5324. of zero or more <code>word</code> groupings.
  5325.  
  5326. <pre class="example">     sequence: /* empty */
  5327.                      { printf ("empty sequence\n"); }
  5328.              | maybeword
  5329.              | sequence word
  5330.                      { printf ("added word %s\n", $2); }
  5331.              ;
  5332.      
  5333.      maybeword: /* empty */
  5334.                      { printf ("empty maybeword\n"); }
  5335.              | word
  5336.                      { printf ("single word %s\n", $1); }
  5337.              ;
  5338. </pre>
  5339.    <p class="noindent">The error is an ambiguity: there is more than one way to parse a single
  5340. <code>word</code> into a <code>sequence</code>.  It could be reduced to a
  5341. <code>maybeword</code> and then into a <code>sequence</code> via the second rule. 
  5342. Alternatively, nothing-at-all could be reduced into a <code>sequence</code>
  5343. via the first rule, and this could be combined with the <code>word</code>
  5344. using the third rule for <code>sequence</code>.
  5345.  
  5346.    <p>There is also more than one way to reduce nothing-at-all into a
  5347. <code>sequence</code>.  This can be done directly via the first rule,
  5348. or indirectly via <code>maybeword</code> and then the second rule.
  5349.  
  5350.    <p>You might think that this is a distinction without a difference, because it
  5351. does not change whether any particular input is valid or not.  But it does
  5352. affect which actions are run.  One parsing order runs the second rule's
  5353. action; the other runs the first rule's action and the third rule's action. 
  5354. In this example, the output of the program changes.
  5355.  
  5356.    <p>Bison resolves a reduce/reduce conflict by choosing to use the rule that
  5357. appears first in the grammar, but it is very risky to rely on this.  Every
  5358. reduce/reduce conflict must be studied and usually eliminated.  Here is the
  5359. proper way to define <code>sequence</code>:
  5360.  
  5361. <pre class="example">     sequence: /* empty */
  5362.                      { printf ("empty sequence\n"); }
  5363.              | sequence word
  5364.                      { printf ("added word %s\n", $2); }
  5365.              ;
  5366. </pre>
  5367.    <p>Here is another common error that yields a reduce/reduce conflict:
  5368.  
  5369. <pre class="example">     sequence: /* empty */
  5370.              | sequence words
  5371.              | sequence redirects
  5372.              ;
  5373.      
  5374.      words:    /* empty */
  5375.              | words word
  5376.              ;
  5377.      
  5378.      redirects:/* empty */
  5379.              | redirects redirect
  5380.              ;
  5381. </pre>
  5382.    <p class="noindent">The intention here is to define a sequence which can contain either
  5383. <code>word</code> or <code>redirect</code> groupings.  The individual definitions of
  5384. <code>sequence</code>, <code>words</code> and <code>redirects</code> are error-free, but the
  5385. three together make a subtle ambiguity: even an empty input can be parsed
  5386. in infinitely many ways!
  5387.  
  5388.    <p>Consider: nothing-at-all could be a <code>words</code>.  Or it could be two
  5389. <code>words</code> in a row, or three, or any number.  It could equally well be a
  5390. <code>redirects</code>, or two, or any number.  Or it could be a <code>words</code>
  5391. followed by three <code>redirects</code> and another <code>words</code>.  And so on.
  5392.  
  5393.    <p>Here are two ways to correct these rules.  First, to make it a single level
  5394. of sequence:
  5395.  
  5396. <pre class="example">     sequence: /* empty */
  5397.              | sequence word
  5398.              | sequence redirect
  5399.              ;
  5400. </pre>
  5401.    <p>Second, to prevent either a <code>words</code> or a <code>redirects</code>
  5402. from being empty:
  5403.  
  5404. <pre class="example">     sequence: /* empty */
  5405.              | sequence words
  5406.              | sequence redirects
  5407.              ;
  5408.      
  5409.      words:    word
  5410.              | words word
  5411.              ;
  5412.      
  5413.      redirects:redirect
  5414.              | redirects redirect
  5415.              ;
  5416. </pre>
  5417.    <div class="node">
  5418. <p><hr>
  5419. <a name="Mystery-Conflicts"></a>
  5420. Next: <a rel="next" accesskey="n" href="#Generalized-LR-Parsing">Generalized LR Parsing</a>,
  5421. Previous: <a rel="previous" accesskey="p" href="#Reduce_002fReduce">Reduce/Reduce</a>,
  5422. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5423.  
  5424. </div>
  5425.  
  5426. <h3 class="section">5.7 Mysterious Reduce/Reduce Conflicts</h3>
  5427.  
  5428. <p>Sometimes reduce/reduce conflicts can occur that don't look warranted. 
  5429. Here is an example:
  5430.  
  5431. <pre class="example">     %token ID
  5432.      
  5433.      %%
  5434.      def:    param_spec return_spec ','
  5435.              ;
  5436.      param_spec:
  5437.                   type
  5438.              |    name_list ':' type
  5439.              ;
  5440.      return_spec:
  5441.                   type
  5442.              |    name ':' type
  5443.              ;
  5444.      type:        ID
  5445.              ;
  5446.      name:        ID
  5447.              ;
  5448.      name_list:
  5449.                   name
  5450.              |    name ',' name_list
  5451.              ;
  5452. </pre>
  5453.    <p>It would seem that this grammar can be parsed with only a single token
  5454. of look-ahead: when a <code>param_spec</code> is being read, an <code>ID</code> is
  5455. a <code>name</code> if a comma or colon follows, or a <code>type</code> if another
  5456. <code>ID</code> follows.  In other words, this grammar is <acronym>LR</acronym>(1).
  5457.  
  5458.    <p><a name="index-g_t_0040acronym_007bLR_007d_00281_0029-245"></a><a name="index-g_t_0040acronym_007bLALR_007d_00281_0029-246"></a>However, Bison, like most parser generators, cannot actually handle all
  5459. <acronym>LR</acronym>(1) grammars.  In this grammar, two contexts, that after
  5460. an <code>ID</code>
  5461. at the beginning of a <code>param_spec</code> and likewise at the beginning of
  5462. a <code>return_spec</code>, are similar enough that Bison assumes they are the
  5463. same.  They appear similar because the same set of rules would be
  5464. active—the rule for reducing to a <code>name</code> and that for reducing to
  5465. a <code>type</code>.  Bison is unable to determine at that stage of processing
  5466. that the rules would require different look-ahead tokens in the two
  5467. contexts, so it makes a single parser state for them both.  Combining
  5468. the two contexts causes a conflict later.  In parser terminology, this
  5469. occurrence means that the grammar is not <acronym>LALR</acronym>(1).
  5470.  
  5471.    <p>In general, it is better to fix deficiencies than to document them.  But
  5472. this particular deficiency is intrinsically hard to fix; parser
  5473. generators that can handle <acronym>LR</acronym>(1) grammars are hard to write
  5474. and tend to
  5475. produce parsers that are very large.  In practice, Bison is more useful
  5476. as it is now.
  5477.  
  5478.    <p>When the problem arises, you can often fix it by identifying the two
  5479. parser states that are being confused, and adding something to make them
  5480. look distinct.  In the above example, adding one rule to
  5481. <code>return_spec</code> as follows makes the problem go away:
  5482.  
  5483. <pre class="example">     %token BOGUS
  5484.      ...
  5485.      %%
  5486.      ...
  5487.      return_spec:
  5488.                   type
  5489.              |    name ':' type
  5490.              /* This rule is never used.  */
  5491.              |    ID BOGUS
  5492.              ;
  5493. </pre>
  5494.    <p>This corrects the problem because it introduces the possibility of an
  5495. additional active rule in the context after the <code>ID</code> at the beginning of
  5496. <code>return_spec</code>.  This rule is not active in the corresponding context
  5497. in a <code>param_spec</code>, so the two contexts receive distinct parser states. 
  5498. As long as the token <code>BOGUS</code> is never generated by <code>yylex</code>,
  5499. the added rule cannot alter the way actual input is parsed.
  5500.  
  5501.    <p>In this particular example, there is another way to solve the problem:
  5502. rewrite the rule for <code>return_spec</code> to use <code>ID</code> directly
  5503. instead of via <code>name</code>.  This also causes the two confusing
  5504. contexts to have different sets of active rules, because the one for
  5505. <code>return_spec</code> activates the altered rule for <code>return_spec</code>
  5506. rather than the one for <code>name</code>.
  5507.  
  5508. <pre class="example">     param_spec:
  5509.                   type
  5510.              |    name_list ':' type
  5511.              ;
  5512.      return_spec:
  5513.                   type
  5514.              |    ID ':' type
  5515.              ;
  5516. </pre>
  5517.    <div class="node">
  5518. <p><hr>
  5519. <a name="Generalized-LR-Parsing"></a>
  5520. Next: <a rel="next" accesskey="n" href="#Stack-Overflow">Stack Overflow</a>,
  5521. Previous: <a rel="previous" accesskey="p" href="#Mystery-Conflicts">Mystery Conflicts</a>,
  5522. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5523.  
  5524. </div>
  5525.  
  5526. <h3 class="section">5.8 Generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) Parsing</h3>
  5527.  
  5528. <p><a name="index-g_t_0040acronym_007bGLR_007d-parsing-247"></a><a name="index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-248"></a><a name="index-ambiguous-grammars-249"></a><a name="index-non_002ddeterministic-parsing-250"></a>
  5529. Bison produces <em>deterministic</em> parsers that choose uniquely
  5530. when to reduce and which reduction to apply
  5531. based on a summary of the preceding input and on one extra token of lookahead. 
  5532. As a result, normal Bison handles a proper subset of the family of
  5533. context-free languages. 
  5534. Ambiguous grammars, since they have strings with more than one possible
  5535. sequence of reductions cannot have deterministic parsers in this sense. 
  5536. The same is true of languages that require more than one symbol of
  5537. lookahead, since the parser lacks the information necessary to make a
  5538. decision at the point it must be made in a shift-reduce parser. 
  5539. Finally, as previously mentioned (see <a href="#Mystery-Conflicts">Mystery Conflicts</a>),
  5540. there are languages where Bison's particular choice of how to
  5541. summarize the input seen so far loses necessary information.
  5542.  
  5543.    <p>When you use the `<samp><span class="samp">%glr-parser</span></samp>' declaration in your grammar file,
  5544. Bison generates a parser that uses a different algorithm, called
  5545. Generalized <acronym>LR</acronym> (or <acronym>GLR</acronym>).  A Bison <acronym>GLR</acronym>
  5546. parser uses the same basic
  5547. algorithm for parsing as an ordinary Bison parser, but behaves
  5548. differently in cases where there is a shift-reduce conflict that has not
  5549. been resolved by precedence rules (see <a href="#Precedence">Precedence</a>) or a
  5550. reduce-reduce conflict.  When a <acronym>GLR</acronym> parser encounters such a
  5551. situation, it
  5552. effectively <em>splits</em> into a several parsers, one for each possible
  5553. shift or reduction.  These parsers then proceed as usual, consuming
  5554. tokens in lock-step.  Some of the stacks may encounter other conflicts
  5555. and split further, with the result that instead of a sequence of states,
  5556. a Bison <acronym>GLR</acronym> parsing stack is what is in effect a tree of states.
  5557.  
  5558.    <p>In effect, each stack represents a guess as to what the proper parse
  5559. is.  Additional input may indicate that a guess was wrong, in which case
  5560. the appropriate stack silently disappears.  Otherwise, the semantics
  5561. actions generated in each stack are saved, rather than being executed
  5562. immediately.  When a stack disappears, its saved semantic actions never
  5563. get executed.  When a reduction causes two stacks to become equivalent,
  5564. their sets of semantic actions are both saved with the state that
  5565. results from the reduction.  We say that two stacks are equivalent
  5566. when they both represent the same sequence of states,
  5567. and each pair of corresponding states represents a
  5568. grammar symbol that produces the same segment of the input token
  5569. stream.
  5570.  
  5571.    <p>Whenever the parser makes a transition from having multiple
  5572. states to having one, it reverts to the normal <acronym>LALR</acronym>(1) parsing
  5573. algorithm, after resolving and executing the saved-up actions. 
  5574. At this transition, some of the states on the stack will have semantic
  5575. values that are sets (actually multisets) of possible actions.  The
  5576. parser tries to pick one of the actions by first finding one whose rule
  5577. has the highest dynamic precedence, as set by the `<samp><span class="samp">%dprec</span></samp>'
  5578. declaration.  Otherwise, if the alternative actions are not ordered by
  5579. precedence, but there the same merging function is declared for both
  5580. rules by the `<samp><span class="samp">%merge</span></samp>' declaration,
  5581. Bison resolves and evaluates both and then calls the merge function on
  5582. the result.  Otherwise, it reports an ambiguity.
  5583.  
  5584.    <p>It is possible to use a data structure for the <acronym>GLR</acronym> parsing tree that
  5585. permits the processing of any <acronym>LALR</acronym>(1) grammar in linear time (in the
  5586. size of the input), any unambiguous (not necessarily
  5587. <acronym>LALR</acronym>(1)) grammar in
  5588. quadratic worst-case time, and any general (possibly ambiguous)
  5589. context-free grammar in cubic worst-case time.  However, Bison currently
  5590. uses a simpler data structure that requires time proportional to the
  5591. length of the input times the maximum number of stacks required for any
  5592. prefix of the input.  Thus, really ambiguous or non-deterministic
  5593. grammars can require exponential time and space to process.  Such badly
  5594. behaving examples, however, are not generally of practical interest. 
  5595. Usually, non-determinism in a grammar is local—the parser is “in
  5596. doubt” only for a few tokens at a time.  Therefore, the current data
  5597. structure should generally be adequate.  On <acronym>LALR</acronym>(1) portions of a
  5598. grammar, in particular, it is only slightly slower than with the default
  5599. Bison parser.
  5600.  
  5601. <div class="node">
  5602. <p><hr>
  5603. <a name="Stack-Overflow"></a>
  5604. Previous: <a rel="previous" accesskey="p" href="#Generalized-LR-Parsing">Generalized LR Parsing</a>,
  5605. Up: <a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>
  5606.  
  5607. </div>
  5608.  
  5609. <h3 class="section">5.9 Stack Overflow, and How to Avoid It</h3>
  5610.  
  5611. <p><a name="index-stack-overflow-251"></a><a name="index-parser-stack-overflow-252"></a><a name="index-overflow-of-parser-stack-253"></a>
  5612. The Bison parser stack can overflow if too many tokens are shifted and
  5613. not reduced.  When this happens, the parser function <code>yyparse</code>
  5614. returns a nonzero value, pausing only to call <code>yyerror</code> to report
  5615. the overflow.
  5616.  
  5617.    <p>Because Bison parsers have growing stacks, hitting the upper limit
  5618. usually results from using a right recursion instead of a left
  5619. recursion, See <a href="#Recursion">Recursive Rules</a>.
  5620.  
  5621.    <p><a name="index-YYMAXDEPTH-254"></a>By defining the macro <code>YYMAXDEPTH</code>, you can control how deep the
  5622. parser stack can become before a stack overflow occurs.  Define the
  5623. macro with a value that is an integer.  This value is the maximum number
  5624. of tokens that can be shifted (and not reduced) before overflow. 
  5625. It must be a constant expression whose value is known at compile time.
  5626.  
  5627.    <p>The stack space allowed is not necessarily allocated.  If you specify a
  5628. large value for <code>YYMAXDEPTH</code>, the parser actually allocates a small
  5629. stack at first, and then makes it bigger by stages as needed.  This
  5630. increasing allocation happens automatically and silently.  Therefore,
  5631. you do not need to make <code>YYMAXDEPTH</code> painfully small merely to save
  5632. space for ordinary inputs that do not need much stack.
  5633.  
  5634.    <p><a name="index-default-stack-limit-255"></a>The default value of <code>YYMAXDEPTH</code>, if you do not define it, is
  5635. 10000.
  5636.  
  5637.    <p><a name="index-YYINITDEPTH-256"></a>You can control how much stack is allocated initially by defining the
  5638. macro <code>YYINITDEPTH</code>.  This value too must be a compile-time
  5639. constant integer.  The default is 200.
  5640.  
  5641. <!-- FIXME: C++ output. -->
  5642. <p>Because of semantical differences between C and C++, the
  5643. <acronym>LALR</acronym>(1) parsers
  5644. in C produced by Bison by compiled as C++ cannot grow.  In this precise
  5645. case (compiling a C parser as C++) you are suggested to grow
  5646. <code>YYINITDEPTH</code>.  In the near future, a C++ output output will be
  5647. provided which addresses this issue.
  5648.  
  5649. <div class="node">
  5650. <p><hr>
  5651. <a name="Error-Recovery"></a>
  5652. Next: <a rel="next" accesskey="n" href="#Context-Dependency">Context Dependency</a>,
  5653. Previous: <a rel="previous" accesskey="p" href="#Algorithm">Algorithm</a>,
  5654. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  5655.  
  5656. </div>
  5657.  
  5658. <h2 class="chapter">6 Error Recovery</h2>
  5659.  
  5660. <p><a name="index-error-recovery-257"></a><a name="index-recovery-from-errors-258"></a>
  5661. It is not usually acceptable to have a program terminate on a syntax
  5662. error.  For example, a compiler should recover sufficiently to parse the
  5663. rest of the input file and check it for errors; a calculator should accept
  5664. another expression.
  5665.  
  5666.    <p>In a simple interactive command parser where each input is one line, it may
  5667. be sufficient to allow <code>yyparse</code> to return 1 on error and have the
  5668. caller ignore the rest of the input line when that happens (and then call
  5669. <code>yyparse</code> again).  But this is inadequate for a compiler, because it
  5670. forgets all the syntactic context leading up to the error.  A syntax error
  5671. deep within a function in the compiler input should not cause the compiler
  5672. to treat the following line like the beginning of a source file.
  5673.  
  5674.    <p><a name="index-error-259"></a>You can define how to recover from a syntax error by writing rules to
  5675. recognize the special token <code>error</code>.  This is a terminal symbol that
  5676. is always defined (you need not declare it) and reserved for error
  5677. handling.  The Bison parser generates an <code>error</code> token whenever a
  5678. syntax error happens; if you have provided a rule to recognize this token
  5679. in the current context, the parse can continue.
  5680.  
  5681.    <p>For example:
  5682.  
  5683. <pre class="example">     stmnts:  /* empty string */
  5684.              | stmnts '\n'
  5685.              | stmnts exp '\n'
  5686.              | stmnts error '\n'
  5687. </pre>
  5688.    <p>The fourth rule in this example says that an error followed by a newline
  5689. makes a valid addition to any <code>stmnts</code>.
  5690.  
  5691.    <p>What happens if a syntax error occurs in the middle of an <code>exp</code>?  The
  5692. error recovery rule, interpreted strictly, applies to the precise sequence
  5693. of a <code>stmnts</code>, an <code>error</code> and a newline.  If an error occurs in
  5694. the middle of an <code>exp</code>, there will probably be some additional tokens
  5695. and subexpressions on the stack after the last <code>stmnts</code>, and there
  5696. will be tokens to read before the next newline.  So the rule is not
  5697. applicable in the ordinary way.
  5698.  
  5699.    <p>But Bison can force the situation to fit the rule, by discarding part of
  5700. the semantic context and part of the input.  First it discards states
  5701. and objects from the stack until it gets back to a state in which the
  5702. <code>error</code> token is acceptable.  (This means that the subexpressions
  5703. already parsed are discarded, back to the last complete <code>stmnts</code>.) 
  5704. At this point the <code>error</code> token can be shifted.  Then, if the old
  5705. look-ahead token is not acceptable to be shifted next, the parser reads
  5706. tokens and discards them until it finds a token which is acceptable.  In
  5707. this example, Bison reads and discards input until the next newline so
  5708. that the fourth rule can apply.  Note that discarded symbols are
  5709. possible sources of memory leaks, see <a href="#Destructor-Decl">Freeing Discarded Symbols</a>, for a means to reclaim this memory.
  5710.  
  5711.    <p>The choice of error rules in the grammar is a choice of strategies for
  5712. error recovery.  A simple and useful strategy is simply to skip the rest of
  5713. the current input line or current statement if an error is detected:
  5714.  
  5715. <pre class="example">     stmnt: error ';'  /* On error, skip until ';' is read.  */
  5716. </pre>
  5717.    <p>It is also useful to recover to the matching close-delimiter of an
  5718. opening-delimiter that has already been parsed.  Otherwise the
  5719. close-delimiter will probably appear to be unmatched, and generate another,
  5720. spurious error message:
  5721.  
  5722. <pre class="example">     primary:  '(' expr ')'
  5723.              | '(' error ')'
  5724.              ...
  5725.              ;
  5726. </pre>
  5727.    <p>Error recovery strategies are necessarily guesses.  When they guess wrong,
  5728. one syntax error often leads to another.  In the above example, the error
  5729. recovery rule guesses that an error is due to bad input within one
  5730. <code>stmnt</code>.  Suppose that instead a spurious semicolon is inserted in the
  5731. middle of a valid <code>stmnt</code>.  After the error recovery rule recovers
  5732. from the first error, another syntax error will be found straightaway,
  5733. since the text following the spurious semicolon is also an invalid
  5734. <code>stmnt</code>.
  5735.  
  5736.    <p>To prevent an outpouring of error messages, the parser will output no error
  5737. message for another syntax error that happens shortly after the first; only
  5738. after three consecutive input tokens have been successfully shifted will
  5739. error messages resume.
  5740.  
  5741.    <p>Note that rules which accept the <code>error</code> token may have actions, just
  5742. as any other rules can.
  5743.  
  5744.    <p><a name="index-yyerrok-260"></a>You can make error messages resume immediately by using the macro
  5745. <code>yyerrok</code> in an action.  If you do this in the error rule's action, no
  5746. error messages will be suppressed.  This macro requires no arguments;
  5747. `<samp><span class="samp">yyerrok;</span></samp>' is a valid C statement.
  5748.  
  5749.    <p><a name="index-yyclearin-261"></a>The previous look-ahead token is reanalyzed immediately after an error.  If
  5750. this is unacceptable, then the macro <code>yyclearin</code> may be used to clear
  5751. this token.  Write the statement `<samp><span class="samp">yyclearin;</span></samp>' in the error rule's
  5752. action.
  5753.  
  5754.    <p>For example, suppose that on a syntax error, an error handling routine is
  5755. called that advances the input stream to some point where parsing should
  5756. once again commence.  The next symbol returned by the lexical scanner is
  5757. probably correct.  The previous look-ahead token ought to be discarded
  5758. with `<samp><span class="samp">yyclearin;</span></samp>'.
  5759.  
  5760.    <p><a name="index-YYRECOVERING-262"></a>The macro <code>YYRECOVERING</code> stands for an expression that has the
  5761. value 1 when the parser is recovering from a syntax error, and 0 the
  5762. rest of the time.  A value of 1 indicates that error messages are
  5763. currently suppressed for new syntax errors.
  5764.  
  5765. <div class="node">
  5766. <p><hr>
  5767. <a name="Context-Dependency"></a>
  5768. Next: <a rel="next" accesskey="n" href="#Debugging">Debugging</a>,
  5769. Previous: <a rel="previous" accesskey="p" href="#Error-Recovery">Error Recovery</a>,
  5770. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  5771.  
  5772. </div>
  5773.  
  5774. <h2 class="chapter">7 Handling Context Dependencies</h2>
  5775.  
  5776. <p>The Bison paradigm is to parse tokens first, then group them into larger
  5777. syntactic units.  In many languages, the meaning of a token is affected by
  5778. its context.  Although this violates the Bison paradigm, certain techniques
  5779. (known as <dfn>kludges</dfn>) may enable you to write Bison parsers for such
  5780. languages.
  5781.  
  5782. <ul class="menu">
  5783. <li><a accesskey="1" href="#Semantic-Tokens">Semantic Tokens</a>:    Token parsing can depend on the semantic context. 
  5784. <li><a accesskey="2" href="#Lexical-Tie_002dins">Lexical Tie-ins</a>:    Token parsing can depend on the syntactic context. 
  5785. <li><a accesskey="3" href="#Tie_002din-Recovery">Tie-in Recovery</a>:    Lexical tie-ins have implications for how
  5786.                         error recovery rules must be written. 
  5787. </ul>
  5788.  
  5789.    <p>(Actually, “kludge” means any technique that gets its job done but is
  5790. neither clean nor robust.)
  5791.  
  5792. <div class="node">
  5793. <p><hr>
  5794. <a name="Semantic-Tokens"></a>
  5795. Next: <a rel="next" accesskey="n" href="#Lexical-Tie_002dins">Lexical Tie-ins</a>,
  5796. Up: <a rel="up" accesskey="u" href="#Context-Dependency">Context Dependency</a>
  5797.  
  5798. </div>
  5799.  
  5800. <h3 class="section">7.1 Semantic Info in Token Types</h3>
  5801.  
  5802. <p>The C language has a context dependency: the way an identifier is used
  5803. depends on what its current meaning is.  For example, consider this:
  5804.  
  5805. <pre class="example">     foo (x);
  5806. </pre>
  5807.    <p>This looks like a function call statement, but if <code>foo</code> is a typedef
  5808. name, then this is actually a declaration of <code>x</code>.  How can a Bison
  5809. parser for C decide how to parse this input?
  5810.  
  5811.    <p>The method used in <acronym>GNU</acronym> C is to have two different token types,
  5812. <code>IDENTIFIER</code> and <code>TYPENAME</code>.  When <code>yylex</code> finds an
  5813. identifier, it looks up the current declaration of the identifier in order
  5814. to decide which token type to return: <code>TYPENAME</code> if the identifier is
  5815. declared as a typedef, <code>IDENTIFIER</code> otherwise.
  5816.  
  5817.    <p>The grammar rules can then express the context dependency by the choice of
  5818. token type to recognize.  <code>IDENTIFIER</code> is accepted as an expression,
  5819. but <code>TYPENAME</code> is not.  <code>TYPENAME</code> can start a declaration, but
  5820. <code>IDENTIFIER</code> cannot.  In contexts where the meaning of the identifier
  5821. is <em>not</em> significant, such as in declarations that can shadow a
  5822. typedef name, either <code>TYPENAME</code> or <code>IDENTIFIER</code> is
  5823. accepted—there is one rule for each of the two token types.
  5824.  
  5825.    <p>This technique is simple to use if the decision of which kinds of
  5826. identifiers to allow is made at a place close to where the identifier is
  5827. parsed.  But in C this is not always so: C allows a declaration to
  5828. redeclare a typedef name provided an explicit type has been specified
  5829. earlier:
  5830.  
  5831. <pre class="example">     typedef int foo, bar, lose;
  5832.      static foo (bar);        /* <span class="roman">redeclare </span><code>bar</code><span class="roman"> as static variable</span> */
  5833.      static int foo (lose);   /* <span class="roman">redeclare </span><code>foo</code><span class="roman"> as function</span> */
  5834. </pre>
  5835.    <p>Unfortunately, the name being declared is separated from the declaration
  5836. construct itself by a complicated syntactic structure—the “declarator”.
  5837.  
  5838.    <p>As a result, part of the Bison parser for C needs to be duplicated, with
  5839. all the nonterminal names changed: once for parsing a declaration in
  5840. which a typedef name can be redefined, and once for parsing a
  5841. declaration in which that can't be done.  Here is a part of the
  5842. duplication, with actions omitted for brevity:
  5843.  
  5844. <pre class="example">     initdcl:
  5845.                declarator maybeasm '='
  5846.                init
  5847.              | declarator maybeasm
  5848.              ;
  5849.      
  5850.      notype_initdcl:
  5851.                notype_declarator maybeasm '='
  5852.                init
  5853.              | notype_declarator maybeasm
  5854.              ;
  5855. </pre>
  5856.    <p class="noindent">Here <code>initdcl</code> can redeclare a typedef name, but <code>notype_initdcl</code>
  5857. cannot.  The distinction between <code>declarator</code> and
  5858. <code>notype_declarator</code> is the same sort of thing.
  5859.  
  5860.    <p>There is some similarity between this technique and a lexical tie-in
  5861. (described next), in that information which alters the lexical analysis is
  5862. changed during parsing by other parts of the program.  The difference is
  5863. here the information is global, and is used for other purposes in the
  5864. program.  A true lexical tie-in has a special-purpose flag controlled by
  5865. the syntactic context.
  5866.  
  5867. <div class="node">
  5868. <p><hr>
  5869. <a name="Lexical-Tie-ins"></a>
  5870. <a name="Lexical-Tie_002dins"></a>
  5871. Next: <a rel="next" accesskey="n" href="#Tie_002din-Recovery">Tie-in Recovery</a>,
  5872. Previous: <a rel="previous" accesskey="p" href="#Semantic-Tokens">Semantic Tokens</a>,
  5873. Up: <a rel="up" accesskey="u" href="#Context-Dependency">Context Dependency</a>
  5874.  
  5875. </div>
  5876.  
  5877. <h3 class="section">7.2 Lexical Tie-ins</h3>
  5878.  
  5879. <p><a name="index-lexical-tie_002din-263"></a>
  5880. One way to handle context-dependency is the <dfn>lexical tie-in</dfn>: a flag
  5881. which is set by Bison actions, whose purpose is to alter the way tokens are
  5882. parsed.
  5883.  
  5884.    <p>For example, suppose we have a language vaguely like C, but with a special
  5885. construct `<samp><span class="samp">hex (</span><var>hex-expr</var><span class="samp">)</span></samp>'.  After the keyword <code>hex</code> comes
  5886. an expression in parentheses in which all integers are hexadecimal.  In
  5887. particular, the token `<samp><span class="samp">a1b</span></samp>' must be treated as an integer rather than
  5888. as an identifier if it appears in that context.  Here is how you can do it:
  5889.  
  5890. <pre class="example">     %{
  5891.        int hexflag;
  5892.        int yylex (void);
  5893.        void yyerror (char const *);
  5894.      %}
  5895.      %%
  5896.      ...
  5897.      expr:   IDENTIFIER
  5898.              | constant
  5899.              | HEX '('
  5900.                      { hexflag = 1; }
  5901.                expr ')'
  5902.                      { hexflag = 0;
  5903.                         $$ = $4; }
  5904.              | expr '+' expr
  5905.                      { $$ = make_sum ($1, $3); }
  5906.              ...
  5907.              ;
  5908.      
  5909.      constant:
  5910.                INTEGER
  5911.              | STRING
  5912.              ;
  5913. </pre>
  5914.    <p class="noindent">Here we assume that <code>yylex</code> looks at the value of <code>hexflag</code>; when
  5915. it is nonzero, all integers are parsed in hexadecimal, and tokens starting
  5916. with letters are parsed as integers if possible.
  5917.  
  5918.    <p>The declaration of <code>hexflag</code> shown in the prologue of the parser file
  5919. is needed to make it accessible to the actions (see <a href="#Prologue">The Prologue</a>). 
  5920. You must also write the code in <code>yylex</code> to obey the flag.
  5921.  
  5922. <div class="node">
  5923. <p><hr>
  5924. <a name="Tie-in-Recovery"></a>
  5925. <a name="Tie_002din-Recovery"></a>
  5926. Previous: <a rel="previous" accesskey="p" href="#Lexical-Tie_002dins">Lexical Tie-ins</a>,
  5927. Up: <a rel="up" accesskey="u" href="#Context-Dependency">Context Dependency</a>
  5928.  
  5929. </div>
  5930.  
  5931. <h3 class="section">7.3 Lexical Tie-ins and Error Recovery</h3>
  5932.  
  5933. <p>Lexical tie-ins make strict demands on any error recovery rules you have. 
  5934. See <a href="#Error-Recovery">Error Recovery</a>.
  5935.  
  5936.    <p>The reason for this is that the purpose of an error recovery rule is to
  5937. abort the parsing of one construct and resume in some larger construct. 
  5938. For example, in C-like languages, a typical error recovery rule is to skip
  5939. tokens until the next semicolon, and then start a new statement, like this:
  5940.  
  5941. <pre class="example">     stmt:   expr ';'
  5942.              | IF '(' expr ')' stmt { ... }
  5943.              ...
  5944.              error ';'
  5945.                      { hexflag = 0; }
  5946.              ;
  5947. </pre>
  5948.    <p>If there is a syntax error in the middle of a `<samp><span class="samp">hex (</span><var>expr</var><span class="samp">)</span></samp>'
  5949. construct, this error rule will apply, and then the action for the
  5950. completed `<samp><span class="samp">hex (</span><var>expr</var><span class="samp">)</span></samp>' will never run.  So <code>hexflag</code> would
  5951. remain set for the entire rest of the input, or until the next <code>hex</code>
  5952. keyword, causing identifiers to be misinterpreted as integers.
  5953.  
  5954.    <p>To avoid this problem the error recovery rule itself clears <code>hexflag</code>.
  5955.  
  5956.    <p>There may also be an error recovery rule that works within expressions. 
  5957. For example, there could be a rule which applies within parentheses
  5958. and skips to the close-parenthesis:
  5959.  
  5960. <pre class="example">     expr:   ...
  5961.              | '(' expr ')'
  5962.                      { $$ = $2; }
  5963.              | '(' error ')'
  5964.              ...
  5965. </pre>
  5966.    <p>If this rule acts within the <code>hex</code> construct, it is not going to abort
  5967. that construct (since it applies to an inner level of parentheses within
  5968. the construct).  Therefore, it should not clear the flag: the rest of
  5969. the <code>hex</code> construct should be parsed with the flag still in effect.
  5970.  
  5971.    <p>What if there is an error recovery rule which might abort out of the
  5972. <code>hex</code> construct or might not, depending on circumstances?  There is no
  5973. way you can write the action to determine whether a <code>hex</code> construct is
  5974. being aborted or not.  So if you are using a lexical tie-in, you had better
  5975. make sure your error recovery rules are not of this kind.  Each rule must
  5976. be such that you can be sure that it always will, or always won't, have to
  5977. clear the flag.
  5978.  
  5979. <!-- ================================================== Debugging Your Parser -->
  5980. <div class="node">
  5981. <p><hr>
  5982. <a name="Debugging"></a>
  5983. Next: <a rel="next" accesskey="n" href="#Invocation">Invocation</a>,
  5984. Previous: <a rel="previous" accesskey="p" href="#Context-Dependency">Context Dependency</a>,
  5985. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  5986.  
  5987. </div>
  5988.  
  5989. <h2 class="chapter">8 Debugging Your Parser</h2>
  5990.  
  5991. <p>Developing a parser can be a challenge, especially if you don't
  5992. understand the algorithm (see <a href="#Algorithm">The Bison Parser Algorithm</a>).  Even so, sometimes a detailed description of the automaton
  5993. can help (see <a href="#Understanding">Understanding Your Parser</a>), or
  5994. tracing the execution of the parser can give some insight on why it
  5995. behaves improperly (see <a href="#Tracing">Tracing Your Parser</a>).
  5996.  
  5997. <ul class="menu">
  5998. <li><a accesskey="1" href="#Understanding">Understanding</a>:      Understanding the structure of your parser. 
  5999. <li><a accesskey="2" href="#Tracing">Tracing</a>:            Tracing the execution of your parser. 
  6000. </ul>
  6001.  
  6002. <div class="node">
  6003. <p><hr>
  6004. <a name="Understanding"></a>
  6005. Next: <a rel="next" accesskey="n" href="#Tracing">Tracing</a>,
  6006. Up: <a rel="up" accesskey="u" href="#Debugging">Debugging</a>
  6007.  
  6008. </div>
  6009.  
  6010. <h3 class="section">8.1 Understanding Your Parser</h3>
  6011.  
  6012. <p>As documented elsewhere (see <a href="#Algorithm">The Bison Parser Algorithm</a>)
  6013. Bison parsers are <dfn>shift/reduce automata</dfn>.  In some cases (much more
  6014. frequent than one would hope), looking at this automaton is required to
  6015. tune or simply fix a parser.  Bison provides two different
  6016. representation of it, either textually or graphically (as a <acronym>VCG</acronym>
  6017. file).
  6018.  
  6019.    <p>The textual file is generated when the options <samp><span class="option">--report</span></samp> or
  6020. <samp><span class="option">--verbose</span></samp> are specified, see See <a href="#Invocation">Invoking Bison</a>.  Its name is made by removing `<samp><span class="samp">.tab.c</span></samp>' or `<samp><span class="samp">.c</span></samp>' from
  6021. the parser output file name, and adding `<samp><span class="samp">.output</span></samp>' instead. 
  6022. Therefore, if the input file is <samp><span class="file">foo.y</span></samp>, then the parser file is
  6023. called <samp><span class="file">foo.tab.c</span></samp> by default.  As a consequence, the verbose
  6024. output file is called <samp><span class="file">foo.output</span></samp>.
  6025.  
  6026.    <p>The following grammar file, <samp><span class="file">calc.y</span></samp>, will be used in the sequel:
  6027.  
  6028. <pre class="example">     %token NUM STR
  6029.      %left '+' '-'
  6030.      %left '*'
  6031.      %%
  6032.      exp: exp '+' exp
  6033.         | exp '-' exp
  6034.         | exp '*' exp
  6035.         | exp '/' exp
  6036.         | NUM
  6037.         ;
  6038.      useless: STR;
  6039.      %%
  6040. </pre>
  6041.    <p><samp><span class="command">bison</span></samp> reports:
  6042.  
  6043. <pre class="example">     calc.y: warning: 1 useless nonterminal and 1 useless rule
  6044.      calc.y:11.1-7: warning: useless nonterminal: useless
  6045.      calc.y:11.10-12: warning: useless rule: useless: STR
  6046.      calc.y: conflicts: 7 shift/reduce
  6047. </pre>
  6048.    <p>When given <samp><span class="option">--report=state</span></samp>, in addition to <samp><span class="file">calc.tab.c</span></samp>, it
  6049. creates a file <samp><span class="file">calc.output</span></samp> with contents detailed below.  The
  6050. order of the output and the exact presentation might vary, but the
  6051. interpretation is the same.
  6052.  
  6053.    <p>The first section includes details on conflicts that were solved thanks
  6054. to precedence and/or associativity:
  6055.  
  6056. <pre class="example">     Conflict in state 8 between rule 2 and token '+' resolved as reduce.
  6057.      Conflict in state 8 between rule 2 and token '-' resolved as reduce.
  6058.      Conflict in state 8 between rule 2 and token '*' resolved as shift.
  6059. <br><small class="dots">...</small><br>
  6060. </pre>
  6061.    <p class="noindent">The next section lists states that still have conflicts.
  6062.  
  6063. <pre class="example">     State 8 conflicts: 1 shift/reduce
  6064.      State 9 conflicts: 1 shift/reduce
  6065.      State 10 conflicts: 1 shift/reduce
  6066.      State 11 conflicts: 4 shift/reduce
  6067. </pre>
  6068.    <p class="noindent"><a name="index-token_002c-useless-264"></a><a name="index-useless-token-265"></a><a name="index-nonterminal_002c-useless-266"></a><a name="index-useless-nonterminal-267"></a><a name="index-rule_002c-useless-268"></a><a name="index-useless-rule-269"></a>The next section reports useless tokens, nonterminal and rules.  Useless
  6069. nonterminals and rules are removed in order to produce a smaller parser,
  6070. but useless tokens are preserved, since they might be used by the
  6071. scanner (note the difference between “useless” and “not used”
  6072. below):
  6073.  
  6074. <pre class="example">     Useless nonterminals:
  6075.         useless
  6076.      
  6077.      Terminals which are not used:
  6078.         STR
  6079.      
  6080.      Useless rules:
  6081.      #6     useless: STR;
  6082. </pre>
  6083.    <p class="noindent">The next section reproduces the exact grammar that Bison used:
  6084.  
  6085. <pre class="example">     Grammar
  6086.      
  6087.        Number, Line, Rule
  6088.          0   5 $accept -> exp $end
  6089.          1   5 exp -> exp '+' exp
  6090.          2   6 exp -> exp '-' exp
  6091.          3   7 exp -> exp '*' exp
  6092.          4   8 exp -> exp '/' exp
  6093.          5   9 exp -> NUM
  6094. </pre>
  6095.    <p class="noindent">and reports the uses of the symbols:
  6096.  
  6097. <pre class="example">     Terminals, with rules where they appear
  6098.      
  6099.      $end (0) 0
  6100.      '*' (42) 3
  6101.      '+' (43) 1
  6102.      '-' (45) 2
  6103.      '/' (47) 4
  6104.      error (256)
  6105.      NUM (258) 5
  6106.      
  6107.      Nonterminals, with rules where they appear
  6108.      
  6109.      $accept (8)
  6110.          on left: 0
  6111.      exp (9)
  6112.          on left: 1 2 3 4 5, on right: 0 1 2 3 4
  6113. </pre>
  6114.    <p class="noindent"><a name="index-item-270"></a><a name="index-pointed-rule-271"></a><a name="index-rule_002c-pointed-272"></a>Bison then proceeds onto the automaton itself, describing each state
  6115. with it set of <dfn>items</dfn>, also known as <dfn>pointed rules</dfn>.  Each
  6116. item is a production rule together with a point (marked by `<samp><span class="samp">.</span></samp>')
  6117. that the input cursor.
  6118.  
  6119. <pre class="example">     state 0
  6120.      
  6121.          $accept  ->  . exp $   (rule 0)
  6122.      
  6123.          NUM         shift, and go to state 1
  6124.      
  6125.          exp         go to state 2
  6126. </pre>
  6127.    <p>This reads as follows: “state 0 corresponds to being at the very
  6128. beginning of the parsing, in the initial rule, right before the start
  6129. symbol (here, <code>exp</code>).  When the parser returns to this state right
  6130. after having reduced a rule that produced an <code>exp</code>, the control
  6131. flow jumps to state 2.  If there is no such transition on a nonterminal
  6132. symbol, and the lookahead is a <code>NUM</code>, then this token is shifted on
  6133. the parse stack, and the control flow jumps to state 1.  Any other
  6134. lookahead triggers a syntax error.”
  6135.  
  6136.    <p><a name="index-core_002c-item-set-273"></a><a name="index-item-set-core-274"></a><a name="index-kernel_002c-item-set-275"></a><a name="index-item-set-core-276"></a>Even though the only active rule in state 0 seems to be rule 0, the
  6137. report lists <code>NUM</code> as a lookahead symbol because <code>NUM</code> can be
  6138. at the beginning of any rule deriving an <code>exp</code>.  By default Bison
  6139. reports the so-called <dfn>core</dfn> or <dfn>kernel</dfn> of the item set, but if
  6140. you want to see more detail you can invoke <samp><span class="command">bison</span></samp> with
  6141. <samp><span class="option">--report=itemset</span></samp> to list all the items, include those that can
  6142. be derived:
  6143.  
  6144. <pre class="example">     state 0
  6145.      
  6146.          $accept  ->  . exp $   (rule 0)
  6147.          exp  ->  . exp '+' exp   (rule 1)
  6148.          exp  ->  . exp '-' exp   (rule 2)
  6149.          exp  ->  . exp '*' exp   (rule 3)
  6150.          exp  ->  . exp '/' exp   (rule 4)
  6151.          exp  ->  . NUM   (rule 5)
  6152.      
  6153.          NUM         shift, and go to state 1
  6154.      
  6155.          exp         go to state 2
  6156. </pre>
  6157.    <p class="noindent">In the state 1...
  6158.  
  6159. <pre class="example">     state 1
  6160.      
  6161.          exp  ->  NUM .   (rule 5)
  6162.      
  6163.          $default    reduce using rule 5 (exp)
  6164. </pre>
  6165.    <p class="noindent">the rule 5, `<samp><span class="samp">exp: NUM;</span></samp>', is completed.  Whatever the lookahead
  6166. (`<samp><span class="samp">$default</span></samp>'), the parser will reduce it.  If it was coming from
  6167. state 0, then, after this reduction it will return to state 0, and will
  6168. jump to state 2 (`<samp><span class="samp">exp: go to state 2</span></samp>').
  6169.  
  6170. <pre class="example">     state 2
  6171.      
  6172.          $accept  ->  exp . $   (rule 0)
  6173.          exp  ->  exp . '+' exp   (rule 1)
  6174.          exp  ->  exp . '-' exp   (rule 2)
  6175.          exp  ->  exp . '*' exp   (rule 3)
  6176.          exp  ->  exp . '/' exp   (rule 4)
  6177.      
  6178.          $           shift, and go to state 3
  6179.          '+'         shift, and go to state 4
  6180.          '-'         shift, and go to state 5
  6181.          '*'         shift, and go to state 6
  6182.          '/'         shift, and go to state 7
  6183. </pre>
  6184.    <p class="noindent">In state 2, the automaton can only shift a symbol.  For instance,
  6185. because of the item `<samp><span class="samp">exp -> exp . '+' exp</span></samp>', if the lookahead if
  6186. `<samp><span class="samp">+</span></samp>', it will be shifted on the parse stack, and the automaton
  6187. control will jump to state 4, corresponding to the item `<samp><span class="samp">exp -> exp
  6188. '+' . exp</span></samp>'.  Since there is no default action, any other token than
  6189. those listed above will trigger a syntax error.
  6190.  
  6191.    <p>The state 3 is named the <dfn>final state</dfn>, or the <dfn>accepting
  6192. state</dfn>:
  6193.  
  6194. <pre class="example">     state 3
  6195.      
  6196.          $accept  ->  exp $ .   (rule 0)
  6197.      
  6198.          $default    accept
  6199. </pre>
  6200.    <p class="noindent">the initial rule is completed (the start symbol and the end
  6201. of input were read), the parsing exits successfully.
  6202.  
  6203.    <p>The interpretation of states 4 to 7 is straightforward, and is left to
  6204. the reader.
  6205.  
  6206. <pre class="example">     state 4
  6207.      
  6208.          exp  ->  exp '+' . exp   (rule 1)
  6209.      
  6210.          NUM         shift, and go to state 1
  6211.      
  6212.          exp         go to state 8
  6213.      
  6214.      state 5
  6215.      
  6216.          exp  ->  exp '-' . exp   (rule 2)
  6217.      
  6218.          NUM         shift, and go to state 1
  6219.      
  6220.          exp         go to state 9
  6221.      
  6222.      state 6
  6223.      
  6224.          exp  ->  exp '*' . exp   (rule 3)
  6225.      
  6226.          NUM         shift, and go to state 1
  6227.      
  6228.          exp         go to state 10
  6229.      
  6230.      state 7
  6231.      
  6232.          exp  ->  exp '/' . exp   (rule 4)
  6233.      
  6234.          NUM         shift, and go to state 1
  6235.      
  6236.          exp         go to state 11
  6237. </pre>
  6238.    <p>As was announced in beginning of the report, `<samp><span class="samp">State 8 conflicts:
  6239. 1 shift/reduce</span></samp>':
  6240.  
  6241. <pre class="example">     state 8
  6242.      
  6243.          exp  ->  exp . '+' exp   (rule 1)
  6244.          exp  ->  exp '+' exp .   (rule 1)
  6245.          exp  ->  exp . '-' exp   (rule 2)
  6246.          exp  ->  exp . '*' exp   (rule 3)
  6247.          exp  ->  exp . '/' exp   (rule 4)
  6248.      
  6249.          '*'         shift, and go to state 6
  6250.          '/'         shift, and go to state 7
  6251.      
  6252.          '/'         [reduce using rule 1 (exp)]
  6253.          $default    reduce using rule 1 (exp)
  6254. </pre>
  6255.    <p>Indeed, there are two actions associated to the lookahead `<samp><span class="samp">/</span></samp>':
  6256. either shifting (and going to state 7), or reducing rule 1.  The
  6257. conflict means that either the grammar is ambiguous, or the parser lacks
  6258. information to make the right decision.  Indeed the grammar is
  6259. ambiguous, as, since we did not specify the precedence of `<samp><span class="samp">/</span></samp>', the
  6260. sentence `<samp><span class="samp">NUM + NUM / NUM</span></samp>' can be parsed as `<samp><span class="samp">NUM + (NUM /
  6261. NUM)</span></samp>', which corresponds to shifting `<samp><span class="samp">/</span></samp>', or as `<samp><span class="samp">(NUM + NUM) /
  6262. NUM</span></samp>', which corresponds to reducing rule 1.
  6263.  
  6264.    <p>Because in <acronym>LALR</acronym>(1) parsing a single decision can be made, Bison
  6265. arbitrarily chose to disable the reduction, see <a href="#Shift_002fReduce">Shift/Reduce Conflicts</a>.  Discarded actions are reported in between
  6266. square brackets.
  6267.  
  6268.    <p>Note that all the previous states had a single possible action: either
  6269. shifting the next token and going to the corresponding state, or
  6270. reducing a single rule.  In the other cases, i.e., when shifting
  6271. <em>and</em> reducing is possible or when <em>several</em> reductions are
  6272. possible, the lookahead is required to select the action.  State 8 is
  6273. one such state: if the lookahead is `<samp><span class="samp">*</span></samp>' or `<samp><span class="samp">/</span></samp>' then the action
  6274. is shifting, otherwise the action is reducing rule 1.  In other words,
  6275. the first two items, corresponding to rule 1, are not eligible when the
  6276. lookahead is `<samp><span class="samp">*</span></samp>', since we specified that `<samp><span class="samp">*</span></samp>' has higher
  6277. precedence that `<samp><span class="samp">+</span></samp>'.  More generally, some items are eligible only
  6278. with some set of possible lookaheads.  When run with
  6279. <samp><span class="option">--report=lookahead</span></samp>, Bison specifies these lookaheads:
  6280.  
  6281. <pre class="example">     state 8
  6282.      
  6283.          exp  ->  exp . '+' exp  [$, '+', '-', '/']   (rule 1)
  6284.          exp  ->  exp '+' exp .  [$, '+', '-', '/']   (rule 1)
  6285.          exp  ->  exp . '-' exp   (rule 2)
  6286.          exp  ->  exp . '*' exp   (rule 3)
  6287.          exp  ->  exp . '/' exp   (rule 4)
  6288.      
  6289.          '*'         shift, and go to state 6
  6290.          '/'         shift, and go to state 7
  6291.      
  6292.          '/'         [reduce using rule 1 (exp)]
  6293.          $default    reduce using rule 1 (exp)
  6294. </pre>
  6295.    <p>The remaining states are similar:
  6296.  
  6297. <pre class="example">     state 9
  6298.      
  6299.          exp  ->  exp . '+' exp   (rule 1)
  6300.          exp  ->  exp . '-' exp   (rule 2)
  6301.          exp  ->  exp '-' exp .   (rule 2)
  6302.          exp  ->  exp . '*' exp   (rule 3)
  6303.          exp  ->  exp . '/' exp   (rule 4)
  6304.      
  6305.          '*'         shift, and go to state 6
  6306.          '/'         shift, and go to state 7
  6307.      
  6308.          '/'         [reduce using rule 2 (exp)]
  6309.          $default    reduce using rule 2 (exp)
  6310.      
  6311.      state 10
  6312.      
  6313.          exp  ->  exp . '+' exp   (rule 1)
  6314.          exp  ->  exp . '-' exp   (rule 2)
  6315.          exp  ->  exp . '*' exp   (rule 3)
  6316.          exp  ->  exp '*' exp .   (rule 3)
  6317.          exp  ->  exp . '/' exp   (rule 4)
  6318.      
  6319.          '/'         shift, and go to state 7
  6320.      
  6321.          '/'         [reduce using rule 3 (exp)]
  6322.          $default    reduce using rule 3 (exp)
  6323.      
  6324.      state 11
  6325.      
  6326.          exp  ->  exp . '+' exp   (rule 1)
  6327.          exp  ->  exp . '-' exp   (rule 2)
  6328.          exp  ->  exp . '*' exp   (rule 3)
  6329.          exp  ->  exp . '/' exp   (rule 4)
  6330.          exp  ->  exp '/' exp .   (rule 4)
  6331.      
  6332.          '+'         shift, and go to state 4
  6333.          '-'         shift, and go to state 5
  6334.          '*'         shift, and go to state 6
  6335.          '/'         shift, and go to state 7
  6336.      
  6337.          '+'         [reduce using rule 4 (exp)]
  6338.          '-'         [reduce using rule 4 (exp)]
  6339.          '*'         [reduce using rule 4 (exp)]
  6340.          '/'         [reduce using rule 4 (exp)]
  6341.          $default    reduce using rule 4 (exp)
  6342. </pre>
  6343.    <p class="noindent">Observe that state 11 contains conflicts due to the lack of precedence
  6344. of `<samp><span class="samp">/</span></samp>' wrt `<samp><span class="samp">+</span></samp>', `<samp><span class="samp">-</span></samp>', and `<samp><span class="samp">*</span></samp>', but also because the
  6345. associativity of `<samp><span class="samp">/</span></samp>' is not specified.
  6346.  
  6347. <div class="node">
  6348. <p><hr>
  6349. <a name="Tracing"></a>
  6350. Previous: <a rel="previous" accesskey="p" href="#Understanding">Understanding</a>,
  6351. Up: <a rel="up" accesskey="u" href="#Debugging">Debugging</a>
  6352.  
  6353. </div>
  6354.  
  6355. <h3 class="section">8.2 Tracing Your Parser</h3>
  6356.  
  6357. <p><a name="index-yydebug-277"></a><a name="index-debugging-278"></a><a name="index-tracing-the-parser-279"></a>
  6358. If a Bison grammar compiles properly but doesn't do what you want when it
  6359. runs, the <code>yydebug</code> parser-trace feature can help you figure out why.
  6360.  
  6361.    <p>There are several means to enable compilation of trace facilities:
  6362.  
  6363.      <dl>
  6364. <dt>the macro <code>YYDEBUG</code><dd><a name="index-YYDEBUG-280"></a>Define the macro <code>YYDEBUG</code> to a nonzero value when you compile the
  6365. parser.  This is compliant with <acronym>POSIX</acronym> Yacc.  You could use
  6366. `<samp><span class="samp">-DYYDEBUG=1</span></samp>' as a compiler option or you could put `<samp><span class="samp">#define
  6367. YYDEBUG 1</span></samp>' in the prologue of the grammar file (see <a href="#Prologue">The Prologue</a>).
  6368.  
  6369.      <br><dt>the option <samp><span class="option">-t</span></samp>, <samp><span class="option">--debug</span></samp><dd>Use the `<samp><span class="samp">-t</span></samp>' option when you run Bison (see <a href="#Invocation">Invoking Bison</a>).  This is <acronym>POSIX</acronym> compliant too.
  6370.  
  6371.      <br><dt>the directive `<samp><span class="samp">%debug</span></samp>'<dd><a name="index-g_t_0025debug-281"></a>Add the <code>%debug</code> directive (see <a href="#Decl-Summary">Bison Declaration Summary</a>).  This is a Bison extension, which will prove
  6372. useful when Bison will output parsers for languages that don't use a
  6373. preprocessor.  Unless <acronym>POSIX</acronym> and Yacc portability matter to
  6374. you, this is
  6375. the preferred solution. 
  6376. </dl>
  6377.  
  6378.    <p>We suggest that you always enable the debug option so that debugging is
  6379. always possible.
  6380.  
  6381.    <p>The trace facility outputs messages with macro calls of the form
  6382. <code>YYFPRINTF (stderr, </code><var>format</var><code>, </code><var>args</var><code>)</code> where
  6383. <var>format</var> and <var>args</var> are the usual <code>printf</code> format and
  6384. arguments.  If you define <code>YYDEBUG</code> to a nonzero value but do not
  6385. define <code>YYFPRINTF</code>, <code><stdio.h></code> is automatically included
  6386. and <code>YYPRINTF</code> is defined to <code>fprintf</code>.
  6387.  
  6388.    <p>Once you have compiled the program with trace facilities, the way to
  6389. request a trace is to store a nonzero value in the variable <code>yydebug</code>. 
  6390. You can do this by making the C code do it (in <code>main</code>, perhaps), or
  6391. you can alter the value with a C debugger.
  6392.  
  6393.    <p>Each step taken by the parser when <code>yydebug</code> is nonzero produces a
  6394. line or two of trace information, written on <code>stderr</code>.  The trace
  6395. messages tell you these things:
  6396.  
  6397.      <ul>
  6398. <li>Each time the parser calls <code>yylex</code>, what kind of token was read.
  6399.  
  6400.      <li>Each time a token is shifted, the depth and complete contents of the
  6401. state stack (see <a href="#Parser-States">Parser States</a>).
  6402.  
  6403.      <li>Each time a rule is reduced, which rule it is, and the complete contents
  6404. of the state stack afterward. 
  6405. </ul>
  6406.  
  6407.    <p>To make sense of this information, it helps to refer to the listing file
  6408. produced by the Bison `<samp><span class="samp">-v</span></samp>' option (see <a href="#Invocation">Invoking Bison</a>).  This file shows the meaning of each state in terms of
  6409. positions in various rules, and also what each state will do with each
  6410. possible input token.  As you read the successive trace messages, you
  6411. can see that the parser is functioning according to its specification in
  6412. the listing file.  Eventually you will arrive at the place where
  6413. something undesirable happens, and you will see which parts of the
  6414. grammar are to blame.
  6415.  
  6416.    <p>The parser file is a C program and you can use C debuggers on it, but it's
  6417. not easy to interpret what it is doing.  The parser function is a
  6418. finite-state machine interpreter, and aside from the actions it executes
  6419. the same code over and over.  Only the values of variables show where in
  6420. the grammar it is working.
  6421.  
  6422.    <p><a name="index-YYPRINT-282"></a>The debugging information normally gives the token type of each token
  6423. read, but not its semantic value.  You can optionally define a macro
  6424. named <code>YYPRINT</code> to provide a way to print the value.  If you define
  6425. <code>YYPRINT</code>, it should take three arguments.  The parser will pass a
  6426. standard I/O stream, the numeric code for the token type, and the token
  6427. value (from <code>yylval</code>).
  6428.  
  6429.    <p>Here is an example of <code>YYPRINT</code> suitable for the multi-function
  6430. calculator (see <a href="#Mfcalc-Decl">Declarations for <code>mfcalc</code></a>):
  6431.  
  6432. <pre class="smallexample">     %{
  6433.        static void print_token_value (FILE *, int, YYSTYPE);
  6434.        #define YYPRINT(file, type, value) print_token_value (file, type, value)
  6435.      %}
  6436.      
  6437.      ... %% ... %% ...
  6438.      
  6439.      static void
  6440.      print_token_value (FILE *file, int type, YYSTYPE value)
  6441.      {
  6442.        if (type == VAR)
  6443.          fprintf (file, "%s", value.tptr->name);
  6444.        else if (type == NUM)
  6445.          fprintf (file, "%d", value.val);
  6446.      }
  6447. </pre>
  6448.    <!-- ================================================= Invoking Bison -->
  6449. <div class="node">
  6450. <p><hr>
  6451. <a name="Invocation"></a>
  6452. Next: <a rel="next" accesskey="n" href="#Table-of-Symbols">Table of Symbols</a>,
  6453. Previous: <a rel="previous" accesskey="p" href="#Debugging">Debugging</a>,
  6454. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  6455.  
  6456. </div>
  6457.  
  6458. <h2 class="chapter">9 Invoking Bison</h2>
  6459.  
  6460. <p><a name="index-invoking-Bison-283"></a><a name="index-Bison-invocation-284"></a><a name="index-options-for-invoking-Bison-285"></a>
  6461. The usual way to invoke Bison is as follows:
  6462.  
  6463. <pre class="example">     bison <var>infile</var>
  6464. </pre>
  6465.    <p>Here <var>infile</var> is the grammar file name, which usually ends in
  6466. `<samp><span class="samp">.y</span></samp>'.  The parser file's name is made by replacing the `<samp><span class="samp">.y</span></samp>'
  6467. with `<samp><span class="samp">.tab.c</span></samp>'.  Thus, the `<samp><span class="samp">bison foo.y</span></samp>' filename yields
  6468. <samp><span class="file">foo.tab.c</span></samp>, and the `<samp><span class="samp">bison hack/foo.y</span></samp>' filename yields
  6469. <samp><span class="file">hack/foo.tab.c</span></samp>.  It's also possible, in case you are writing
  6470. C++ code instead of C in your grammar file, to name it <samp><span class="file">foo.ypp</span></samp>
  6471. or <samp><span class="file">foo.y++</span></samp>.  Then, the output files will take an extension like
  6472. the given one as input (respectively <samp><span class="file">foo.tab.cpp</span></samp> and
  6473. <samp><span class="file">foo.tab.c++</span></samp>). 
  6474. This feature takes effect with all options that manipulate filenames like
  6475. `<samp><span class="samp">-o</span></samp>' or `<samp><span class="samp">-d</span></samp>'.
  6476.  
  6477.    <p>For example :
  6478.  
  6479. <pre class="example">     bison -d <var>infile.yxx</var>
  6480. </pre>
  6481.    <p class="noindent">will produce <samp><span class="file">infile.tab.cxx</span></samp> and <samp><span class="file">infile.tab.hxx</span></samp>, and
  6482.  
  6483. <pre class="example">     bison -d -o <var>output.c++</var> <var>infile.y</var>
  6484. </pre>
  6485.    <p class="noindent">will produce <samp><span class="file">output.c++</span></samp> and <samp><span class="file">outfile.h++</span></samp>.
  6486.  
  6487.    <p>For compatibility with <acronym>POSIX</acronym>, the standard Bison
  6488. distribution also contains a shell script called <samp><span class="command">yacc</span></samp> that
  6489. invokes Bison with the <samp><span class="option">-y</span></samp> option.
  6490.  
  6491. <ul class="menu">
  6492. <li><a accesskey="1" href="#Bison-Options">Bison Options</a>:      All the options described in detail,
  6493.                         in alphabetical order by short options. 
  6494. <li><a accesskey="2" href="#Option-Cross-Key">Option Cross Key</a>:   Alphabetical list of long options. 
  6495. <li><a accesskey="3" href="#Yacc-Library">Yacc Library</a>:       Yacc-compatible <code>yylex</code> and <code>main</code>. 
  6496. </ul>
  6497.  
  6498. <div class="node">
  6499. <p><hr>
  6500. <a name="Bison-Options"></a>
  6501. Next: <a rel="next" accesskey="n" href="#Option-Cross-Key">Option Cross Key</a>,
  6502. Up: <a rel="up" accesskey="u" href="#Invocation">Invocation</a>
  6503.  
  6504. </div>
  6505.  
  6506. <h3 class="section">9.1 Bison Options</h3>
  6507.  
  6508. <p>Bison supports both traditional single-letter options and mnemonic long
  6509. option names.  Long option names are indicated with `<samp><span class="samp">--</span></samp>' instead of
  6510. `<samp><span class="samp">-</span></samp>'.  Abbreviations for option names are allowed as long as they
  6511. are unique.  When a long option takes an argument, like
  6512. `<samp><span class="samp">--file-prefix</span></samp>', connect the option name and the argument with
  6513. `<samp><span class="samp">=</span></samp>'.
  6514.  
  6515.    <p>Here is a list of options that can be used with Bison, alphabetized by
  6516. short option.  It is followed by a cross key alphabetized by long
  6517. option.
  6518.  
  6519. <!-- Please, keep this ordered as in `bison -help'. -->
  6520. <p class="noindent">Operations modes:
  6521.      <dl>
  6522. <dt><samp><span class="option">-h</span></samp><dt><samp><span class="option">--help</span></samp><dd>Print a summary of the command-line options to Bison and exit.
  6523.  
  6524.      <br><dt><samp><span class="option">-V</span></samp><dt><samp><span class="option">--version</span></samp><dd>Print the version number of Bison and exit.
  6525.  
  6526.      <br><dt><samp><span class="option">-y</span></samp><dt><samp><span class="option">--yacc</span></samp><dd>Equivalent to `<samp><span class="samp">-o y.tab.c</span></samp>'; the parser output file is called
  6527. <samp><span class="file">y.tab.c</span></samp>, and the other outputs are called <samp><span class="file">y.output</span></samp> and
  6528. <samp><span class="file">y.tab.h</span></samp>.  The purpose of this option is to imitate Yacc's output
  6529. file name conventions.  Thus, the following shell script can substitute
  6530. for Yacc, and the Bison distribution contains such a script for
  6531. compatibility with <acronym>POSIX</acronym>:
  6532.  
  6533.      <pre class="example">          #! /bin/sh
  6534.           bison -y "$¨
  6535.      </pre>
  6536.      </dl>
  6537.  
  6538. <p class="noindent">Tuning the parser:
  6539.  
  6540.      <dl>
  6541. <dt><samp><span class="option">-S </span><var>file</var></samp><dt><samp><span class="option">--skeleton=</span><var>file</var></samp><dd>Specify the skeleton to use.  You probably don't need this option unless
  6542. you are developing Bison.
  6543.  
  6544.      <br><dt><samp><span class="option">-t</span></samp><dt><samp><span class="option">--debug</span></samp><dd>In the parser file, define the macro <code>YYDEBUG</code> to 1 if it is not
  6545. already defined, so that the debugging facilities are compiled. 
  6546. See <a href="#Tracing">Tracing Your Parser</a>.
  6547.  
  6548.      <br><dt><samp><span class="option">--locations</span></samp><dd>Pretend that <code>%locations</code> was specified.  See <a href="#Decl-Summary">Decl Summary</a>.
  6549.  
  6550.      <br><dt><samp><span class="option">-p </span><var>prefix</var></samp><dt><samp><span class="option">--name-prefix=</span><var>prefix</var></samp><dd>Pretend that <code>%name-prefix="</code><var>prefix</var><code>"</code> was specified. 
  6551. See <a href="#Decl-Summary">Decl Summary</a>.
  6552.  
  6553.      <br><dt><samp><span class="option">-l</span></samp><dt><samp><span class="option">--no-lines</span></samp><dd>Don't put any <code>#line</code> preprocessor commands in the parser file. 
  6554. Ordinarily Bison puts them in the parser file so that the C compiler
  6555. and debuggers will associate errors with your source file, the
  6556. grammar file.  This option causes them to associate errors with the
  6557. parser file, treating it as an independent source file in its own right.
  6558.  
  6559.      <br><dt><samp><span class="option">-n</span></samp><dt><samp><span class="option">--no-parser</span></samp><dd>Pretend that <code>%no-parser</code> was specified.  See <a href="#Decl-Summary">Decl Summary</a>.
  6560.  
  6561.      <br><dt><samp><span class="option">-k</span></samp><dt><samp><span class="option">--token-table</span></samp><dd>Pretend that <code>%token-table</code> was specified.  See <a href="#Decl-Summary">Decl Summary</a>. 
  6562. </dl>
  6563.  
  6564. <p class="noindent">Adjust the output:
  6565.  
  6566.      <dl>
  6567. <dt><samp><span class="option">-d</span></samp><dt><samp><span class="option">--defines</span></samp><dd>Pretend that <code>%defines</code> was specified, i.e., write an extra output
  6568. file containing macro definitions for the token type names defined in
  6569. the grammar and the semantic value type <code>YYSTYPE</code>, as well as a few
  6570. <code>extern</code> variable declarations.  See <a href="#Decl-Summary">Decl Summary</a>.
  6571.  
  6572.      <br><dt><samp><span class="option">--defines=</span><var>defines-file</var></samp><dd>Same as above, but save in the file <var>defines-file</var>.
  6573.  
  6574.      <br><dt><samp><span class="option">-b </span><var>file-prefix</var></samp><dt><samp><span class="option">--file-prefix=</span><var>prefix</var></samp><dd>Pretend that <code>%verbose</code> was specified, i.e, specify prefix to use
  6575. for all Bison output file names.  See <a href="#Decl-Summary">Decl Summary</a>.
  6576.  
  6577.      <br><dt><samp><span class="option">-r </span><var>things</var></samp><dt><samp><span class="option">--report=</span><var>things</var></samp><dd>Write an extra output file containing verbose description of the comma
  6578. separated list of <var>things</var> among:
  6579.  
  6580.           <dl>
  6581. <dt><code>state</code><dd>Description of the grammar, conflicts (resolved and unresolved), and
  6582. <acronym>LALR</acronym> automaton.
  6583.  
  6584.           <br><dt><code>lookahead</code><dd>Implies <code>state</code> and augments the description of the automaton with
  6585. each rule's lookahead set.
  6586.  
  6587.           <br><dt><code>itemset</code><dd>Implies <code>state</code> and augments the description of the automaton with
  6588. the full set of items for each state, instead of its core only. 
  6589. </dl>
  6590.  
  6591.      <p>For instance, on the following grammar
  6592.  
  6593.      <br><dt><samp><span class="option">-v</span></samp><dt><samp><span class="option">--verbose</span></samp><dd>Pretend that <code>%verbose</code> was specified, i.e, write an extra output
  6594. file containing verbose descriptions of the grammar and
  6595. parser.  See <a href="#Decl-Summary">Decl Summary</a>.
  6596.  
  6597.      <br><dt><samp><span class="option">-o </span><var>filename</var></samp><dt><samp><span class="option">--output=</span><var>filename</var></samp><dd>Specify the <var>filename</var> for the parser file.
  6598.  
  6599.      <p>The other output files' names are constructed from <var>filename</var> as
  6600. described under the `<samp><span class="samp">-v</span></samp>' and `<samp><span class="samp">-d</span></samp>' options.
  6601.  
  6602.      <br><dt><samp><span class="option">-g</span></samp><dd>Output a <acronym>VCG</acronym> definition of the <acronym>LALR</acronym>(1) grammar
  6603. automaton computed by Bison.  If the grammar file is <samp><span class="file">foo.y</span></samp>, the
  6604. <acronym>VCG</acronym> output file will
  6605. be <samp><span class="file">foo.vcg</span></samp>.
  6606.  
  6607.      <br><dt><samp><span class="option">--graph=</span><var>graph-file</var></samp><dd>The behavior of <var>–graph</var> is the same than `<samp><span class="samp">-g</span></samp>'.  The only
  6608. difference is that it has an optional argument which is the name of
  6609. the output graph filename. 
  6610. </dl>
  6611.  
  6612. <div class="node">
  6613. <p><hr>
  6614. <a name="Option-Cross-Key"></a>
  6615. Next: <a rel="next" accesskey="n" href="#Yacc-Library">Yacc Library</a>,
  6616. Previous: <a rel="previous" accesskey="p" href="#Bison-Options">Bison Options</a>,
  6617. Up: <a rel="up" accesskey="u" href="#Invocation">Invocation</a>
  6618.  
  6619. </div>
  6620.  
  6621. <h3 class="section">9.2 Option Cross Key</h3>
  6622.  
  6623. <p>Here is a list of options, alphabetized by long option, to help you find
  6624. the corresponding short option.
  6625.  
  6626. <div class="node">
  6627. <p><hr>
  6628. <a name="Yacc-Library"></a>
  6629. Previous: <a rel="previous" accesskey="p" href="#Option-Cross-Key">Option Cross Key</a>,
  6630. Up: <a rel="up" accesskey="u" href="#Invocation">Invocation</a>
  6631.  
  6632. </div>
  6633.  
  6634. <h3 class="section">9.3 Yacc Library</h3>
  6635.  
  6636. <p>The Yacc library contains default implementations of the
  6637. <code>yyerror</code> and <code>main</code> functions.  These default
  6638. implementations are normally not useful, but <acronym>POSIX</acronym> requires
  6639. them.  To use the Yacc library, link your program with the
  6640. <samp><span class="option">-ly</span></samp> option.  Note that Bison's implementation of the Yacc
  6641. library is distributed under the terms of the <acronym>GNU</acronym> General
  6642. Public License (see <a href="#Copying">Copying</a>).
  6643.  
  6644.    <p>If you use the Yacc library's <code>yyerror</code> function, you should
  6645. declare <code>yyerror</code> as follows:
  6646.  
  6647. <pre class="example">     int yyerror (char const *);
  6648. </pre>
  6649.    <p>Bison ignores the <code>int</code> value returned by this <code>yyerror</code>. 
  6650. If you use the Yacc library's <code>main</code> function, your
  6651. <code>yyparse</code> function should have the following type signature:
  6652.  
  6653. <pre class="example">     int yyparse (void);
  6654. </pre>
  6655.    <!-- ================================================= Invoking Bison -->
  6656. <div class="node">
  6657. <p><hr>
  6658. <a name="FAQ"></a>
  6659. Next: <a rel="next" accesskey="n" href="#Copying-This-Manual">Copying This Manual</a>,
  6660. Previous: <a rel="previous" accesskey="p" href="#Glossary">Glossary</a>,
  6661. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  6662.  
  6663. </div>
  6664.  
  6665. <h2 class="chapter">10 Frequently Asked Questions</h2>
  6666.  
  6667. <p><a name="index-frequently-asked-questions-286"></a><a name="index-questions-287"></a>
  6668. Several questions about Bison come up occasionally.  Here some of them
  6669. are addressed.
  6670.  
  6671. <ul class="menu">
  6672. <li><a accesskey="1" href="#Parser-Stack-Overflow">Parser Stack Overflow</a>:       Breaking the Stack Limits
  6673. </ul>
  6674.  
  6675. <div class="node">
  6676. <p><hr>
  6677. <a name="Parser-Stack-Overflow"></a>
  6678. Up: <a rel="up" accesskey="u" href="#FAQ">FAQ</a>
  6679.  
  6680. </div>
  6681.  
  6682. <h3 class="section">10.1 Parser Stack Overflow</h3>
  6683.  
  6684. <pre class="display">     My parser returns with error with a `<samp><span class="samp">parser stack overflow</span></samp>'
  6685.      message.  What can I do?
  6686. </pre>
  6687.    <p>This question is already addressed elsewhere, See <a href="#Recursion">Recursive Rules</a>.
  6688.  
  6689. <!-- ================================================= Table of Symbols -->
  6690. <div class="node">
  6691. <p><hr>
  6692. <a name="Table-of-Symbols"></a>
  6693. Next: <a rel="next" accesskey="n" href="#Glossary">Glossary</a>,
  6694. Previous: <a rel="previous" accesskey="p" href="#Invocation">Invocation</a>,
  6695. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  6696.  
  6697. </div>
  6698.  
  6699. <h2 class="appendix">Appendix A Bison Symbols</h2>
  6700.  
  6701. <p><a name="index-Bison-symbols_002c-table-of-288"></a><a name="index-symbols-in-Bison_002c-table-of-289"></a>
  6702.  
  6703. <div class="defun">
  6704. — Variable: <b>@$</b><var><a name="index-g_t_0040_0040_0024-290"></a></var><br>
  6705. <blockquote><p>In an action, the location of the left-hand side of the rule. 
  6706. See <a href="#Locations">Locations Overview</a>. 
  6707. </p></blockquote></div>
  6708.  
  6709. <div class="defun">
  6710. — Variable: <b>@</b><var>n</var><var><a name="index-g_t_0040_0040_0040var_007bn_007d-291"></a></var><br>
  6711. <blockquote><p>In an action, the location of the <var>n</var>-th symbol of the right-hand
  6712. side of the rule.  See <a href="#Locations">Locations Overview</a>. 
  6713. </p></blockquote></div>
  6714.  
  6715. <div class="defun">
  6716. — Variable: <b>$$</b><var><a name="index-g_t_0024_0024-292"></a></var><br>
  6717. <blockquote><p>In an action, the semantic value of the left-hand side of the rule. 
  6718. See <a href="#Actions">Actions</a>. 
  6719. </p></blockquote></div>
  6720.  
  6721. <div class="defun">
  6722. — Variable: <b>$</b><var>n<a name="index-g_t_0024-293"></a></var><br>
  6723. <blockquote><p>In an action, the semantic value of the <var>n</var>-th symbol of the
  6724. right-hand side of the rule.  See <a href="#Actions">Actions</a>. 
  6725. </p></blockquote></div>
  6726.  
  6727. <div class="defun">
  6728. — Symbol: <b>$accept</b><var><a name="index-g_t_0024accept-294"></a></var><br>
  6729. <blockquote><p>The predefined nonterminal whose only rule is `<samp><span class="samp">$accept: </span><var>start</var><span class="samp">
  6730. $end</span></samp>', where <var>start</var> is the start symbol.  See <a href="#Start-Decl">The Start-Symbol</a>.  It cannot be used in the grammar. 
  6731. </p></blockquote></div>
  6732.  
  6733. <div class="defun">
  6734. — Symbol: <b>$end</b><var><a name="index-g_t_0024end-295"></a></var><br>
  6735. <blockquote><p>The predefined token marking the end of the token stream.  It cannot be
  6736. used in the grammar. 
  6737. </p></blockquote></div>
  6738.  
  6739. <div class="defun">
  6740. — Symbol: <b>$undefined</b><var><a name="index-g_t_0024undefined-296"></a></var><br>
  6741. <blockquote><p>The predefined token onto which all undefined values returned by
  6742. <code>yylex</code> are mapped.  It cannot be used in the grammar, rather, use
  6743. <code>error</code>. 
  6744. </p></blockquote></div>
  6745.  
  6746. <div class="defun">
  6747. — Symbol: <b>error</b><var><a name="index-error-297"></a></var><br>
  6748. <blockquote><p>A token name reserved for error recovery.  This token may be used in
  6749. grammar rules so as to allow the Bison parser to recognize an error in
  6750. the grammar without halting the process.  In effect, a sentence
  6751. containing an error may be recognized as valid.  On a syntax error, the
  6752. token <code>error</code> becomes the current look-ahead token.  Actions
  6753. corresponding to <code>error</code> are then executed, and the look-ahead
  6754. token is reset to the token that originally caused the violation. 
  6755. See <a href="#Error-Recovery">Error Recovery</a>. 
  6756. </p></blockquote></div>
  6757.  
  6758. <div class="defun">
  6759. — Macro: <b>YYABORT</b><var><a name="index-YYABORT-298"></a></var><br>
  6760. <blockquote><p>Macro to pretend that an unrecoverable syntax error has occurred, by
  6761. making <code>yyparse</code> return 1 immediately.  The error reporting
  6762. function <code>yyerror</code> is not called.  See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
  6763. </p></blockquote></div>
  6764.  
  6765. <div class="defun">
  6766. — Macro: <b>YYACCEPT</b><var><a name="index-YYACCEPT-299"></a></var><br>
  6767. <blockquote><p>Macro to pretend that a complete utterance of the language has been
  6768. read, by making <code>yyparse</code> return 0 immediately. 
  6769. See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
  6770. </p></blockquote></div>
  6771.  
  6772. <div class="defun">
  6773. — Macro: <b>YYBACKUP</b><var><a name="index-YYBACKUP-300"></a></var><br>
  6774. <blockquote><p>Macro to discard a value from the parser stack and fake a look-ahead
  6775. token.  See <a href="#Action-Features">Special Features for Use in Actions</a>. 
  6776. </p></blockquote></div>
  6777.  
  6778. <div class="defun">
  6779. — Macro: <b>YYDEBUG</b><var><a name="index-YYDEBUG-301"></a></var><br>
  6780. <blockquote><p>Macro to define to equip the parser with tracing code.  See <a href="#Tracing">Tracing Your Parser</a>. 
  6781. </p></blockquote></div>
  6782.  
  6783. <div class="defun">
  6784. — Macro: <b>YYERROR</b><var><a name="index-YYERROR-302"></a></var><br>
  6785. <blockquote><p>Macro to pretend that a syntax error has just been detected: call
  6786. <code>yyerror</code> and then perform normal error recovery if possible
  6787. (see <a href="#Error-Recovery">Error Recovery</a>), or (if recovery is impossible) make
  6788. <code>yyparse</code> return 1.  See <a href="#Error-Recovery">Error Recovery</a>. 
  6789. </p></blockquote></div>
  6790.  
  6791. <div class="defun">
  6792. — Macro: <b>YYERROR_VERBOSE</b><var><a name="index-YYERROR_005fVERBOSE-303"></a></var><br>
  6793. <blockquote><p>An obsolete macro that you define with <code>#define</code> in the prologue
  6794. to request verbose, specific error message strings
  6795. when <code>yyerror</code> is called.  It doesn't matter what definition you
  6796. use for <code>YYERROR_VERBOSE</code>, just whether you define it.  Using
  6797. <code>%error-verbose</code> is preferred. 
  6798. </p></blockquote></div>
  6799.  
  6800. <div class="defun">
  6801. — Macro: <b>YYINITDEPTH</b><var><a name="index-YYINITDEPTH-304"></a></var><br>
  6802. <blockquote><p>Macro for specifying the initial size of the parser stack. 
  6803. See <a href="#Stack-Overflow">Stack Overflow</a>. 
  6804. </p></blockquote></div>
  6805.  
  6806. <div class="defun">
  6807. — Macro: <b>YYLEX_PARAM</b><var><a name="index-YYLEX_005fPARAM-305"></a></var><br>
  6808. <blockquote><p>An obsolete macro for specifying an extra argument (or list of extra
  6809. arguments) for <code>yyparse</code> to pass to <code>yylex</code>.  he use of this
  6810. macro is deprecated, and is supported only for Yacc like parsers. 
  6811. See <a href="#Pure-Calling">Calling Conventions for Pure Parsers</a>. 
  6812. </p></blockquote></div>
  6813.  
  6814. <div class="defun">
  6815. — Type: <b>YYLTYPE</b><var><a name="index-YYLTYPE-306"></a></var><br>
  6816. <blockquote><p>Data type of <code>yylloc</code>; by default, a structure with four
  6817. members.  See <a href="#Location-Type">Data Types of Locations</a>. 
  6818. </p></blockquote></div>
  6819.  
  6820. <div class="defun">
  6821. — Macro: <b>YYMAXDEPTH</b><var><a name="index-YYMAXDEPTH-307"></a></var><br>
  6822. <blockquote><p>Macro for specifying the maximum size of the parser stack.  See <a href="#Stack-Overflow">Stack Overflow</a>. 
  6823. </p></blockquote></div>
  6824.  
  6825. <div class="defun">
  6826. — Macro: <b>YYPARSE_PARAM</b><var><a name="index-YYPARSE_005fPARAM-308"></a></var><br>
  6827. <blockquote><p>An obsolete macro for specifying the name of a parameter that
  6828. <code>yyparse</code> should accept.  The use of this macro is deprecated, and
  6829. is supported only for Yacc like parsers.  See <a href="#Pure-Calling">Calling Conventions for Pure Parsers</a>. 
  6830. </p></blockquote></div>
  6831.  
  6832. <div class="defun">
  6833. — Macro: <b>YYRECOVERING</b><var><a name="index-YYRECOVERING-309"></a></var><br>
  6834. <blockquote><p>Macro whose value indicates whether the parser is recovering from a
  6835. syntax error.  See <a href="#Action-Features">Special Features for Use in Actions</a>. 
  6836. </p></blockquote></div>
  6837.  
  6838. <div class="defun">
  6839. — Macro: <b>YYSTACK_USE_ALLOCA</b><var><a name="index-YYSTACK_005fUSE_005fALLOCA-310"></a></var><br>
  6840. <blockquote><p>Macro used to control the use of <code>alloca</code>.  If defined to `<samp><span class="samp">0</span></samp>',
  6841. the parser will not use <code>alloca</code> but <code>malloc</code> when trying to
  6842. grow its internal stacks.  Do <em>not</em> define <code>YYSTACK_USE_ALLOCA</code>
  6843. to anything else. 
  6844. </p></blockquote></div>
  6845.  
  6846. <div class="defun">
  6847. — Type: <b>YYSTYPE</b><var><a name="index-YYSTYPE-311"></a></var><br>
  6848. <blockquote><p>Data type of semantic values; <code>int</code> by default. 
  6849. See <a href="#Value-Type">Data Types of Semantic Values</a>. 
  6850. </p></blockquote></div>
  6851.  
  6852. <div class="defun">
  6853. — Variable: <b>yychar</b><var><a name="index-yychar-312"></a></var><br>
  6854. <blockquote><p>External integer variable that contains the integer value of the current
  6855. look-ahead token.  (In a pure parser, it is a local variable within
  6856. <code>yyparse</code>.)  Error-recovery rule actions may examine this variable. 
  6857. See <a href="#Action-Features">Special Features for Use in Actions</a>. 
  6858. </p></blockquote></div>
  6859.  
  6860. <div class="defun">
  6861. — Variable: <b>yyclearin</b><var><a name="index-yyclearin-313"></a></var><br>
  6862. <blockquote><p>Macro used in error-recovery rule actions.  It clears the previous
  6863. look-ahead token.  See <a href="#Error-Recovery">Error Recovery</a>. 
  6864. </p></blockquote></div>
  6865.  
  6866. <div class="defun">
  6867. — Variable: <b>yydebug</b><var><a name="index-yydebug-314"></a></var><br>
  6868. <blockquote><p>External integer variable set to zero by default.  If <code>yydebug</code>
  6869. is given a nonzero value, the parser will output information on input
  6870. symbols and parser action.  See <a href="#Tracing">Tracing Your Parser</a>. 
  6871. </p></blockquote></div>
  6872.  
  6873. <div class="defun">
  6874. — Macro: <b>yyerrok</b><var><a name="index-yyerrok-315"></a></var><br>
  6875. <blockquote><p>Macro to cause parser to recover immediately to its normal mode
  6876. after a syntax error.  See <a href="#Error-Recovery">Error Recovery</a>. 
  6877. </p></blockquote></div>
  6878.  
  6879. <div class="defun">
  6880. — Function: <b>yyerror</b><var><a name="index-yyerror-316"></a></var><br>
  6881. <blockquote><p>User-supplied function to be called by <code>yyparse</code> on error. 
  6882. See <a href="#Error-Reporting">The Error Reporting Function <code>yyerror</code></a>. 
  6883. </p></blockquote></div>
  6884.  
  6885. <div class="defun">
  6886. — Function: <b>yylex</b><var><a name="index-yylex-317"></a></var><br>
  6887. <blockquote><p>User-supplied lexical analyzer function, called with no arguments to get
  6888. the next token.  See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>. 
  6889. </p></blockquote></div>
  6890.  
  6891. <div class="defun">
  6892. — Variable: <b>yylval</b><var><a name="index-yylval-318"></a></var><br>
  6893. <blockquote><p>External variable in which <code>yylex</code> should place the semantic
  6894. value associated with a token.  (In a pure parser, it is a local
  6895. variable within <code>yyparse</code>, and its address is passed to
  6896. <code>yylex</code>.)  See <a href="#Token-Values">Semantic Values of Tokens</a>. 
  6897. </p></blockquote></div>
  6898.  
  6899. <div class="defun">
  6900. — Variable: <b>yylloc</b><var><a name="index-yylloc-319"></a></var><br>
  6901. <blockquote><p>External variable in which <code>yylex</code> should place the line and column
  6902. numbers associated with a token.  (In a pure parser, it is a local
  6903. variable within <code>yyparse</code>, and its address is passed to
  6904. <code>yylex</code>.)  You can ignore this variable if you don't use the
  6905. `<samp><span class="samp">@</span></samp>' feature in the grammar actions.  See <a href="#Token-Positions">Textual Positions of Tokens</a>. 
  6906. </p></blockquote></div>
  6907.  
  6908. <div class="defun">
  6909. — Variable: <b>yynerrs</b><var><a name="index-yynerrs-320"></a></var><br>
  6910. <blockquote><p>Global variable which Bison increments each time there is a syntax error. 
  6911. (In a pure parser, it is a local variable within <code>yyparse</code>.) 
  6912. See <a href="#Error-Reporting">The Error Reporting Function <code>yyerror</code></a>. 
  6913. </p></blockquote></div>
  6914.  
  6915. <div class="defun">
  6916. — Function: <b>yyparse</b><var><a name="index-yyparse-321"></a></var><br>
  6917. <blockquote><p>The parser function produced by Bison; call this function to start
  6918. parsing.  See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
  6919. </p></blockquote></div>
  6920.  
  6921. <div class="defun">
  6922. — Directive: <b>%debug</b><var><a name="index-g_t_0025debug-322"></a></var><br>
  6923. <blockquote><p>Equip the parser for debugging.  See <a href="#Decl-Summary">Decl Summary</a>. 
  6924. </p></blockquote></div>
  6925.  
  6926. <div class="defun">
  6927. — Directive: <b>%defines</b><var><a name="index-g_t_0025defines-323"></a></var><br>
  6928. <blockquote><p>Bison declaration to create a header file meant for the scanner. 
  6929. See <a href="#Decl-Summary">Decl Summary</a>. 
  6930. </p></blockquote></div>
  6931.  
  6932. <div class="defun">
  6933. — Directive: <b>%destructor</b><var><a name="index-g_t_0025destructor-324"></a></var><br>
  6934. <blockquote><p>Specifying how the parser should reclaim the memory associated to
  6935. discarded symbols. See <a href="#Destructor-Decl">Freeing Discarded Symbols</a>. 
  6936. </p></blockquote></div>
  6937.  
  6938. <div class="defun">
  6939. — Directive: <b>%dprec</b><var><a name="index-g_t_0025dprec-325"></a></var><br>
  6940. <blockquote><p>Bison declaration to assign a precedence to a rule that is used at parse
  6941. time to resolve reduce/reduce conflicts.  See <a href="#GLR-Parsers">Writing <acronym>GLR</acronym> Parsers</a>. 
  6942. </p></blockquote></div>
  6943.  
  6944. <div class="defun">
  6945. — Directive: <b>%error-verbose</b><var><a name="index-g_t_0025error_002dverbose-326"></a></var><br>
  6946. <blockquote><p>Bison declaration to request verbose, specific error message strings
  6947. when <code>yyerror</code> is called. 
  6948. </p></blockquote></div>
  6949.  
  6950. <div class="defun">
  6951. — Directive: <b>%file-prefix="</b><var>prefix"<a name="index-g_t_0025file_002dprefix_003d_0022-327"></a></var><br>
  6952. <blockquote><p>Bison declaration to set the prefix of the output files.  See <a href="#Decl-Summary">Decl Summary</a>. 
  6953. </p></blockquote></div>
  6954.  
  6955. <div class="defun">
  6956. — Directive: <b>%glr-parser</b><var><a name="index-g_t_0025glr_002dparser-328"></a></var><br>
  6957. <blockquote><p>Bison declaration to produce a <acronym>GLR</acronym> parser.  See <a href="#GLR-Parsers">Writing <acronym>GLR</acronym> Parsers</a>. 
  6958. </p></blockquote></div>
  6959.  
  6960. <div class="defun">
  6961. — Directive: <b>%left</b><var><a name="index-g_t_0025left-329"></a></var><br>
  6962. <blockquote><p>Bison declaration to assign left associativity to token(s). 
  6963. See <a href="#Precedence-Decl">Operator Precedence</a>. 
  6964. </p></blockquote></div>
  6965.  
  6966. <div class="defun">
  6967. — Directive: <b>%merge</b><var><a name="index-g_t_0025merge-330"></a></var><br>
  6968. <blockquote><p>Bison declaration to assign a merging function to a rule.  If there is a
  6969. reduce/reduce conflict with a rule having the same merging function, the
  6970. function is applied to the two semantic values to get a single result. 
  6971. See <a href="#GLR-Parsers">Writing <acronym>GLR</acronym> Parsers</a>. 
  6972. </p></blockquote></div>
  6973.  
  6974. <div class="defun">
  6975. — Directive: <b>%name-prefix="</b><var>prefix"<a name="index-g_t_0025name_002dprefix_003d_0022-331"></a></var><br>
  6976. <blockquote><p>Bison declaration to rename the external symbols.  See <a href="#Decl-Summary">Decl Summary</a>. 
  6977. </p></blockquote></div>
  6978.  
  6979. <div class="defun">
  6980. — Directive: <b>%no-lines</b><var><a name="index-g_t_0025no_002dlines-332"></a></var><br>
  6981. <blockquote><p>Bison declaration to avoid generating <code>#line</code> directives in the
  6982. parser file.  See <a href="#Decl-Summary">Decl Summary</a>. 
  6983. </p></blockquote></div>
  6984.  
  6985. <div class="defun">
  6986. — Directive: <b>%nonassoc</b><var><a name="index-g_t_0025nonassoc-333"></a></var><br>
  6987. <blockquote><p>Bison declaration to assign non-associativity to token(s). 
  6988. See <a href="#Precedence-Decl">Operator Precedence</a>. 
  6989. </p></blockquote></div>
  6990.  
  6991. <div class="defun">
  6992. — Directive: <b>%output="</b><var>filename"<a name="index-g_t_0025output_003d_0022-334"></a></var><br>
  6993. <blockquote><p>Bison declaration to set the name of the parser file.  See <a href="#Decl-Summary">Decl Summary</a>. 
  6994. </p></blockquote></div>
  6995.  
  6996. <div class="defun">
  6997. — Directive: <b>%prec</b><var><a name="index-g_t_0025prec-335"></a></var><br>
  6998. <blockquote><p>Bison declaration to assign a precedence to a specific rule. 
  6999. See <a href="#Contextual-Precedence">Context-Dependent Precedence</a>. 
  7000. </p></blockquote></div>
  7001.  
  7002. <div class="defun">
  7003. — Directive: <b>%pure-parser</b><var><a name="index-g_t_0025pure_002dparser-336"></a></var><br>
  7004. <blockquote><p>Bison declaration to request a pure (reentrant) parser. 
  7005. See <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>. 
  7006. </p></blockquote></div>
  7007.  
  7008. <div class="defun">
  7009. — Directive: <b>%right</b><var><a name="index-g_t_0025right-337"></a></var><br>
  7010. <blockquote><p>Bison declaration to assign right associativity to token(s). 
  7011. See <a href="#Precedence-Decl">Operator Precedence</a>. 
  7012. </p></blockquote></div>
  7013.  
  7014. <div class="defun">
  7015. — Directive: <b>%start</b><var><a name="index-g_t_0025start-338"></a></var><br>
  7016. <blockquote><p>Bison declaration to specify the start symbol.  See <a href="#Start-Decl">The Start-Symbol</a>. 
  7017. </p></blockquote></div>
  7018.  
  7019. <div class="defun">
  7020. — Directive: <b>%token</b><var><a name="index-g_t_0025token-339"></a></var><br>
  7021. <blockquote><p>Bison declaration to declare token(s) without specifying precedence. 
  7022. See <a href="#Token-Decl">Token Type Names</a>. 
  7023. </p></blockquote></div>
  7024.  
  7025. <div class="defun">
  7026. — Directive: <b>%token-table</b><var><a name="index-g_t_0025token_002dtable-340"></a></var><br>
  7027. <blockquote><p>Bison declaration to include a token name table in the parser file. 
  7028. See <a href="#Decl-Summary">Decl Summary</a>. 
  7029. </p></blockquote></div>
  7030.  
  7031. <div class="defun">
  7032. — Directive: <b>%type</b><var><a name="index-g_t_0025type-341"></a></var><br>
  7033. <blockquote><p>Bison declaration to declare nonterminals.  See <a href="#Type-Decl">Nonterminal Symbols</a>. 
  7034. </p></blockquote></div>
  7035.  
  7036. <div class="defun">
  7037. — Directive: <b>%union</b><var><a name="index-g_t_0025union-342"></a></var><br>
  7038. <blockquote><p>Bison declaration to specify several possible data types for semantic
  7039. values.  See <a href="#Union-Decl">The Collection of Value Types</a>. 
  7040. </p></blockquote></div>
  7041.  
  7042.    <pre class="sp">
  7043.  
  7044. </pre>
  7045.  
  7046. These are the punctuation and delimiters used in Bison input:
  7047.  
  7048. <div class="defun">
  7049. — Delimiter: <b>%%</b><var><a name="index-g_t_0025_0025-343"></a></var><br>
  7050. <blockquote><p>Delimiter used to separate the grammar rule section from the
  7051. Bison declarations section or the epilogue. 
  7052. See <a href="#Grammar-Layout">The Overall Layout of a Bison Grammar</a>. 
  7053. </p></blockquote></div>
  7054.  
  7055. <!-- Don't insert spaces, or check the DVI output. -->
  7056. <div class="defun">
  7057. — Delimiter: <b>%</b><var>{code%}<a name="index-g_t_0025-344"></a></var><br>
  7058. <blockquote><p>All code listed between `<samp><span class="samp">%{</span></samp>' and `<samp><span class="samp">%}</span></samp>' is copied directly to
  7059. the output file uninterpreted.  Such code forms the prologue of the input
  7060. file.  See <a href="#Grammar-Outline">Outline of a Bison Grammar</a>. 
  7061. </p></blockquote></div>
  7062.  
  7063. <div class="defun">
  7064. — Construct: <b>/*</b><var><small class="dots">...</small>*/<a name="index-g_t_002f_002a-345"></a></var><br>
  7065. <blockquote><p>Comment delimiters, as in C. 
  7066. </p></blockquote></div>
  7067.  
  7068. <div class="defun">
  7069. — Delimiter: <b>:</b><var><a name="index-g_t_003a-346"></a></var><br>
  7070. <blockquote><p>Separates a rule's result from its components.  See <a href="#Rules">Syntax of Grammar Rules</a>. 
  7071. </p></blockquote></div>
  7072.  
  7073. <div class="defun">
  7074. — Delimiter: <b>;</b><var><a name="index-g_t_003b-347"></a></var><br>
  7075. <blockquote><p>Terminates a rule.  See <a href="#Rules">Syntax of Grammar Rules</a>. 
  7076. </p></blockquote></div>
  7077.  
  7078. <div class="defun">
  7079. — Delimiter: <b>|</b><var><a name="index-g_t_007c-348"></a></var><br>
  7080. <blockquote><p>Separates alternate rules for the same result nonterminal. 
  7081. See <a href="#Rules">Syntax of Grammar Rules</a>. 
  7082. </p></blockquote></div>
  7083.  
  7084. <div class="node">
  7085. <p><hr>
  7086. <a name="Glossary"></a>
  7087. Next: <a rel="next" accesskey="n" href="#FAQ">FAQ</a>,
  7088. Previous: <a rel="previous" accesskey="p" href="#Table-of-Symbols">Table of Symbols</a>,
  7089. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  7090.  
  7091. </div>
  7092.  
  7093. <h2 class="appendix">Appendix B Glossary</h2>
  7094.  
  7095. <p><a name="index-glossary-349"></a>
  7096.      <dl>
  7097. <dt>Backus-Naur Form (<acronym>BNF</acronym>; also called “Backus Normal Form”)<dd>Formal method of specifying context-free grammars originally proposed
  7098. by John Backus, and slightly improved by Peter Naur in his 1960-01-02
  7099. committee document contributing to what became the Algol 60 report. 
  7100. See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.
  7101.  
  7102.      <br><dt>Context-free grammars<dd>Grammars specified as rules that can be applied regardless of context. 
  7103. Thus, if there is a rule which says that an integer can be used as an
  7104. expression, integers are allowed <em>anywhere</em> an expression is
  7105. permitted.  See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.
  7106.  
  7107.      <br><dt>Dynamic allocation<dd>Allocation of memory that occurs during execution, rather than at
  7108. compile time or on entry to a function.
  7109.  
  7110.      <br><dt>Empty string<dd>Analogous to the empty set in set theory, the empty string is a
  7111. character string of length zero.
  7112.  
  7113.      <br><dt>Finite-state stack machine<dd>A “machine” that has discrete states in which it is said to exist at
  7114. each instant in time.  As input to the machine is processed, the
  7115. machine moves from state to state as specified by the logic of the
  7116. machine.  In the case of the parser, the input is the language being
  7117. parsed, and the states correspond to various stages in the grammar
  7118. rules.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.
  7119.  
  7120.      <br><dt>Generalized <acronym>LR</acronym> (<acronym>GLR</acronym>)<dd>A parsing algorithm that can handle all context-free grammars, including those
  7121. that are not <acronym>LALR</acronym>(1).  It resolves situations that Bison's
  7122. usual <acronym>LALR</acronym>(1)
  7123. algorithm cannot by effectively splitting off multiple parsers, trying all
  7124. possible parsers, and discarding those that fail in the light of additional
  7125. right context.  See <a href="#Generalized-LR-Parsing">Generalized <acronym>LR</acronym> Parsing</a>.
  7126.  
  7127.      <br><dt>Grouping<dd>A language construct that is (in general) grammatically divisible;
  7128. for example, `expression' or `declaration' in C. 
  7129. See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.
  7130.  
  7131.      <br><dt>Infix operator<dd>An arithmetic operator that is placed between the operands on which it
  7132. performs some operation.
  7133.  
  7134.      <br><dt>Input stream<dd>A continuous flow of data between devices or programs.
  7135.  
  7136.      <br><dt>Language construct<dd>One of the typical usage schemas of the language.  For example, one of
  7137. the constructs of the C language is the <code>if</code> statement. 
  7138. See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.
  7139.  
  7140.      <br><dt>Left associativity<dd>Operators having left associativity are analyzed from left to right:
  7141. `<samp><span class="samp">a+b+c</span></samp>' first computes `<samp><span class="samp">a+b</span></samp>' and then combines with
  7142. `<samp><span class="samp">c</span></samp>'.  See <a href="#Precedence">Operator Precedence</a>.
  7143.  
  7144.      <br><dt>Left recursion<dd>A rule whose result symbol is also its first component symbol; for
  7145. example, `<samp><span class="samp">expseq1 : expseq1 ',' exp;</span></samp>'.  See <a href="#Recursion">Recursive Rules</a>.
  7146.  
  7147.      <br><dt>Left-to-right parsing<dd>Parsing a sentence of a language by analyzing it token by token from
  7148. left to right.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.
  7149.  
  7150.      <br><dt>Lexical analyzer (scanner)<dd>A function that reads an input stream and returns tokens one by one. 
  7151. See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>.
  7152.  
  7153.      <br><dt>Lexical tie-in<dd>A flag, set by actions in the grammar rules, which alters the way
  7154. tokens are parsed.  See <a href="#Lexical-Tie_002dins">Lexical Tie-ins</a>.
  7155.  
  7156.      <br><dt>Literal string token<dd>A token which consists of two or more fixed characters.  See <a href="#Symbols">Symbols</a>.
  7157.  
  7158.      <br><dt>Look-ahead token<dd>A token already read but not yet shifted.  See <a href="#Look_002dAhead">Look-Ahead Tokens</a>.
  7159.  
  7160.      <br><dt><acronym>LALR</acronym>(1)<dd>The class of context-free grammars that Bison (like most other parser
  7161. generators) can handle; a subset of <acronym>LR</acronym>(1).  See <a href="#Mystery-Conflicts">Mysterious Reduce/Reduce Conflicts</a>.
  7162.  
  7163.      <br><dt><acronym>LR</acronym>(1)<dd>The class of context-free grammars in which at most one token of
  7164. look-ahead is needed to disambiguate the parsing of any piece of input.
  7165.  
  7166.      <br><dt>Nonterminal symbol<dd>A grammar symbol standing for a grammatical construct that can
  7167. be expressed through rules in terms of smaller constructs; in other
  7168. words, a construct that is not a token.  See <a href="#Symbols">Symbols</a>.
  7169.  
  7170.      <br><dt>Parser<dd>A function that recognizes valid sentences of a language by analyzing
  7171. the syntax structure of a set of tokens passed to it from a lexical
  7172. analyzer.
  7173.  
  7174.      <br><dt>Postfix operator<dd>An arithmetic operator that is placed after the operands upon which it
  7175. performs some operation.
  7176.  
  7177.      <br><dt>Reduction<dd>Replacing a string of nonterminals and/or terminals with a single
  7178. nonterminal, according to a grammar rule.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.
  7179.  
  7180.      <br><dt>Reentrant<dd>A reentrant subprogram is a subprogram which can be in invoked any
  7181. number of times in parallel, without interference between the various
  7182. invocations.  See <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>.
  7183.  
  7184.      <br><dt>Reverse polish notation<dd>A language in which all operators are postfix operators.
  7185.  
  7186.      <br><dt>Right recursion<dd>A rule whose result symbol is also its last component symbol; for
  7187. example, `<samp><span class="samp">expseq1: exp ',' expseq1;</span></samp>'.  See <a href="#Recursion">Recursive Rules</a>.
  7188.  
  7189.      <br><dt>Semantics<dd>In computer languages, the semantics are specified by the actions
  7190. taken for each instance of the language, i.e., the meaning of
  7191. each statement.  See <a href="#Semantics">Defining Language Semantics</a>.
  7192.  
  7193.      <br><dt>Shift<dd>A parser is said to shift when it makes the choice of analyzing
  7194. further input from the stream rather than reducing immediately some
  7195. already-recognized rule.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.
  7196.  
  7197.      <br><dt>Single-character literal<dd>A single character that is recognized and interpreted as is. 
  7198. See <a href="#Grammar-in-Bison">From Formal Rules to Bison Input</a>.
  7199.  
  7200.      <br><dt>Start symbol<dd>The nonterminal symbol that stands for a complete valid utterance in
  7201. the language being parsed.  The start symbol is usually listed as the
  7202. first nonterminal symbol in a language specification. 
  7203. See <a href="#Start-Decl">The Start-Symbol</a>.
  7204.  
  7205.      <br><dt>Symbol table<dd>A data structure where symbol names and associated data are stored
  7206. during parsing to allow for recognition and use of existing
  7207. information in repeated uses of a symbol.  See <a href="#Multi_002dfunction-Calc">Multi-function Calc</a>.
  7208.  
  7209.      <br><dt>Syntax error<dd>An error encountered during parsing of an input stream due to invalid
  7210. syntax.  See <a href="#Error-Recovery">Error Recovery</a>.
  7211.  
  7212.      <br><dt>Token<dd>A basic, grammatically indivisible unit of a language.  The symbol
  7213. that describes a token in the grammar is a terminal symbol. 
  7214. The input of the Bison parser is a stream of tokens which comes from
  7215. the lexical analyzer.  See <a href="#Symbols">Symbols</a>.
  7216.  
  7217.      <br><dt>Terminal symbol<dd>A grammar symbol that has no rules in the grammar and therefore is
  7218. grammatically indivisible.  The piece of text it represents is a token. 
  7219. See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>. 
  7220. </dl>
  7221.  
  7222. <div class="node">
  7223. <p><hr>
  7224. <a name="Copying-This-Manual"></a>
  7225. Next: <a rel="next" accesskey="n" href="#Index">Index</a>,
  7226. Previous: <a rel="previous" accesskey="p" href="#FAQ">FAQ</a>,
  7227. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  7228.  
  7229. </div>
  7230.  
  7231. <h2 class="appendix">Appendix C Copying This Manual</h2>
  7232.  
  7233. <ul class="menu">
  7234. <li><a accesskey="1" href="#GNU-Free-Documentation-License">GNU Free Documentation License</a>:   License for copying this manual. 
  7235. </ul>
  7236.  
  7237. <div class="node">
  7238. <p><hr>
  7239. <a name="GNU-Free-Documentation-License"></a>
  7240. Up: <a rel="up" accesskey="u" href="#Copying-This-Manual">Copying This Manual</a>
  7241.  
  7242. </div>
  7243.  
  7244. <h3 class="appendixsec">C.1 GNU Free Documentation License</h3>
  7245.  
  7246. <p><a name="index-FDL_002c-GNU-Free-Documentation-License-350"></a><div align="center">Version 1.2, November 2002</div>
  7247.  
  7248. <pre class="display">     Copyright © 2000,2001,2002 Free Software Foundation, Inc.
  7249.      59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
  7250.      
  7251.      Everyone is permitted to copy and distribute verbatim copies
  7252.      of this license document, but changing it is not allowed.
  7253. </pre>
  7254.      <ol type=1 start=0>
  7255. <li>PREAMBLE
  7256.  
  7257.      <p>The purpose of this License is to make a manual, textbook, or other
  7258. functional and useful document <dfn>free</dfn> in the sense of freedom: to
  7259. assure everyone the effective freedom to copy and redistribute it,
  7260. with or without modifying it, either commercially or noncommercially. 
  7261. Secondarily, this License preserves for the author and publisher a way
  7262. to get credit for their work, while not being considered responsible
  7263. for modifications made by others.
  7264.  
  7265.      <p>This License is a kind of “copyleft”, which means that derivative
  7266. works of the document must themselves be free in the same sense.  It
  7267. complements the GNU General Public License, which is a copyleft
  7268. license designed for free software.
  7269.  
  7270.      <p>We have designed this License in order to use it for manuals for free
  7271. software, because free software needs free documentation: a free
  7272. program should come with manuals providing the same freedoms that the
  7273. software does.  But this License is not limited to software manuals;
  7274. it can be used for any textual work, regardless of subject matter or
  7275. whether it is published as a printed book.  We recommend this License
  7276. principally for works whose purpose is instruction or reference.
  7277.  
  7278.      <li>APPLICABILITY AND DEFINITIONS
  7279.  
  7280.      <p>This License applies to any manual or other work, in any medium, that
  7281. contains a notice placed by the copyright holder saying it can be
  7282. distributed under the terms of this License.  Such a notice grants a
  7283. world-wide, royalty-free license, unlimited in duration, to use that
  7284. work under the conditions stated herein.  The “Document”, below,
  7285. refers to any such manual or work.  Any member of the public is a
  7286. licensee, and is addressed as “you”.  You accept the license if you
  7287. copy, modify or distribute the work in a way requiring permission
  7288. under copyright law.
  7289.  
  7290.      <p>A “Modified Version” of the Document means any work containing the
  7291. Document or a portion of it, either copied verbatim, or with
  7292. modifications and/or translated into another language.
  7293.  
  7294.      <p>A “Secondary Section” is a named appendix or a front-matter section
  7295. of the Document that deals exclusively with the relationship of the
  7296. publishers or authors of the Document to the Document's overall
  7297. subject (or to related matters) and contains nothing that could fall
  7298. directly within that overall subject.  (Thus, if the Document is in
  7299. part a textbook of mathematics, a Secondary Section may not explain
  7300. any mathematics.)  The relationship could be a matter of historical
  7301. connection with the subject or with related matters, or of legal,
  7302. commercial, philosophical, ethical or political position regarding
  7303. them.
  7304.  
  7305.      <p>The “Invariant Sections” are certain Secondary Sections whose titles
  7306. are designated, as being those of Invariant Sections, in the notice
  7307. that says that the Document is released under this License.  If a
  7308. section does not fit the above definition of Secondary then it is not
  7309. allowed to be designated as Invariant.  The Document may contain zero
  7310. Invariant Sections.  If the Document does not identify any Invariant
  7311. Sections then there are none.
  7312.  
  7313.      <p>The “Cover Texts” are certain short passages of text that are listed,
  7314. as Front-Cover Texts or Back-Cover Texts, in the notice that says that
  7315. the Document is released under this License.  A Front-Cover Text may
  7316. be at most 5 words, and a Back-Cover Text may be at most 25 words.
  7317.  
  7318.      <p>A “Transparent” copy of the Document means a machine-readable copy,
  7319. represented in a format whose specification is available to the
  7320. general public, that is suitable for revising the document
  7321. straightforwardly with generic text editors or (for images composed of
  7322. pixels) generic paint programs or (for drawings) some widely available
  7323. drawing editor, and that is suitable for input to text formatters or
  7324. for automatic translation to a variety of formats suitable for input
  7325. to text formatters.  A copy made in an otherwise Transparent file
  7326. format whose markup, or absence of markup, has been arranged to thwart
  7327. or discourage subsequent modification by readers is not Transparent. 
  7328. An image format is not Transparent if used for any substantial amount
  7329. of text.  A copy that is not “Transparent” is called “Opaque”.
  7330.  
  7331.      <p>Examples of suitable formats for Transparent copies include plain
  7332. <span class="sc">ascii</span> without markup, Texinfo input format, LaTeX input
  7333. format, <acronym>SGML</acronym> or <acronym>XML</acronym> using a publicly available
  7334. <acronym>DTD</acronym>, and standard-conforming simple <acronym>HTML</acronym>,
  7335. PostScript or <acronym>PDF</acronym> designed for human modification.  Examples
  7336. of transparent image formats include <acronym>PNG</acronym>, <acronym>XCF</acronym> and
  7337. <acronym>JPG</acronym>.  Opaque formats include proprietary formats that can be
  7338. read and edited only by proprietary word processors, <acronym>SGML</acronym> or
  7339. <acronym>XML</acronym> for which the <acronym>DTD</acronym> and/or processing tools are
  7340. not generally available, and the machine-generated <acronym>HTML</acronym>,
  7341. PostScript or <acronym>PDF</acronym> produced by some word processors for
  7342. output purposes only.
  7343.  
  7344.      <p>The “Title Page” means, for a printed book, the title page itself,
  7345. plus such following pages as are needed to hold, legibly, the material
  7346. this License requires to appear in the title page.  For works in
  7347. formats which do not have any title page as such, “Title Page” means
  7348. the text near the most prominent appearance of the work's title,
  7349. preceding the beginning of the body of the text.
  7350.  
  7351.      <p>A section “Entitled XYZ” means a named subunit of the Document whose
  7352. title either is precisely XYZ or contains XYZ in parentheses following
  7353. text that translates XYZ in another language.  (Here XYZ stands for a
  7354. specific section name mentioned below, such as “Acknowledgements”,
  7355. “Dedications”, “Endorsements”, or “History”.)  To “Preserve the Title”
  7356. of such a section when you modify the Document means that it remains a
  7357. section “Entitled XYZ” according to this definition.
  7358.  
  7359.      <p>The Document may include Warranty Disclaimers next to the notice which
  7360. states that this License applies to the Document.  These Warranty
  7361. Disclaimers are considered to be included by reference in this
  7362. License, but only as regards disclaiming warranties: any other
  7363. implication that these Warranty Disclaimers may have is void and has
  7364. no effect on the meaning of this License.
  7365.  
  7366.      <li>VERBATIM COPYING
  7367.  
  7368.      <p>You may copy and distribute the Document in any medium, either
  7369. commercially or noncommercially, provided that this License, the
  7370. copyright notices, and the license notice saying this License applies
  7371. to the Document are reproduced in all copies, and that you add no other
  7372. conditions whatsoever to those of this License.  You may not use
  7373. technical measures to obstruct or control the reading or further
  7374. copying of the copies you make or distribute.  However, you may accept
  7375. compensation in exchange for copies.  If you distribute a large enough
  7376. number of copies you must also follow the conditions in section 3.
  7377.  
  7378.      <p>You may also lend copies, under the same conditions stated above, and
  7379. you may publicly display copies.
  7380.  
  7381.      <li>COPYING IN QUANTITY
  7382.  
  7383.      <p>If you publish printed copies (or copies in media that commonly have
  7384. printed covers) of the Document, numbering more than 100, and the
  7385. Document's license notice requires Cover Texts, you must enclose the
  7386. copies in covers that carry, clearly and legibly, all these Cover
  7387. Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
  7388. the back cover.  Both covers must also clearly and legibly identify
  7389. you as the publisher of these copies.  The front cover must present
  7390. the full title with all words of the title equally prominent and
  7391. visible.  You may add other material on the covers in addition. 
  7392. Copying with changes limited to the covers, as long as they preserve
  7393. the title of the Document and satisfy these conditions, can be treated
  7394. as verbatim copying in other respects.
  7395.  
  7396.      <p>If the required texts for either cover are too voluminous to fit
  7397. legibly, you should put the first ones listed (as many as fit
  7398. reasonably) on the actual cover, and continue the rest onto adjacent
  7399. pages.
  7400.  
  7401.      <p>If you publish or distribute Opaque copies of the Document numbering
  7402. more than 100, you must either include a machine-readable Transparent
  7403. copy along with each Opaque copy, or state in or with each Opaque copy
  7404. a computer-network location from which the general network-using
  7405. public has access to download using public-standard network protocols
  7406. a complete Transparent copy of the Document, free of added material. 
  7407. If you use the latter option, you must take reasonably prudent steps,
  7408. when you begin distribution of Opaque copies in quantity, to ensure
  7409. that this Transparent copy will remain thus accessible at the stated
  7410. location until at least one year after the last time you distribute an
  7411. Opaque copy (directly or through your agents or retailers) of that
  7412. edition to the public.
  7413.  
  7414.      <p>It is requested, but not required, that you contact the authors of the
  7415. Document well before redistributing any large number of copies, to give
  7416. them a chance to provide you with an updated version of the Document.
  7417.  
  7418.      <li>MODIFICATIONS
  7419.  
  7420.      <p>You may copy and distribute a Modified Version of the Document under
  7421. the conditions of sections 2 and 3 above, provided that you release
  7422. the Modified Version under precisely this License, with the Modified
  7423. Version filling the role of the Document, thus licensing distribution
  7424. and modification of the Modified Version to whoever possesses a copy
  7425. of it.  In addition, you must do these things in the Modified Version:
  7426.  
  7427.           <ol type=A start=1>
  7428. <li>Use in the Title Page (and on the covers, if any) a title distinct
  7429. from that of the Document, and from those of previous versions
  7430. (which should, if there were any, be listed in the History section
  7431. of the Document).  You may use the same title as a previous version
  7432. if the original publisher of that version gives permission.
  7433.  
  7434.           <li>List on the Title Page, as authors, one or more persons or entities
  7435. responsible for authorship of the modifications in the Modified
  7436. Version, together with at least five of the principal authors of the
  7437. Document (all of its principal authors, if it has fewer than five),
  7438. unless they release you from this requirement.
  7439.  
  7440.           <li>State on the Title page the name of the publisher of the
  7441. Modified Version, as the publisher.
  7442.  
  7443.           <li>Preserve all the copyright notices of the Document.
  7444.  
  7445.           <li>Add an appropriate copyright notice for your modifications
  7446. adjacent to the other copyright notices.
  7447.  
  7448.           <li>Include, immediately after the copyright notices, a license notice
  7449. giving the public permission to use the Modified Version under the
  7450. terms of this License, in the form shown in the Addendum below.
  7451.  
  7452.           <li>Preserve in that license notice the full lists of Invariant Sections
  7453. and required Cover Texts given in the Document's license notice.
  7454.  
  7455.           <li>Include an unaltered copy of this License.
  7456.  
  7457.           <li>Preserve the section Entitled “History”, Preserve its Title, and add
  7458. to it an item stating at least the title, year, new authors, and
  7459. publisher of the Modified Version as given on the Title Page.  If
  7460. there is no section Entitled “History” in the Document, create one
  7461. stating the title, year, authors, and publisher of the Document as
  7462. given on its Title Page, then add an item describing the Modified
  7463. Version as stated in the previous sentence.
  7464.  
  7465.           <li>Preserve the network location, if any, given in the Document for
  7466. public access to a Transparent copy of the Document, and likewise
  7467. the network locations given in the Document for previous versions
  7468. it was based on.  These may be placed in the “History” section. 
  7469. You may omit a network location for a work that was published at
  7470. least four years before the Document itself, or if the original
  7471. publisher of the version it refers to gives permission.
  7472.  
  7473.           <li>For any section Entitled “Acknowledgements” or “Dedications”, Preserve
  7474. the Title of the section, and preserve in the section all the
  7475. substance and tone of each of the contributor acknowledgements and/or
  7476. dedications given therein.
  7477.  
  7478.           <li>Preserve all the Invariant Sections of the Document,
  7479. unaltered in their text and in their titles.  Section numbers
  7480. or the equivalent are not considered part of the section titles.
  7481.  
  7482.           <li>Delete any section Entitled “Endorsements”.  Such a section
  7483. may not be included in the Modified Version.
  7484.  
  7485.           <li>Do not retitle any existing section to be Entitled “Endorsements” or
  7486. to conflict in title with any Invariant Section.
  7487.  
  7488.           <li>Preserve any Warranty Disclaimers.
  7489.           </ol>
  7490.  
  7491.      <p>If the Modified Version includes new front-matter sections or
  7492. appendices that qualify as Secondary Sections and contain no material
  7493. copied from the Document, you may at your option designate some or all
  7494. of these sections as invariant.  To do this, add their titles to the
  7495. list of Invariant Sections in the Modified Version's license notice. 
  7496. These titles must be distinct from any other section titles.
  7497.  
  7498.      <p>You may add a section Entitled “Endorsements”, provided it contains
  7499. nothing but endorsements of your Modified Version by various
  7500. parties—for example, statements of peer review or that the text has
  7501. been approved by an organization as the authoritative definition of a
  7502. standard.
  7503.  
  7504.      <p>You may add a passage of up to five words as a Front-Cover Text, and a
  7505. passage of up to 25 words as a Back-Cover Text, to the end of the list
  7506. of Cover Texts in the Modified Version.  Only one passage of
  7507. Front-Cover Text and one of Back-Cover Text may be added by (or
  7508. through arrangements made by) any one entity.  If the Document already
  7509. includes a cover text for the same cover, previously added by you or
  7510. by arrangement made by the same entity you are acting on behalf of,
  7511. you may not add another; but you may replace the old one, on explicit
  7512. permission from the previous publisher that added the old one.
  7513.  
  7514.      <p>The author(s) and publisher(s) of the Document do not by this License
  7515. give permission to use their names for publicity for or to assert or
  7516. imply endorsement of any Modified Version.
  7517.  
  7518.      <li>COMBINING DOCUMENTS
  7519.  
  7520.      <p>You may combine the Document with other documents released under this
  7521. License, under the terms defined in section 4 above for modified
  7522. versions, provided that you include in the combination all of the
  7523. Invariant Sections of all of the original documents, unmodified, and
  7524. list them all as Invariant Sections of your combined work in its
  7525. license notice, and that you preserve all their Warranty Disclaimers.
  7526.  
  7527.      <p>The combined work need only contain one copy of this License, and
  7528. multiple identical Invariant Sections may be replaced with a single
  7529. copy.  If there are multiple Invariant Sections with the same name but
  7530. different contents, make the title of each such section unique by
  7531. adding at the end of it, in parentheses, the name of the original
  7532. author or publisher of that section if known, or else a unique number. 
  7533. Make the same adjustment to the section titles in the list of
  7534. Invariant Sections in the license notice of the combined work.
  7535.  
  7536.      <p>In the combination, you must combine any sections Entitled “History”
  7537. in the various original documents, forming one section Entitled
  7538. “History”; likewise combine any sections Entitled “Acknowledgements”,
  7539. and any sections Entitled “Dedications”.  You must delete all
  7540. sections Entitled “Endorsements.”
  7541.  
  7542.      <li>COLLECTIONS OF DOCUMENTS
  7543.  
  7544.      <p>You may make a collection consisting of the Document and other documents
  7545. released under this License, and replace the individual copies of this
  7546. License in the various documents with a single copy that is included in
  7547. the collection, provided that you follow the rules of this License for
  7548. verbatim copying of each of the documents in all other respects.
  7549.  
  7550.      <p>You may extract a single document from such a collection, and distribute
  7551. it individually under this License, provided you insert a copy of this
  7552. License into the extracted document, and follow this License in all
  7553. other respects regarding verbatim copying of that document.
  7554.  
  7555.      <li>AGGREGATION WITH INDEPENDENT WORKS
  7556.  
  7557.      <p>A compilation of the Document or its derivatives with other separate
  7558. and independent documents or works, in or on a volume of a storage or
  7559. distribution medium, is called an “aggregate” if the copyright
  7560. resulting from the compilation is not used to limit the legal rights
  7561. of the compilation's users beyond what the individual works permit. 
  7562. When the Document is included an aggregate, this License does not
  7563. apply to the other works in the aggregate which are not themselves
  7564. derivative works of the Document.
  7565.  
  7566.      <p>If the Cover Text requirement of section 3 is applicable to these
  7567. copies of the Document, then if the Document is less than one half of
  7568. the entire aggregate, the Document's Cover Texts may be placed on
  7569. covers that bracket the Document within the aggregate, or the
  7570. electronic equivalent of covers if the Document is in electronic form. 
  7571. Otherwise they must appear on printed covers that bracket the whole
  7572. aggregate.
  7573.  
  7574.      <li>TRANSLATION
  7575.  
  7576.      <p>Translation is considered a kind of modification, so you may
  7577. distribute translations of the Document under the terms of section 4. 
  7578. Replacing Invariant Sections with translations requires special
  7579. permission from their copyright holders, but you may include
  7580. translations of some or all Invariant Sections in addition to the
  7581. original versions of these Invariant Sections.  You may include a
  7582. translation of this License, and all the license notices in the
  7583. Document, and any Warrany Disclaimers, provided that you also include
  7584. the original English version of this License and the original versions
  7585. of those notices and disclaimers.  In case of a disagreement between
  7586. the translation and the original version of this License or a notice
  7587. or disclaimer, the original version will prevail.
  7588.  
  7589.      <p>If a section in the Document is Entitled “Acknowledgements”,
  7590. “Dedications”, or “History”, the requirement (section 4) to Preserve
  7591. its Title (section 1) will typically require changing the actual
  7592. title.
  7593.  
  7594.      <li>TERMINATION
  7595.  
  7596.      <p>You may not copy, modify, sublicense, or distribute the Document except
  7597. as expressly provided for under this License.  Any other attempt to
  7598. copy, modify, sublicense or distribute the Document is void, and will
  7599. automatically terminate your rights under this License.  However,
  7600. parties who have received copies, or rights, from you under this
  7601. License will not have their licenses terminated so long as such
  7602. parties remain in full compliance.
  7603.  
  7604.      <li>FUTURE REVISIONS OF THIS LICENSE
  7605.  
  7606.      <p>The Free Software Foundation may publish new, revised versions
  7607. of the GNU Free Documentation License from time to time.  Such new
  7608. versions will be similar in spirit to the present version, but may
  7609. differ in detail to address new problems or concerns.  See
  7610. <a href="http://www.gnu.org/copyleft/">http://www.gnu.org/copyleft/</a>.
  7611.  
  7612.      <p>Each version of the License is given a distinguishing version number. 
  7613. If the Document specifies that a particular numbered version of this
  7614. License “or any later version” applies to it, you have the option of
  7615. following the terms and conditions either of that specified version or
  7616. of any later version that has been published (not as a draft) by the
  7617. Free Software Foundation.  If the Document does not specify a version
  7618. number of this License, you may choose any version ever published (not
  7619. as a draft) by the Free Software Foundation.
  7620.         </ol>
  7621.  
  7622. <h4 class="appendixsubsec">C.1.1 ADDENDUM: How to use this License for your documents</h4>
  7623.  
  7624. <p>To use this License in a document you have written, include a copy of
  7625. the License in the document and put the following copyright and
  7626. license notices just after the title page:
  7627.  
  7628. <pre class="smallexample">       Copyright (C)  <var>year</var>  <var>your name</var>.
  7629.        Permission is granted to copy, distribute and/or modify this document
  7630.        under the terms of the GNU Free Documentation License, Version 1.2
  7631.        or any later version published by the Free Software Foundation;
  7632.        with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
  7633.        A copy of the license is included in the section entitled ``GNU
  7634.        Free Documentation License''.
  7635. </pre>
  7636.    <p>If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
  7637. replace the “with...Texts.” line with this:
  7638.  
  7639. <pre class="smallexample">         with the Invariant Sections being <var>list their titles</var>, with
  7640.          the Front-Cover Texts being <var>list</var>, and with the Back-Cover Texts
  7641.          being <var>list</var>.
  7642. </pre>
  7643.    <p>If you have Invariant Sections without Cover Texts, or some other
  7644. combination of the three, merge those two alternatives to suit the
  7645. situation.
  7646.  
  7647.    <p>If your document contains nontrivial examples of program code, we
  7648. recommend releasing these examples in parallel under your choice of
  7649. free software license, such as the GNU General Public License,
  7650. to permit their use in free software.
  7651.  
  7652. <!-- Local Variables: -->
  7653. <!-- ispell-local-pdict: "ispell-dict" -->
  7654. <!-- End: -->
  7655. <div class="node">
  7656. <p><hr>
  7657. <a name="Index"></a>
  7658. Previous: <a rel="previous" accesskey="p" href="#Copying-This-Manual">Copying This Manual</a>,
  7659. Up: <a rel="up" accesskey="u" href="#Top">Top</a>
  7660.  
  7661. </div>
  7662.  
  7663. <h2 class="unnumbered">Index</h2>
  7664.  
  7665. <ul class="index-cp" compact>
  7666. <li><a href="#index-action-103">action</a>: <a href="#Actions">Actions</a></li>
  7667. <li><a href="#index-action-data-types-107">action data types</a>: <a href="#Action-Types">Action Types</a></li>
  7668. <li><a href="#index-action-features-summary-196">action features summary</a>: <a href="#Action-Features">Action Features</a></li>
  7669. <li><a href="#index-actions-in-mid_002drule-109">actions in mid-rule</a>: <a href="#Mid_002dRule-Actions">Mid-Rule Actions</a></li>
  7670. <li><a href="#index-actions_002c-location-117">actions, location</a>: <a href="#Actions-and-Locations">Actions and Locations</a></li>
  7671. <li><a href="#index-actions_002c-semantic-23">actions, semantic</a>: <a href="#Semantic-Actions">Semantic Actions</a></li>
  7672. <li><a href="#index-additional-C-code-section-76">additional C code section</a>: <a href="#Epilogue">Epilogue</a></li>
  7673. <li><a href="#index-algorithm-of-parser-218">algorithm of parser</a>: <a href="#Algorithm">Algorithm</a></li>
  7674. <li><a href="#index-ambiguous-grammars-249">ambiguous grammars</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
  7675. <li><a href="#index-ambiguous-grammars-10">ambiguous grammars</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7676. <li><a href="#index-associativity-231">associativity</a>: <a href="#Why-Precedence">Why Precedence</a></li>
  7677. <li><a href="#index-Backus_002dNaur-form-5">Backus-Naur form</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7678. <li><a href="#index-Bison-declaration-summary-152">Bison declaration summary</a>: <a href="#Decl-Summary">Decl Summary</a></li>
  7679. <li><a href="#index-Bison-declarations-122">Bison declarations</a>: <a href="#Declarations">Declarations</a></li>
  7680. <li><a href="#index-Bison-declarations-_0028introduction_0029-72">Bison declarations (introduction)</a>: <a href="#Bison-Declarations">Bison Declarations</a></li>
  7681. <li><a href="#index-Bison-grammar-17">Bison grammar</a>: <a href="#Grammar-in-Bison">Grammar in Bison</a></li>
  7682. <li><a href="#index-Bison-invocation-284">Bison invocation</a>: <a href="#Invocation">Invocation</a></li>
  7683. <li><a href="#index-Bison-parser-34">Bison parser</a>: <a href="#Bison-Parser">Bison Parser</a></li>
  7684. <li><a href="#index-Bison-parser-algorithm-217">Bison parser algorithm</a>: <a href="#Algorithm">Algorithm</a></li>
  7685. <li><a href="#index-Bison-symbols_002c-table-of-288">Bison symbols, table of</a>: <a href="#Table-of-Symbols">Table of Symbols</a></li>
  7686. <li><a href="#index-Bison-utility-35">Bison utility</a>: <a href="#Bison-Parser">Bison Parser</a></li>
  7687. <li><a href="#index-g_t_0040acronym_007bBNF_007d-4"><acronym>BNF</acronym></a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7688. <li><a href="#index-C-code_002c-section-for-additional-78">C code, section for additional</a>: <a href="#Epilogue">Epilogue</a></li>
  7689. <li><a href="#index-C_002dlanguage-interface-176">C-language interface</a>: <a href="#Interface">Interface</a></li>
  7690. <li><a href="#index-g_t_0040code_007bcalc_007d-58"><code>calc</code></a>: <a href="#Infix-Calc">Infix Calc</a></li>
  7691. <li><a href="#index-calculator_002c-infix-notation-59">calculator, infix notation</a>: <a href="#Infix-Calc">Infix Calc</a></li>
  7692. <li><a href="#index-calculator_002c-location-tracking-63">calculator, location tracking</a>: <a href="#Location-Tracking-Calc">Location Tracking Calc</a></li>
  7693. <li><a href="#index-calculator_002c-multi_002dfunction-66">calculator, multi-function</a>: <a href="#Multi_002dfunction-Calc">Multi-function Calc</a></li>
  7694. <li><a href="#index-calculator_002c-simple-49">calculator, simple</a>: <a href="#RPN-Calc">RPN Calc</a></li>
  7695. <li><a href="#index-character-token-83">character token</a>: <a href="#Symbols">Symbols</a></li>
  7696. <li><a href="#index-compiling-the-parser-56">compiling the parser</a>: <a href="#Rpcalc-Compile">Rpcalc Compile</a></li>
  7697. <li><a href="#index-conflicts-225">conflicts</a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
  7698. <li><a href="#index-conflicts-27">conflicts</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
  7699. <li><a href="#index-conflicts_002c-reduce_002freduce-244">conflicts, reduce/reduce</a>: <a href="#Reduce_002fReduce">Reduce/Reduce</a></li>
  7700. <li><a href="#index-conflicts_002c-suppressing-warnings-of-143">conflicts, suppressing warnings of</a>: <a href="#Expect-Decl">Expect Decl</a></li>
  7701. <li><a href="#index-context_002ddependent-precedence-235">context-dependent precedence</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
  7702. <li><a href="#index-context_002dfree-grammar-2">context-free grammar</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7703. <li><a href="#index-controlling-function-52">controlling function</a>: <a href="#Rpcalc-Main">Rpcalc Main</a></li>
  7704. <li><a href="#index-core_002c-item-set-273">core, item set</a>: <a href="#Understanding">Understanding</a></li>
  7705. <li><a href="#index-dangling-_0040code_007belse_007d-227">dangling <code>else</code></a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
  7706. <li><a href="#index-data-type-of-locations-114">data type of locations</a>: <a href="#Location-Type">Location Type</a></li>
  7707. <li><a href="#index-data-types-in-actions-108">data types in actions</a>: <a href="#Action-Types">Action Types</a></li>
  7708. <li><a href="#index-data-types-of-semantic-values-101">data types of semantic values</a>: <a href="#Value-Type">Value Type</a></li>
  7709. <li><a href="#index-debugging-278">debugging</a>: <a href="#Tracing">Tracing</a></li>
  7710. <li><a href="#index-declaration-summary-153">declaration summary</a>: <a href="#Decl-Summary">Decl Summary</a></li>
  7711. <li><a href="#index-declarations-71">declarations</a>: <a href="#Prologue">Prologue</a></li>
  7712. <li><a href="#index-declarations-section-69">declarations section</a>: <a href="#Prologue">Prologue</a></li>
  7713. <li><a href="#index-declarations_002c-Bison-121">declarations, Bison</a>: <a href="#Declarations">Declarations</a></li>
  7714. <li><a href="#index-declarations_002c-Bison-_0028introduction_0029-73">declarations, Bison (introduction)</a>: <a href="#Bison-Declarations">Bison Declarations</a></li>
  7715. <li><a href="#index-declaring-literal-string-tokens-125">declaring literal string tokens</a>: <a href="#Token-Decl">Token Decl</a></li>
  7716. <li><a href="#index-declaring-operator-precedence-128">declaring operator precedence</a>: <a href="#Precedence-Decl">Precedence Decl</a></li>
  7717. <li><a href="#index-declaring-the-start-symbol-145">declaring the start symbol</a>: <a href="#Start-Decl">Start Decl</a></li>
  7718. <li><a href="#index-declaring-token-type-names-123">declaring token type names</a>: <a href="#Token-Decl">Token Decl</a></li>
  7719. <li><a href="#index-declaring-value-types-130">declaring value types</a>: <a href="#Union-Decl">Union Decl</a></li>
  7720. <li><a href="#index-declaring-value-types_002c-nonterminals-133">declaring value types, nonterminals</a>: <a href="#Type-Decl">Type Decl</a></li>
  7721. <li><a href="#index-default-action-106">default action</a>: <a href="#Actions">Actions</a></li>
  7722. <li><a href="#index-default-data-type-102">default data type</a>: <a href="#Value-Type">Value Type</a></li>
  7723. <li><a href="#index-default-location-type-115">default location type</a>: <a href="#Location-Type">Location Type</a></li>
  7724. <li><a href="#index-default-stack-limit-255">default stack limit</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
  7725. <li><a href="#index-default-start-symbol-147">default start symbol</a>: <a href="#Start-Decl">Start Decl</a></li>
  7726. <li><a href="#index-defining-language-semantics-97">defining language semantics</a>: <a href="#Semantics">Semantics</a></li>
  7727. <li><a href="#index-g_t_0040code_007belse_007d_002c-dangling-228"><code>else</code>, dangling</a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
  7728. <li><a href="#index-epilogue-77">epilogue</a>: <a href="#Epilogue">Epilogue</a></li>
  7729. <li><a href="#index-error-recovery-257">error recovery</a>: <a href="#Error-Recovery">Error Recovery</a></li>
  7730. <li><a href="#index-error-recovery_002c-simple-60">error recovery, simple</a>: <a href="#Simple-Error-Recovery">Simple Error Recovery</a></li>
  7731. <li><a href="#index-error-reporting-function-189">error reporting function</a>: <a href="#Error-Reporting">Error Reporting</a></li>
  7732. <li><a href="#index-error-reporting-routine-54">error reporting routine</a>: <a href="#Rpcalc-Error">Rpcalc Error</a></li>
  7733. <li><a href="#index-examples_002c-simple-45">examples, simple</a>: <a href="#Examples">Examples</a></li>
  7734. <li><a href="#index-exercises-68">exercises</a>: <a href="#Exercises">Exercises</a></li>
  7735. <li><a href="#index-FDL_002c-GNU-Free-Documentation-License-350">FDL, GNU Free Documentation License</a>: <a href="#GNU-Free-Documentation-License">GNU Free Documentation License</a></li>
  7736. <li><a href="#index-file-format-41">file format</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
  7737. <li><a href="#index-finite_002dstate-machine-240">finite-state machine</a>: <a href="#Parser-States">Parser States</a></li>
  7738. <li><a href="#index-formal-grammar-19">formal grammar</a>: <a href="#Grammar-in-Bison">Grammar in Bison</a></li>
  7739. <li><a href="#index-format-of-grammar-file-42">format of grammar file</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
  7740. <li><a href="#index-freeing-discarded-symbols-136">freeing discarded symbols</a>: <a href="#Destructor-Decl">Destructor Decl</a></li>
  7741. <li><a href="#index-frequently-asked-questions-286">frequently asked questions</a>: <a href="#FAQ">FAQ</a></li>
  7742. <li><a href="#index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-248">generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) parsing</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
  7743. <li><a href="#index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-25">generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) parsing</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
  7744. <li><a href="#index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-9">generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) parsing</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7745. <li><a href="#index-glossary-349">glossary</a>: <a href="#Glossary">Glossary</a></li>
  7746. <li><a href="#index-g_t_0040acronym_007bGLR_007d-parsers-and-_0040code_007binline_007d-30"><acronym>GLR</acronym> parsers and <code>inline</code></a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
  7747. <li><a href="#index-g_t_0040acronym_007bGLR_007d-parsing-247"><acronym>GLR</acronym> parsing</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
  7748. <li><a href="#index-g_t_0040acronym_007bGLR_007d-parsing-24"><acronym>GLR</acronym> parsing</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
  7749. <li><a href="#index-g_t_0040acronym_007bGLR_007d-parsing-8"><acronym>GLR</acronym> parsing</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7750. <li><a href="#index-grammar-file-40">grammar file</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
  7751. <li><a href="#index-grammar-rule-syntax-90">grammar rule syntax</a>: <a href="#Rules">Rules</a></li>
  7752. <li><a href="#index-grammar-rules-section-74">grammar rules section</a>: <a href="#Grammar-Rules">Grammar Rules</a></li>
  7753. <li><a href="#index-grammar_002c-Bison-18">grammar, Bison</a>: <a href="#Grammar-in-Bison">Grammar in Bison</a></li>
  7754. <li><a href="#index-grammar_002c-context_002dfree-3">grammar, context-free</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7755. <li><a href="#index-grouping_002c-syntactic-15">grouping, syntactic</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7756. <li><a href="#index-g_t_0040code_007bincline_007d-29"><code>incline</code></a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
  7757. <li><a href="#index-infix-notation-calculator-57">infix notation calculator</a>: <a href="#Infix-Calc">Infix Calc</a></li>
  7758. <li><a href="#index-interface-177">interface</a>: <a href="#Interface">Interface</a></li>
  7759. <li><a href="#index-introduction-1">introduction</a>: <a href="#Introduction">Introduction</a></li>
  7760. <li><a href="#index-invoking-Bison-283">invoking Bison</a>: <a href="#Invocation">Invocation</a></li>
  7761. <li><a href="#index-item-270">item</a>: <a href="#Understanding">Understanding</a></li>
  7762. <li><a href="#index-item-set-core-274">item set core</a>: <a href="#Understanding">Understanding</a></li>
  7763. <li><a href="#index-kernel_002c-item-set-275">kernel, item set</a>: <a href="#Understanding">Understanding</a></li>
  7764. <li><a href="#index-g_t_0040acronym_007bLALR_007d_00281_0029-246"><acronym>LALR</acronym>(1)</a>: <a href="#Mystery-Conflicts">Mystery Conflicts</a></li>
  7765. <li><a href="#index-g_t_0040acronym_007bLALR_007d_00281_0029-grammars-6"><acronym>LALR</acronym>(1) grammars</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7766. <li><a href="#index-language-semantics_002c-defining-98">language semantics, defining</a>: <a href="#Semantics">Semantics</a></li>
  7767. <li><a href="#index-layout-of-Bison-grammar-43">layout of Bison grammar</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
  7768. <li><a href="#index-left-recursion-94">left recursion</a>: <a href="#Recursion">Recursion</a></li>
  7769. <li><a href="#index-lexical-analyzer-185">lexical analyzer</a>: <a href="#Lexical">Lexical</a></li>
  7770. <li><a href="#index-lexical-analyzer_002c-purpose-36">lexical analyzer, purpose</a>: <a href="#Bison-Parser">Bison Parser</a></li>
  7771. <li><a href="#index-lexical-analyzer_002c-writing-51">lexical analyzer, writing</a>: <a href="#Rpcalc-Lexer">Rpcalc Lexer</a></li>
  7772. <li><a href="#index-lexical-tie_002din-263">lexical tie-in</a>: <a href="#Lexical-Tie_002dins">Lexical Tie-ins</a></li>
  7773. <li><a href="#index-literal-string-token-87">literal string token</a>: <a href="#Symbols">Symbols</a></li>
  7774. <li><a href="#index-literal-token-84">literal token</a>: <a href="#Symbols">Symbols</a></li>
  7775. <li><a href="#index-location-111">location</a>: <a href="#Locations">Locations</a></li>
  7776. <li><a href="#index-location-31">location</a>: <a href="#Locations-Overview">Locations Overview</a></li>
  7777. <li><a href="#index-location-actions-116">location actions</a>: <a href="#Actions-and-Locations">Actions and Locations</a></li>
  7778. <li><a href="#index-location-tracking-calculator-61">location tracking calculator</a>: <a href="#Location-Tracking-Calc">Location Tracking Calc</a></li>
  7779. <li><a href="#index-look_002dahead-token-223">look-ahead token</a>: <a href="#Look_002dAhead">Look-Ahead</a></li>
  7780. <li><a href="#index-g_t_0040acronym_007bLR_007d_00281_0029-245"><acronym>LR</acronym>(1)</a>: <a href="#Mystery-Conflicts">Mystery Conflicts</a></li>
  7781. <li><a href="#index-g_t_0040acronym_007bLR_007d_00281_0029-grammars-7"><acronym>LR</acronym>(1) grammars</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7782. <li><a href="#index-g_t_0040code_007bltcalc_007d-62"><code>ltcalc</code></a>: <a href="#Location-Tracking-Calc">Location Tracking Calc</a></li>
  7783. <li><a href="#index-main-function-in-simple-example-53">main function in simple example</a>: <a href="#Rpcalc-Main">Rpcalc Main</a></li>
  7784. <li><a href="#index-g_t_0040code_007bmfcalc_007d-65"><code>mfcalc</code></a>: <a href="#Multi_002dfunction-Calc">Multi-function Calc</a></li>
  7785. <li><a href="#index-mid_002drule-actions-110">mid-rule actions</a>: <a href="#Mid_002dRule-Actions">Mid-Rule Actions</a></li>
  7786. <li><a href="#index-multi_002dfunction-calculator-64">multi-function calculator</a>: <a href="#Multi_002dfunction-Calc">Multi-function Calc</a></li>
  7787. <li><a href="#index-multicharacter-literal-88">multicharacter literal</a>: <a href="#Symbols">Symbols</a></li>
  7788. <li><a href="#index-mutual-recursion-96">mutual recursion</a>: <a href="#Recursion">Recursion</a></li>
  7789. <li><a href="#index-non_002ddeterministic-parsing-250">non-deterministic parsing</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
  7790. <li><a href="#index-non_002ddeterministic-parsing-11">non-deterministic parsing</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7791. <li><a href="#index-nonterminal-symbol-79">nonterminal symbol</a>: <a href="#Symbols">Symbols</a></li>
  7792. <li><a href="#index-nonterminal_002c-useless-266">nonterminal, useless</a>: <a href="#Understanding">Understanding</a></li>
  7793. <li><a href="#index-operator-precedence-229">operator precedence</a>: <a href="#Precedence">Precedence</a></li>
  7794. <li><a href="#index-operator-precedence_002c-declaring-129">operator precedence, declaring</a>: <a href="#Precedence-Decl">Precedence Decl</a></li>
  7795. <li><a href="#index-options-for-invoking-Bison-285">options for invoking Bison</a>: <a href="#Invocation">Invocation</a></li>
  7796. <li><a href="#index-overflow-of-parser-stack-253">overflow of parser stack</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
  7797. <li><a href="#index-parse-error-191">parse error</a>: <a href="#Error-Reporting">Error Reporting</a></li>
  7798. <li><a href="#index-parser-37">parser</a>: <a href="#Bison-Parser">Bison Parser</a></li>
  7799. <li><a href="#index-parser-stack-221">parser stack</a>: <a href="#Algorithm">Algorithm</a></li>
  7800. <li><a href="#index-parser-stack-overflow-252">parser stack overflow</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
  7801. <li><a href="#index-parser-state-241">parser state</a>: <a href="#Parser-States">Parser States</a></li>
  7802. <li><a href="#index-pointed-rule-271">pointed rule</a>: <a href="#Understanding">Understanding</a></li>
  7803. <li><a href="#index-polish-notation-calculator-47">polish notation calculator</a>: <a href="#RPN-Calc">RPN Calc</a></li>
  7804. <li><a href="#index-position_002c-textual-113">position, textual</a>: <a href="#Locations">Locations</a></li>
  7805. <li><a href="#index-position_002c-textual-33">position, textual</a>: <a href="#Locations-Overview">Locations Overview</a></li>
  7806. <li><a href="#index-precedence-declarations-127">precedence declarations</a>: <a href="#Precedence-Decl">Precedence Decl</a></li>
  7807. <li><a href="#index-precedence-of-operators-230">precedence of operators</a>: <a href="#Precedence">Precedence</a></li>
  7808. <li><a href="#index-precedence_002c-context_002ddependent-237">precedence, context-dependent</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
  7809. <li><a href="#index-precedence_002c-unary-operator-238">precedence, unary operator</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
  7810. <li><a href="#index-preventing-warnings-about-conflicts-141">preventing warnings about conflicts</a>: <a href="#Expect-Decl">Expect Decl</a></li>
  7811. <li><a href="#index-Prologue-70">Prologue</a>: <a href="#Prologue">Prologue</a></li>
  7812. <li><a href="#index-pure-parser-150">pure parser</a>: <a href="#Pure-Decl">Pure Decl</a></li>
  7813. <li><a href="#index-questions-287">questions</a>: <a href="#FAQ">FAQ</a></li>
  7814. <li><a href="#index-recovery-from-errors-258">recovery from errors</a>: <a href="#Error-Recovery">Error Recovery</a></li>
  7815. <li><a href="#index-recursive-rule-93">recursive rule</a>: <a href="#Recursion">Recursion</a></li>
  7816. <li><a href="#index-reduce_002freduce-conflict-243">reduce/reduce conflict</a>: <a href="#Reduce_002fReduce">Reduce/Reduce</a></li>
  7817. <li><a href="#index-reduction-220">reduction</a>: <a href="#Algorithm">Algorithm</a></li>
  7818. <li><a href="#index-reentrant-parser-149">reentrant parser</a>: <a href="#Pure-Decl">Pure Decl</a></li>
  7819. <li><a href="#index-reverse-polish-notation-46">reverse polish notation</a>: <a href="#RPN-Calc">RPN Calc</a></li>
  7820. <li><a href="#index-right-recursion-95">right recursion</a>: <a href="#Recursion">Recursion</a></li>
  7821. <li><a href="#index-g_t_0040code_007brpcalc_007d-48"><code>rpcalc</code></a>: <a href="#RPN-Calc">RPN Calc</a></li>
  7822. <li><a href="#index-rule-syntax-89">rule syntax</a>: <a href="#Rules">Rules</a></li>
  7823. <li><a href="#index-rule_002c-pointed-272">rule, pointed</a>: <a href="#Understanding">Understanding</a></li>
  7824. <li><a href="#index-rule_002c-useless-268">rule, useless</a>: <a href="#Understanding">Understanding</a></li>
  7825. <li><a href="#index-rules-section-for-grammar-75">rules section for grammar</a>: <a href="#Grammar-Rules">Grammar Rules</a></li>
  7826. <li><a href="#index-running-Bison-_0028introduction_0029-55">running Bison (introduction)</a>: <a href="#Rpcalc-Gen">Rpcalc Gen</a></li>
  7827. <li><a href="#index-semantic-actions-22">semantic actions</a>: <a href="#Semantic-Actions">Semantic Actions</a></li>
  7828. <li><a href="#index-semantic-value-20">semantic value</a>: <a href="#Semantic-Values">Semantic Values</a></li>
  7829. <li><a href="#index-semantic-value-type-99">semantic value type</a>: <a href="#Value-Type">Value Type</a></li>
  7830. <li><a href="#index-shift_002freduce-conflicts-226">shift/reduce conflicts</a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
  7831. <li><a href="#index-shift_002freduce-conflicts-28">shift/reduce conflicts</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
  7832. <li><a href="#index-shifting-219">shifting</a>: <a href="#Algorithm">Algorithm</a></li>
  7833. <li><a href="#index-simple-examples-44">simple examples</a>: <a href="#Examples">Examples</a></li>
  7834. <li><a href="#index-single_002dcharacter-literal-85">single-character literal</a>: <a href="#Symbols">Symbols</a></li>
  7835. <li><a href="#index-stack-overflow-251">stack overflow</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
  7836. <li><a href="#index-stack_002c-parser-222">stack, parser</a>: <a href="#Algorithm">Algorithm</a></li>
  7837. <li><a href="#index-stages-in-using-Bison-38">stages in using Bison</a>: <a href="#Stages">Stages</a></li>
  7838. <li><a href="#index-start-symbol-16">start symbol</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7839. <li><a href="#index-start-symbol_002c-declaring-146">start symbol, declaring</a>: <a href="#Start-Decl">Start Decl</a></li>
  7840. <li><a href="#index-state-_0028of-parser_0029-242">state (of parser)</a>: <a href="#Parser-States">Parser States</a></li>
  7841. <li><a href="#index-string-token-86">string token</a>: <a href="#Symbols">Symbols</a></li>
  7842. <li><a href="#index-summary_002c-action-features-195">summary, action features</a>: <a href="#Action-Features">Action Features</a></li>
  7843. <li><a href="#index-summary_002c-Bison-declaration-154">summary, Bison declaration</a>: <a href="#Decl-Summary">Decl Summary</a></li>
  7844. <li><a href="#index-suppressing-conflict-warnings-140">suppressing conflict warnings</a>: <a href="#Expect-Decl">Expect Decl</a></li>
  7845. <li><a href="#index-symbol-82">symbol</a>: <a href="#Symbols">Symbols</a></li>
  7846. <li><a href="#index-symbol-table-example-67">symbol table example</a>: <a href="#Mfcalc-Symtab">Mfcalc Symtab</a></li>
  7847. <li><a href="#index-symbols-_0028abstract_0029-12">symbols (abstract)</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7848. <li><a href="#index-symbols-in-Bison_002c-table-of-289">symbols in Bison, table of</a>: <a href="#Table-of-Symbols">Table of Symbols</a></li>
  7849. <li><a href="#index-syntactic-grouping-14">syntactic grouping</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7850. <li><a href="#index-syntax-error-192">syntax error</a>: <a href="#Error-Reporting">Error Reporting</a></li>
  7851. <li><a href="#index-syntax-of-grammar-rules-91">syntax of grammar rules</a>: <a href="#Rules">Rules</a></li>
  7852. <li><a href="#index-terminal-symbol-80">terminal symbol</a>: <a href="#Symbols">Symbols</a></li>
  7853. <li><a href="#index-textual-position-112">textual position</a>: <a href="#Locations">Locations</a></li>
  7854. <li><a href="#index-textual-position-32">textual position</a>: <a href="#Locations-Overview">Locations Overview</a></li>
  7855. <li><a href="#index-token-13">token</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
  7856. <li><a href="#index-token-type-81">token type</a>: <a href="#Symbols">Symbols</a></li>
  7857. <li><a href="#index-token-type-names_002c-declaring-124">token type names, declaring</a>: <a href="#Token-Decl">Token Decl</a></li>
  7858. <li><a href="#index-token_002c-useless-264">token, useless</a>: <a href="#Understanding">Understanding</a></li>
  7859. <li><a href="#index-tracing-the-parser-279">tracing the parser</a>: <a href="#Tracing">Tracing</a></li>
  7860. <li><a href="#index-unary-operator-precedence-236">unary operator precedence</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
  7861. <li><a href="#index-useless-nonterminal-267">useless nonterminal</a>: <a href="#Understanding">Understanding</a></li>
  7862. <li><a href="#index-useless-rule-269">useless rule</a>: <a href="#Understanding">Understanding</a></li>
  7863. <li><a href="#index-useless-token-265">useless token</a>: <a href="#Understanding">Understanding</a></li>
  7864. <li><a href="#index-using-Bison-39">using Bison</a>: <a href="#Stages">Stages</a></li>
  7865. <li><a href="#index-value-type_002c-semantic-100">value type, semantic</a>: <a href="#Value-Type">Value Type</a></li>
  7866. <li><a href="#index-value-types_002c-declaring-131">value types, declaring</a>: <a href="#Union-Decl">Union Decl</a></li>
  7867. <li><a href="#index-value-types_002c-nonterminals_002c-declaring-134">value types, nonterminals, declaring</a>: <a href="#Type-Decl">Type Decl</a></li>
  7868. <li><a href="#index-value_002c-semantic-21">value, semantic</a>: <a href="#Semantic-Values">Semantic Values</a></li>
  7869. <li><a href="#index-warnings_002c-preventing-142">warnings, preventing</a>: <a href="#Expect-Decl">Expect Decl</a></li>
  7870. <li><a href="#index-writing-a-lexical-analyzer-50">writing a lexical analyzer</a>: <a href="#Rpcalc-Lexer">Rpcalc Lexer</a></li>
  7871.    </ul></body></html>
  7872.  
  7873.