home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 4 / FreshFish_May-June1994.bin / bbs / gnu / bison-1.22-src.lha / src / amiga / bison-1.22 / bison.info-3 < prev    next >
Encoding:
GNU Info File  |  1993-06-27  |  49.9 KB  |  1,313 lines

  1. This is Info file bison.info, produced by Makeinfo-1.54 from the input
  2. file /home/gd2/gnu/bison/bison.texinfo.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 1989, 1990, 1991, 1992 Free Software Foundation,
  7. Inc.
  8.  
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.  
  13.    Permission is granted to copy and distribute modified versions of
  14. this manual under the conditions for verbatim copying, provided also
  15. that the sections entitled "GNU General Public License" and "Conditions
  16. for Using Bison" are included exactly as in the original, and provided
  17. that the entire resulting derived work is distributed under the terms
  18. of a permission notice identical to this one.
  19.  
  20.    Permission is granted to copy and distribute translations of this
  21. manual into another language, under the above conditions for modified
  22. versions, except that the sections entitled "GNU General Public
  23. License", "Conditions for Using Bison" and this permission notice may be
  24. included in translations approved by the Free Software Foundation
  25. instead of in the original English.
  26.  
  27. 
  28. File: bison.info,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  29.  
  30. Actions in Mid-Rule
  31. -------------------
  32.  
  33.    Occasionally it is useful to put an action in the middle of a rule.
  34. These actions are written just like usual end-of-rule actions, but they
  35. are executed before the parser even recognizes the following components.
  36.  
  37.    A mid-rule action may refer to the components preceding it using
  38. `$N', but it may not refer to subsequent components because it is run
  39. before they are parsed.
  40.  
  41.    The mid-rule action itself counts as one of the components of the
  42. rule.  This makes a difference when there is another action later in
  43. the same rule (and usually there is another at the end): you have to
  44. count the actions along with the symbols when working out which number
  45. N to use in `$N'.
  46.  
  47.    The mid-rule action can also have a semantic value.  The action can
  48. set its value with an assignment to `$$', and actions later in the rule
  49. can refer to the value using `$N'.  Since there is no symbol to name
  50. the action, there is no way to declare a data type for the value in
  51. advance, so you must use the `$<...>' construct to specify a data type
  52. each time you refer to this value.
  53.  
  54.    There is no way to set the value of the entire rule with a mid-rule
  55. action, because assignments to `$$' do not have that effect.  The only
  56. way to set the value for the entire rule is with an ordinary action at
  57. the end of the rule.
  58.  
  59.    Here is an example from a hypothetical compiler, handling a `let'
  60. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  61. create a variable named VARIABLE temporarily for the duration of
  62. STATEMENT.  To parse this construct, we must put VARIABLE into the
  63. symbol table while STATEMENT is parsed, then remove it afterward.  Here
  64. is how it is done:
  65.  
  66.      stmt:   LET '(' var ')'
  67.                      { $<context>$ = push_context ();
  68.                        declare_variable ($3); }
  69.              stmt    { $$ = $6;
  70.                        pop_context ($<context>5); }
  71.  
  72. As soon as `let (VARIABLE)' has been recognized, the first action is
  73. run.  It saves a copy of the current semantic context (the list of
  74. accessible variables) as its semantic value, using alternative
  75. `context' in the data-type union.  Then it calls `declare_variable' to
  76. add the new variable to that list.  Once the first action is finished,
  77. the embedded statement `stmt' can be parsed.  Note that the mid-rule
  78. action is component number 5, so the `stmt' is component number 6.
  79.  
  80.    After the embedded statement is parsed, its semantic value becomes
  81. the value of the entire `let'-statement.  Then the semantic value from
  82. the earlier action is used to restore the prior list of variables.  This
  83. removes the temporary `let'-variable from the list so that it won't
  84. appear to exist while the rest of the program is parsed.
  85.  
  86.    Taking action before a rule is completely recognized often leads to
  87. conflicts since the parser must commit to a parse in order to execute
  88. the action.  For example, the following two rules, without mid-rule
  89. actions, can coexist in a working parser because the parser can shift
  90. the open-brace token and look at what follows before deciding whether
  91. there is a declaration or not:
  92.  
  93.      compound: '{' declarations statements '}'
  94.              | '{' statements '}'
  95.              ;
  96.  
  97. But when we add a mid-rule action as follows, the rules become
  98. nonfunctional:
  99.  
  100.      compound: { prepare_for_local_variables (); }
  101.                '{' declarations statements '}'
  102.              | '{' statements '}'
  103.              ;
  104.  
  105. Now the parser is forced to decide whether to run the mid-rule action
  106. when it has read no farther than the open-brace.  In other words, it
  107. must commit to using one rule or the other, without sufficient
  108. information to do it correctly.  (The open-brace token is what is called
  109. the "look-ahead" token at this time, since the parser is still deciding
  110. what to do about it.  *Note Look-Ahead Tokens: Look-Ahead.)
  111.  
  112.    You might think that you could correct the problem by putting
  113. identical actions into the two rules, like this:
  114.  
  115.      compound: { prepare_for_local_variables (); }
  116.                '{' declarations statements '}'
  117.              | { prepare_for_local_variables (); }
  118.                '{' statements '}'
  119.              ;
  120.  
  121. But this does not help, because Bison does not realize that the two
  122. actions are identical.  (Bison never tries to understand the C code in
  123. an action.)
  124.  
  125.    If the grammar is such that a declaration can be distinguished from a
  126. statement by the first token (which is true in C), then one solution
  127. which does work is to put the action after the open-brace, like this:
  128.  
  129.      compound: '{' { prepare_for_local_variables (); }
  130.                declarations statements '}'
  131.              | '{' statements '}'
  132.              ;
  133.  
  134. Now the first token of the following declaration or statement, which
  135. would in any case tell Bison which rule to use, can still do so.
  136.  
  137.    Another solution is to bury the action inside a nonterminal symbol
  138. which serves as a subroutine:
  139.  
  140.      subroutine: /* empty */
  141.                { prepare_for_local_variables (); }
  142.              ;
  143.      
  144.      compound: subroutine
  145.                '{' declarations statements '}'
  146.              | subroutine
  147.                '{' statements '}'
  148.              ;
  149.  
  150. Now Bison can execute the action in the rule for `subroutine' without
  151. deciding which rule for `compound' it will eventually use.  Note that
  152. the action is now at the end of its rule.  Any mid-rule action can be
  153. converted to an end-of-rule action in this way, and this is what Bison
  154. actually does to implement mid-rule actions.
  155.  
  156. 
  157. File: bison.info,  Node: Declarations,  Next: Multiple Parsers,  Prev: Semantics,  Up: Grammar File
  158.  
  159. Bison Declarations
  160. ==================
  161.  
  162.    The "Bison declarations" section of a Bison grammar defines the
  163. symbols used in formulating the grammar and the data types of semantic
  164. values.  *Note Symbols::.
  165.  
  166.    All token type names (but not single-character literal tokens such as
  167. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  168. declared if you need to specify which data type to use for the semantic
  169. value (*note More Than One Value Type: Multiple Types.).
  170.  
  171.    The first rule in the file also specifies the start symbol, by
  172. default.  If you want some other symbol to be the start symbol, you
  173. must declare it explicitly (*note Languages and Context-Free Grammars:
  174. Language and Grammar.).
  175.  
  176. * Menu:
  177.  
  178. * Token Decl::        Declaring terminal symbols.
  179. * Precedence Decl::   Declaring terminals with precedence and associativity.
  180. * Union Decl::        Declaring the set of all semantic value types.
  181. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  182. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  183. * Start Decl::        Specifying the start symbol.
  184. * Pure Decl::         Requesting a reentrant parser.
  185. * Decl Summary::      Table of all Bison declarations.
  186.  
  187. 
  188. File: bison.info,  Node: Token Decl,  Next: Precedence Decl,  Up: Declarations
  189.  
  190. Token Type Names
  191. ----------------
  192.  
  193.    The basic way to declare a token type name (terminal symbol) is as
  194. follows:
  195.  
  196.      %token NAME
  197.  
  198.    Bison will convert this into a `#define' directive in the parser, so
  199. that the function `yylex' (if it is in this file) can use the name NAME
  200. to stand for this token type's code.
  201.  
  202.    Alternatively, you can use `%left', `%right', or `%nonassoc' instead
  203. of `%token', if you wish to specify precedence.  *Note Operator
  204. Precedence: Precedence Decl.
  205.  
  206.    You can explicitly specify the numeric code for a token type by
  207. appending an integer value in the field immediately following the token
  208. name:
  209.  
  210.      %token NUM 300
  211.  
  212. It is generally best, however, to let Bison choose the numeric codes for
  213. all token types.  Bison will automatically select codes that don't
  214. conflict with each other or with ASCII characters.
  215.  
  216.    In the event that the stack type is a union, you must augment the
  217. `%token' or other token declaration to include the data type
  218. alternative delimited by angle-brackets (*note More Than One Value
  219. Type: Multiple Types.).
  220.  
  221.    For example:
  222.  
  223.      %union {              /* define stack type */
  224.        double val;
  225.        symrec *tptr;
  226.      }
  227.      %token <val> NUM      /* define token NUM and its type */
  228.  
  229. 
  230. File: bison.info,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  231.  
  232. Operator Precedence
  233. -------------------
  234.  
  235.    Use the `%left', `%right' or `%nonassoc' declaration to declare a
  236. token and specify its precedence and associativity, all at once.  These
  237. are called "precedence declarations".  *Note Operator Precedence:
  238. Precedence, for general information on operator precedence.
  239.  
  240.    The syntax of a precedence declaration is the same as that of
  241. `%token': either
  242.  
  243.      %left SYMBOLS...
  244.  
  245. or
  246.  
  247.      %left <TYPE> SYMBOLS...
  248.  
  249.    And indeed any of these declarations serves the purposes of `%token'.
  250. But in addition, they specify the associativity and relative precedence
  251. for all the SYMBOLS:
  252.  
  253.    * The associativity of an operator OP determines how repeated uses
  254.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  255.      X with Y first or by grouping Y with Z first.  `%left' specifies
  256.      left-associativity (grouping X with Y first) and `%right'
  257.      specifies right-associativity (grouping Y with Z first).
  258.      `%nonassoc' specifies no associativity, which means that `X OP Y
  259.      OP Z' is considered a syntax error.
  260.  
  261.    * The precedence of an operator determines how it nests with other
  262.      operators.  All the tokens declared in a single precedence
  263.      declaration have equal precedence and nest together according to
  264.      their associativity.  When two tokens declared in different
  265.      precedence declarations associate, the one declared later has the
  266.      higher precedence and is grouped first.
  267.  
  268. 
  269. File: bison.info,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  270.  
  271. The Collection of Value Types
  272. -----------------------------
  273.  
  274.    The `%union' declaration specifies the entire collection of possible
  275. data types for semantic values.  The keyword `%union' is followed by a
  276. pair of braces containing the same thing that goes inside a `union' in
  277. C.
  278.  
  279.    For example:
  280.  
  281.      %union {
  282.        double val;
  283.        symrec *tptr;
  284.      }
  285.  
  286. This says that the two alternative types are `double' and `symrec *'.
  287. They are given names `val' and `tptr'; these names are used in the
  288. `%token' and `%type' declarations to pick one of the types for a
  289. terminal or nonterminal symbol (*note Nonterminal Symbols: Type Decl.).
  290.  
  291.    Note that, unlike making a `union' declaration in C, you do not write
  292. a semicolon after the closing brace.
  293.  
  294. 
  295. File: bison.info,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  296.  
  297. Nonterminal Symbols
  298. -------------------
  299.  
  300. When you use `%union' to specify multiple value types, you must declare
  301. the value type of each nonterminal symbol for which values are used.
  302. This is done with a `%type' declaration, like this:
  303.  
  304.      %type <TYPE> NONTERMINAL...
  305.  
  306. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  307. name given in the `%union' to the alternative that you want (*note The
  308. Collection of Value Types: Union Decl.).  You can give any number of
  309. nonterminal symbols in the same `%type' declaration, if they have the
  310. same value type.  Use spaces to separate the symbol names.
  311.  
  312. 
  313. File: bison.info,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  314.  
  315. Suppressing Conflict Warnings
  316. -----------------------------
  317.  
  318.    Bison normally warns if there are any conflicts in the grammar
  319. (*note Shift/Reduce Conflicts: Shift/Reduce.), but most real grammars
  320. have harmless shift/reduce conflicts which are resolved in a
  321. predictable way and would be difficult to eliminate.  It is desirable
  322. to suppress the warning about these conflicts unless the number of
  323. conflicts changes.  You can do this with the `%expect' declaration.
  324.  
  325.    The declaration looks like this:
  326.  
  327.      %expect N
  328.  
  329.    Here N is a decimal integer.  The declaration says there should be no
  330. warning if there are N shift/reduce conflicts and no reduce/reduce
  331. conflicts.  The usual warning is given if there are either more or fewer
  332. conflicts, or if there are any reduce/reduce conflicts.
  333.  
  334.    In general, using `%expect' involves these steps:
  335.  
  336.    * Compile your grammar without `%expect'.  Use the `-v' option to
  337.      get a verbose list of where the conflicts occur.  Bison will also
  338.      print the number of conflicts.
  339.  
  340.    * Check each of the conflicts to make sure that Bison's default
  341.      resolution is what you really want.  If not, rewrite the grammar
  342.      and go back to the beginning.
  343.  
  344.    * Add an `%expect' declaration, copying the number N from the number
  345.      which Bison printed.
  346.  
  347.    Now Bison will stop annoying you about the conflicts you have
  348. checked, but it will warn you again if changes in the grammar result in
  349. additional conflicts.
  350.  
  351. 
  352. File: bison.info,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  353.  
  354. The Start-Symbol
  355. ----------------
  356.  
  357.    Bison assumes by default that the start symbol for the grammar is
  358. the first nonterminal specified in the grammar specification section.
  359. The programmer may override this restriction with the `%start'
  360. declaration as follows:
  361.  
  362.      %start SYMBOL
  363.  
  364. 
  365. File: bison.info,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  366.  
  367. A Pure (Reentrant) Parser
  368. -------------------------
  369.  
  370.    A "reentrant" program is one which does not alter in the course of
  371. execution; in other words, it consists entirely of "pure" (read-only)
  372. code.  Reentrancy is important whenever asynchronous execution is
  373. possible; for example, a nonreentrant program may not be safe to call
  374. from a signal handler.  In systems with multiple threads of control, a
  375. nonreentrant program must be called only within interlocks.
  376.  
  377.    The Bison parser is not normally a reentrant program, because it uses
  378. statically allocated variables for communication with `yylex'.  These
  379. variables include `yylval' and `yylloc'.
  380.  
  381.    The Bison declaration `%pure_parser' says that you want the parser
  382. to be reentrant.  It looks like this:
  383.  
  384.      %pure_parser
  385.  
  386.    The effect is that the two communication variables become local
  387. variables in `yyparse', and a different calling convention is used for
  388. the lexical analyzer function `yylex'.  *Note Calling for Pure Parsers:
  389. Pure Calling, for the details of this.  The variable `yynerrs' also
  390. becomes local in `yyparse' (*note The Error Reporting Function
  391. `yyerror': Error Reporting.).  The convention for calling `yyparse'
  392. itself is unchanged.
  393.  
  394. 
  395. File: bison.info,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  396.  
  397. Bison Declaration Summary
  398. -------------------------
  399.  
  400.    Here is a summary of all Bison declarations:
  401.  
  402. `%union'
  403.      Declare the collection of data types that semantic values may have
  404.      (*note The Collection of Value Types: Union Decl.).
  405.  
  406. `%token'
  407.      Declare a terminal symbol (token type name) with no precedence or
  408.      associativity specified (*note Token Type Names: Token Decl.).
  409.  
  410. `%right'
  411.      Declare a terminal symbol (token type name) that is
  412.      right-associative (*note Operator Precedence: Precedence Decl.).
  413.  
  414. `%left'
  415.      Declare a terminal symbol (token type name) that is
  416.      left-associative (*note Operator Precedence: Precedence Decl.).
  417.  
  418. `%nonassoc'
  419.      Declare a terminal symbol (token type name) that is nonassociative
  420.      (using it in a way that would be associative is a syntax error)
  421.      (*note Operator Precedence: Precedence Decl.).
  422.  
  423. `%type'
  424.      Declare the type of semantic values for a nonterminal symbol
  425.      (*note Nonterminal Symbols: Type Decl.).
  426.  
  427. `%start'
  428.      Specify the grammar's start symbol (*note The Start-Symbol: Start
  429.      Decl.).
  430.  
  431. `%expect'
  432.      Declare the expected number of shift-reduce conflicts (*note
  433.      Suppressing Conflict Warnings: Expect Decl.).
  434.  
  435. `%pure_parser'
  436.      Request a pure (reentrant) parser program (*note A Pure
  437.      (Reentrant) Parser: Pure Decl.).
  438.  
  439. 
  440. File: bison.info,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  441.  
  442. Multiple Parsers in the Same Program
  443. ====================================
  444.  
  445.    Most programs that use Bison parse only one language and therefore
  446. contain only one Bison parser.  But what if you want to parse more than
  447. one language with the same program?  Then you need to avoid a name
  448. conflict between different definitions of `yyparse', `yylval', and so
  449. on.
  450.  
  451.    The easy way to do this is to use the option `-p PREFIX' (*note
  452. Invoking Bison: Invocation.).  This renames the interface functions and
  453. variables of the Bison parser to start with PREFIX instead of `yy'.
  454. You can use this to give each parser distinct names that do not
  455. conflict.
  456.  
  457.    The precise list of symbols renamed is `yyparse', `yylex',
  458. `yyerror', `yylval', `yychar' and `yydebug'.  For example, if you use
  459. `-p c', the names become `cparse', `clex', and so on.
  460.  
  461.    *All the other variables and macros associated with Bison are not
  462. renamed.* These others are not global; there is no conflict if the same
  463. name is used in different parsers.  For example, `YYSTYPE' is not
  464. renamed, but defining this in different ways in different parsers causes
  465. no trouble (*note Data Types of Semantic Values: Value Type.).
  466.  
  467.    The `-p' option works by adding macro definitions to the beginning
  468. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  469. on.  This effectively substitutes one name for the other in the entire
  470. parser file.
  471.  
  472. 
  473. File: bison.info,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  474.  
  475. Parser C-Language Interface
  476. ***************************
  477.  
  478.    The Bison parser is actually a C function named `yyparse'.  Here we
  479. describe the interface conventions of `yyparse' and the other functions
  480. that it needs to use.
  481.  
  482.    Keep in mind that the parser uses many C identifiers starting with
  483. `yy' and `YY' for internal purposes.  If you use such an identifier
  484. (aside from those in this manual) in an action or in additional C code
  485. in the grammar file, you are likely to run into trouble.
  486.  
  487. * Menu:
  488.  
  489. * Parser Function::   How to call `yyparse' and what it returns.
  490. * Lexical::           You must supply a function `yylex'
  491.                         which reads tokens.
  492. * Error Reporting::   You must supply a function `yyerror'.
  493. * Action Features::   Special features for use in actions.
  494.  
  495. 
  496. File: bison.info,  Node: Parser Function,  Next: Lexical,  Up: Interface
  497.  
  498. The Parser Function `yyparse'
  499. =============================
  500.  
  501.    You call the function `yyparse' to cause parsing to occur.  This
  502. function reads tokens, executes actions, and ultimately returns when it
  503. encounters end-of-input or an unrecoverable syntax error.  You can also
  504. write an action which directs `yyparse' to return immediately without
  505. reading further.
  506.  
  507.    The value returned by `yyparse' is 0 if parsing was successful
  508. (return is due to end-of-input).
  509.  
  510.    The value is 1 if parsing failed (return is due to a syntax error).
  511.  
  512.    In an action, you can cause immediate return from `yyparse' by using
  513. these macros:
  514.  
  515. `YYACCEPT'
  516.      Return immediately with value 0 (to report success).
  517.  
  518. `YYABORT'
  519.      Return immediately with value 1 (to report failure).
  520.  
  521. 
  522. File: bison.info,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  523.  
  524. The Lexical Analyzer Function `yylex'
  525. =====================================
  526.  
  527.    The "lexical analyzer" function, `yylex', recognizes tokens from the
  528. input stream and returns them to the parser.  Bison does not create
  529. this function automatically; you must write it so that `yyparse' can
  530. call it.  The function is sometimes referred to as a lexical scanner.
  531.  
  532.    In simple programs, `yylex' is often defined at the end of the Bison
  533. grammar file.  If `yylex' is defined in a separate source file, you
  534. need to arrange for the token-type macro definitions to be available
  535. there.  To do this, use the `-d' option when you run Bison, so that it
  536. will write these macro definitions into a separate header file
  537. `NAME.tab.h' which you can include in the other source files that need
  538. it.  *Note Invoking Bison: Invocation.
  539.  
  540. * Menu:
  541.  
  542. * Calling Convention::  How `yyparse' calls `yylex'.
  543. * Token Values::      How `yylex' must return the semantic value
  544.                         of the token it has read.
  545. * Token Positions::   How `yylex' must return the text position
  546.                         (line number, etc.) of the token, if the
  547.                         actions want that.
  548. * Pure Calling::      How the calling convention differs
  549.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  550.  
  551. 
  552. File: bison.info,  Node: Calling Convention,  Next: Token Values,  Up: Lexical
  553.  
  554. Calling Convention for `yylex'
  555. ------------------------------
  556.  
  557.    The value that `yylex' returns must be the numeric code for the type
  558. of token it has just found, or 0 for end-of-input.
  559.  
  560.    When a token is referred to in the grammar rules by a name, that name
  561. in the parser file becomes a C macro whose definition is the proper
  562. numeric code for that token type.  So `yylex' can use the name to
  563. indicate that type.  *Note Symbols::.
  564.  
  565.    When a token is referred to in the grammar rules by a character
  566. literal, the numeric code for that character is also the code for the
  567. token type.  So `yylex' can simply return that character code.  The
  568. null character must not be used this way, because its code is zero and
  569. that is what signifies end-of-input.
  570.  
  571.    Here is an example showing these things:
  572.  
  573.      yylex ()
  574.      {
  575.        ...
  576.        if (c == EOF)     /* Detect end of file. */
  577.          return 0;
  578.        ...
  579.        if (c == '+' || c == '-')
  580.          return c;      /* Assume token type for `+' is '+'. */
  581.        ...
  582.        return INT;      /* Return the type of the token. */
  583.        ...
  584.      }
  585.  
  586. This interface has been designed so that the output from the `lex'
  587. utility can be used without change as the definition of `yylex'.
  588.  
  589. 
  590. File: bison.info,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  591.  
  592. Semantic Values of Tokens
  593. -------------------------
  594.  
  595.    In an ordinary (nonreentrant) parser, the semantic value of the
  596. token must be stored into the global variable `yylval'.  When you are
  597. using just one data type for semantic values, `yylval' has that type.
  598. Thus, if the type is `int' (the default), you might write this in
  599. `yylex':
  600.  
  601.        ...
  602.        yylval = value;  /* Put value onto Bison stack. */
  603.        return INT;      /* Return the type of the token. */
  604.        ...
  605.  
  606.    When you are using multiple data types, `yylval''s type is a union
  607. made from the `%union' declaration (*note The Collection of Value
  608. Types: Union Decl.).  So when you store a token's value, you must use
  609. the proper member of the union.  If the `%union' declaration looks like
  610. this:
  611.  
  612.      %union {
  613.        int intval;
  614.        double val;
  615.        symrec *tptr;
  616.      }
  617.  
  618. then the code in `yylex' might look like this:
  619.  
  620.        ...
  621.        yylval.intval = value; /* Put value onto Bison stack. */
  622.        return INT;          /* Return the type of the token. */
  623.        ...
  624.  
  625. 
  626. File: bison.info,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  627.  
  628. Textual Positions of Tokens
  629. ---------------------------
  630.  
  631.    If you are using the `@N'-feature (*note Special Features for Use in
  632. Actions: Action Features.) in actions to keep track of the textual
  633. locations of tokens and groupings, then you must provide this
  634. information in `yylex'.  The function `yyparse' expects to find the
  635. textual location of a token just parsed in the global variable
  636. `yylloc'.  So `yylex' must store the proper data in that variable.  The
  637. value of `yylloc' is a structure and you need only initialize the
  638. members that are going to be used by the actions.  The four members are
  639. called `first_line', `first_column', `last_line' and `last_column'.
  640. Note that the use of this feature makes the parser noticeably slower.
  641.  
  642.    The data type of `yylloc' has the name `YYLTYPE'.
  643.  
  644. 
  645. File: bison.info,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  646.  
  647. Calling for Pure Parsers
  648. ------------------------
  649.  
  650.    When you use the Bison declaration `%pure_parser' to request a pure,
  651. reentrant parser, the global communication variables `yylval' and
  652. `yylloc' cannot be used.  (*Note A Pure (Reentrant) Parser: Pure Decl.)
  653. In such parsers the two global variables are replaced by pointers
  654. passed as arguments to `yylex'.  You must declare them as shown here,
  655. and pass the information back by storing it through those pointers.
  656.  
  657.      yylex (lvalp, llocp)
  658.           YYSTYPE *lvalp;
  659.           YYLTYPE *llocp;
  660.      {
  661.        ...
  662.        *lvalp = value;  /* Put value onto Bison stack.  */
  663.        return INT;      /* Return the type of the token.  */
  664.        ...
  665.      }
  666.  
  667.    If the grammar file does not use the `@' constructs to refer to
  668. textual positions, then the type `YYLTYPE' will not be defined.  In
  669. this case, omit the second argument; `yylex' will be called with only
  670. one argument.
  671.  
  672. 
  673. File: bison.info,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  674.  
  675. The Error Reporting Function `yyerror'
  676. ======================================
  677.  
  678.    The Bison parser detects a "parse error" or "syntax error" whenever
  679. it reads a token which cannot satisfy any syntax rule.  A action in the
  680. grammar can also explicitly proclaim an error, using the macro
  681. `YYERROR' (*note Special Features for Use in Actions: Action Features.).
  682.  
  683.    The Bison parser expects to report the error by calling an error
  684. reporting function named `yyerror', which you must supply.  It is
  685. called by `yyparse' whenever a syntax error is found, and it receives
  686. one argument.  For a parse error, the string is normally
  687. `"parse error"'.
  688.  
  689.    If you define the macro `YYERROR_VERBOSE' in the Bison declarations
  690. section (*note The Bison Declarations Section: Bison Declarations.),
  691. then Bison provides a more verbose and specific error message string
  692. instead of just plain `"parse error"'.  It doesn't matter what
  693. definition you use for `YYERROR_VERBOSE', just whether you define it.
  694.  
  695.    The parser can detect one other kind of error: stack overflow.  This
  696. happens when the input contains constructions that are very deeply
  697. nested.  It isn't likely you will encounter this, since the Bison
  698. parser extends its stack automatically up to a very large limit.  But
  699. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  700. except that the argument string is `"parser stack overflow"'.
  701.  
  702.    The following definition suffices in simple programs:
  703.  
  704.      yyerror (s)
  705.           char *s;
  706.      {
  707.        fprintf (stderr, "%s\n", s);
  708.      }
  709.  
  710.    After `yyerror' returns to `yyparse', the latter will attempt error
  711. recovery if you have written suitable error recovery grammar rules
  712. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  713. immediately return 1.
  714.  
  715.    The variable `yynerrs' contains the number of syntax errors
  716. encountered so far.  Normally this variable is global; but if you
  717. request a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.)
  718. then it is a local variable which only the actions can access.
  719.  
  720. 
  721. File: bison.info,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  722.  
  723. Special Features for Use in Actions
  724. ===================================
  725.  
  726.    Here is a table of Bison constructs, variables and macros that are
  727. useful in actions.
  728.  
  729. `$$'
  730.      Acts like a variable that contains the semantic value for the
  731.      grouping made by the current rule.  *Note Actions::.
  732.  
  733. `$N'
  734.      Acts like a variable that contains the semantic value for the Nth
  735.      component of the current rule.  *Note Actions::.
  736.  
  737. `$<TYPEALT>$'
  738.      Like `$$' but specifies alternative TYPEALT in the union specified
  739.      by the `%union' declaration.  *Note Data Types of Values in
  740.      Actions: Action Types.
  741.  
  742. `$<TYPEALT>N'
  743.      Like `$N' but specifies alternative TYPEALT in the union specified
  744.      by the `%union' declaration.  *Note Data Types of Values in
  745.      Actions: Action Types.
  746.  
  747. `YYABORT;'
  748.      Return immediately from `yyparse', indicating failure.  *Note The
  749.      Parser Function `yyparse': Parser Function.
  750.  
  751. `YYACCEPT;'
  752.      Return immediately from `yyparse', indicating success.  *Note The
  753.      Parser Function `yyparse': Parser Function.
  754.  
  755. `YYBACKUP (TOKEN, VALUE);'
  756.      Unshift a token.  This macro is allowed only for rules that reduce
  757.      a single value, and only when there is no look-ahead token.  It
  758.      installs a look-ahead token with token type TOKEN and semantic
  759.      value VALUE; then it discards the value that was going to be
  760.      reduced by this rule.
  761.  
  762.      If the macro is used when it is not valid, such as when there is a
  763.      look-ahead token already, then it reports a syntax error with a
  764.      message `cannot back up' and performs ordinary error recovery.
  765.  
  766.      In either case, the rest of the action is not executed.
  767.  
  768. `YYEMPTY'
  769.      Value stored in `yychar' when there is no look-ahead token.
  770.  
  771. `YYERROR;'
  772.      Cause an immediate syntax error.  This statement initiates error
  773.      recovery just as if the parser itself had detected an error;
  774.      however, it does not call `yyerror', and does not print any
  775.      message.  If you want to print an error message, call `yyerror'
  776.      explicitly before the `YYERROR;' statement.  *Note Error
  777.      Recovery::.
  778.  
  779. `YYRECOVERING'
  780.      This macro stands for an expression that has the value 1 when the
  781.      parser is recovering from a syntax error, and 0 the rest of the
  782.      time.  *Note Error Recovery::.
  783.  
  784. `yychar'
  785.      Variable containing the current look-ahead token.  (In a pure
  786.      parser, this is actually a local variable within `yyparse'.)  When
  787.      there is no look-ahead token, the value `YYEMPTY' is stored in the
  788.      variable.  *Note Look-Ahead Tokens: Look-Ahead.
  789.  
  790. `yyclearin;'
  791.      Discard the current look-ahead token.  This is useful primarily in
  792.      error rules.  *Note Error Recovery::.
  793.  
  794. `yyerrok;'
  795.      Resume generating error messages immediately for subsequent syntax
  796.      errors.  This is useful primarily in error rules.  *Note Error
  797.      Recovery::.
  798.  
  799. `@N'
  800.      Acts like a structure variable containing information on the line
  801.      numbers and column numbers of the Nth component of the current
  802.      rule.  The structure has four members, like this:
  803.  
  804.           struct {
  805.             int first_line, last_line;
  806.             int first_column, last_column;
  807.           };
  808.  
  809.      Thus, to get the starting line number of the third component, use
  810.      `@3.first_line'.
  811.  
  812.      In order for the members of this structure to contain valid
  813.      information, you must make `yylex' supply this information about
  814.      each token.  If you need only certain members, then `yylex' need
  815.      only fill in those members.
  816.  
  817.      The use of this feature makes the parser noticeably slower.
  818.  
  819. 
  820. File: bison.info,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  821.  
  822. The Bison Parser Algorithm
  823. **************************
  824.  
  825.    As Bison reads tokens, it pushes them onto a stack along with their
  826. semantic values.  The stack is called the "parser stack".  Pushing a
  827. token is traditionally called "shifting".
  828.  
  829.    For example, suppose the infix calculator has read `1 + 5 *', with a
  830. `3' to come.  The stack will have four elements, one for each token
  831. that was shifted.
  832.  
  833.    But the stack does not always have an element for each token read.
  834. When the last N tokens and groupings shifted match the components of a
  835. grammar rule, they can be combined according to that rule.  This is
  836. called "reduction".  Those tokens and groupings are replaced on the
  837. stack by a single grouping whose symbol is the result (left hand side)
  838. of that rule.  Running the rule's action is part of the process of
  839. reduction, because this is what computes the semantic value of the
  840. resulting grouping.
  841.  
  842.    For example, if the infix calculator's parser stack contains this:
  843.  
  844.      1 + 5 * 3
  845.  
  846. and the next input token is a newline character, then the last three
  847. elements can be reduced to 15 via the rule:
  848.  
  849.      expr: expr '*' expr;
  850.  
  851. Then the stack contains just these three elements:
  852.  
  853.      1 + 15
  854.  
  855. At this point, another reduction can be made, resulting in the single
  856. value 16.  Then the newline token can be shifted.
  857.  
  858.    The parser tries, by shifts and reductions, to reduce the entire
  859. input down to a single grouping whose symbol is the grammar's
  860. start-symbol (*note Languages and Context-Free Grammars: Language and
  861. Grammar.).
  862.  
  863.    This kind of parser is known in the literature as a bottom-up parser.
  864.  
  865. * Menu:
  866.  
  867. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  868. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  869. * Precedence::        Operator precedence works by resolving conflicts.
  870. * Contextual Precedence::  When an operator's precedence depends on context.
  871. * Parser States::     The parser is a finite-state-machine with stack.
  872. * Reduce/Reduce::     When two rules are applicable in the same situation.
  873. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  874. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  875.  
  876. 
  877. File: bison.info,  Node: Look-Ahead,  Next: Shift/Reduce,  Up: Algorithm
  878.  
  879. Look-Ahead Tokens
  880. =================
  881.  
  882.    The Bison parser does *not* always reduce immediately as soon as the
  883. last N tokens and groupings match a rule.  This is because such a
  884. simple strategy is inadequate to handle most languages.  Instead, when a
  885. reduction is possible, the parser sometimes "looks ahead" at the next
  886. token in order to decide what to do.
  887.  
  888.    When a token is read, it is not immediately shifted; first it
  889. becomes the "look-ahead token", which is not on the stack.  Now the
  890. parser can perform one or more reductions of tokens and groupings on
  891. the stack, while the look-ahead token remains off to the side.  When no
  892. more reductions should take place, the look-ahead token is shifted onto
  893. the stack.  This does not mean that all possible reductions have been
  894. done; depending on the token type of the look-ahead token, some rules
  895. may choose to delay their application.
  896.  
  897.    Here is a simple case where look-ahead is needed.  These three rules
  898. define expressions which contain binary addition operators and postfix
  899. unary factorial operators (`!'), and allow parentheses for grouping.
  900.  
  901.      expr:     term '+' expr
  902.              | term
  903.              ;
  904.      
  905.      term:     '(' expr ')'
  906.              | term '!'
  907.              | NUMBER
  908.              ;
  909.  
  910.    Suppose that the tokens `1 + 2' have been read and shifted; what
  911. should be done?  If the following token is `)', then the first three
  912. tokens must be reduced to form an `expr'.  This is the only valid
  913. course, because shifting the `)' would produce a sequence of symbols
  914. `term ')'', and no rule allows this.
  915.  
  916.    If the following token is `!', then it must be shifted immediately so
  917. that `2 !' can be reduced to make a `term'.  If instead the parser were
  918. to reduce before shifting, `1 + 2' would become an `expr'.  It would
  919. then be impossible to shift the `!' because doing so would produce on
  920. the stack the sequence of symbols `expr '!''.  No rule allows that
  921. sequence.
  922.  
  923.    The current look-ahead token is stored in the variable `yychar'.
  924. *Note Special Features for Use in Actions: Action Features.
  925.  
  926. 
  927. File: bison.info,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  928.  
  929. Shift/Reduce Conflicts
  930. ======================
  931.  
  932.    Suppose we are parsing a language which has if-then and if-then-else
  933. statements, with a pair of rules like this:
  934.  
  935.      if_stmt:
  936.                IF expr THEN stmt
  937.              | IF expr THEN stmt ELSE stmt
  938.              ;
  939.  
  940. Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  941. specific keyword tokens.
  942.  
  943.    When the `ELSE' token is read and becomes the look-ahead token, the
  944. contents of the stack (assuming the input is valid) are just right for
  945. reduction by the first rule.  But it is also legitimate to shift the
  946. `ELSE', because that would lead to eventual reduction by the second
  947. rule.
  948.  
  949.    This situation, where either a shift or a reduction would be valid,
  950. is called a "shift/reduce conflict".  Bison is designed to resolve
  951. these conflicts by choosing to shift, unless otherwise directed by
  952. operator precedence declarations.  To see the reason for this, let's
  953. contrast it with the other alternative.
  954.  
  955.    Since the parser prefers to shift the `ELSE', the result is to attach
  956. the else-clause to the innermost if-statement, making these two inputs
  957. equivalent:
  958.  
  959.      if x then if y then win (); else lose;
  960.      
  961.      if x then do; if y then win (); else lose; end;
  962.  
  963.    But if the parser chose to reduce when possible rather than shift,
  964. the result would be to attach the else-clause to the outermost
  965. if-statement, making these two inputs equivalent:
  966.  
  967.      if x then if y then win (); else lose;
  968.      
  969.      if x then do; if y then win (); end; else lose;
  970.  
  971.    The conflict exists because the grammar as written is ambiguous:
  972. either parsing of the simple nested if-statement is legitimate.  The
  973. established convention is that these ambiguities are resolved by
  974. attaching the else-clause to the innermost if-statement; this is what
  975. Bison accomplishes by choosing to shift rather than reduce.  (It would
  976. ideally be cleaner to write an unambiguous grammar, but that is very
  977. hard to do in this case.) This particular ambiguity was first
  978. encountered in the specifications of Algol 60 and is called the
  979. "dangling `else'" ambiguity.
  980.  
  981.    To avoid warnings from Bison about predictable, legitimate
  982. shift/reduce conflicts, use the `%expect N' declaration.  There will be
  983. no warning as long as the number of shift/reduce conflicts is exactly N.
  984. *Note Suppressing Conflict Warnings: Expect Decl.
  985.  
  986.    The definition of `if_stmt' above is solely to blame for the
  987. conflict, but the conflict does not actually appear without additional
  988. rules.  Here is a complete Bison input file that actually manifests the
  989. conflict:
  990.  
  991.      %token IF THEN ELSE variable
  992.      %%
  993.      stmt:     expr
  994.              | if_stmt
  995.              ;
  996.      
  997.      if_stmt:
  998.                IF expr THEN stmt
  999.              | IF expr THEN stmt ELSE stmt
  1000.              ;
  1001.      
  1002.      expr:     variable
  1003.              ;
  1004.  
  1005. 
  1006. File: bison.info,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  1007.  
  1008. Operator Precedence
  1009. ===================
  1010.  
  1011.    Another situation where shift/reduce conflicts appear is in
  1012. arithmetic expressions.  Here shifting is not always the preferred
  1013. resolution; the Bison declarations for operator precedence allow you to
  1014. specify when to shift and when to reduce.
  1015.  
  1016. * Menu:
  1017.  
  1018. * Why Precedence::    An example showing why precedence is needed.
  1019. * Using Precedence::  How to specify precedence in Bison grammars.
  1020. * Precedence Examples::  How these features are used in the previous example.
  1021. * How Precedence::    How they work.
  1022.  
  1023. 
  1024. File: bison.info,  Node: Why Precedence,  Next: Using Precedence,  Up: Precedence
  1025.  
  1026. When Precedence is Needed
  1027. -------------------------
  1028.  
  1029.    Consider the following ambiguous grammar fragment (ambiguous because
  1030. the input `1 - 2 * 3' can be parsed in two different ways):
  1031.  
  1032.      expr:     expr '-' expr
  1033.              | expr '*' expr
  1034.              | expr '<' expr
  1035.              | '(' expr ')'
  1036.              ...
  1037.              ;
  1038.  
  1039. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  1040. reduce them via the rule for the addition operator?  It depends on the
  1041. next token.  Of course, if the next token is `)', we must reduce;
  1042. shifting is invalid because no single rule can reduce the token
  1043. sequence `- 2 )' or anything starting with that.  But if the next token
  1044. is `*' or `<', we have a choice: either shifting or reduction would
  1045. allow the parse to complete, but with different results.
  1046.  
  1047.    To decide which one Bison should do, we must consider the results.
  1048. If the next operator token OP is shifted, then it must be reduced first
  1049. in order to permit another opportunity to reduce the sum.  The result
  1050. is (in effect) `1 - (2 OP 3)'.  On the other hand, if the subtraction
  1051. is reduced before shifting OP, the result is `(1 - 2) OP 3'.  Clearly,
  1052. then, the choice of shift or reduce should depend on the relative
  1053. precedence of the operators `-' and OP: `*' should be shifted first,
  1054. but not `<'.
  1055.  
  1056.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  1057. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  1058. former, which is called "left association".  The latter alternative,
  1059. "right association", is desirable for assignment operators.  The choice
  1060. of left or right association is a matter of whether the parser chooses
  1061. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  1062. token is `-': shifting makes right-associativity.
  1063.  
  1064. 
  1065. File: bison.info,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  1066.  
  1067. Specifying Operator Precedence
  1068. ------------------------------
  1069.  
  1070.    Bison allows you to specify these choices with the operator
  1071. precedence declarations `%left' and `%right'.  Each such declaration
  1072. contains a list of tokens, which are operators whose precedence and
  1073. associativity is being declared.  The `%left' declaration makes all
  1074. those operators left-associative and the `%right' declaration makes
  1075. them right-associative.  A third alternative is `%nonassoc', which
  1076. declares that it is a syntax error to find the same operator twice "in a
  1077. row".
  1078.  
  1079.    The relative precedence of different operators is controlled by the
  1080. order in which they are declared.  The first `%left' or `%right'
  1081. declaration in the file declares the operators whose precedence is
  1082. lowest, the next such declaration declares the operators whose
  1083. precedence is a little higher, and so on.
  1084.  
  1085. 
  1086. File: bison.info,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  1087.  
  1088. Precedence Examples
  1089. -------------------
  1090.  
  1091.    In our example, we would want the following declarations:
  1092.  
  1093.      %left '<'
  1094.      %left '-'
  1095.      %left '*'
  1096.  
  1097.    In a more complete example, which supports other operators as well,
  1098. we would declare them in groups of equal precedence.  For example,
  1099. `'+'' is declared with `'-'':
  1100.  
  1101.      %left '<' '>' '=' NE LE GE
  1102.      %left '+' '-'
  1103.      %left '*' '/'
  1104.  
  1105. (Here `NE' and so on stand for the operators for "not equal" and so on.
  1106. We assume that these tokens are more than one character long and
  1107. therefore are represented by names, not character literals.)
  1108.  
  1109. 
  1110. File: bison.info,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  1111.  
  1112. How Precedence Works
  1113. --------------------
  1114.  
  1115.    The first effect of the precedence declarations is to assign
  1116. precedence levels to the terminal symbols declared.  The second effect
  1117. is to assign precedence levels to certain rules: each rule gets its
  1118. precedence from the last terminal symbol mentioned in the components.
  1119. (You can also specify explicitly the precedence of a rule.  *Note
  1120. Context-Dependent Precedence: Contextual Precedence.)
  1121.  
  1122.    Finally, the resolution of conflicts works by comparing the
  1123. precedence of the rule being considered with that of the look-ahead
  1124. token.  If the token's precedence is higher, the choice is to shift.
  1125. If the rule's precedence is higher, the choice is to reduce.  If they
  1126. have equal precedence, the choice is made based on the associativity of
  1127. that precedence level.  The verbose output file made by `-v' (*note
  1128. Invoking Bison: Invocation.) says how each conflict was resolved.
  1129.  
  1130.    Not all rules and not all tokens have precedence.  If either the
  1131. rule or the look-ahead token has no precedence, then the default is to
  1132. shift.
  1133.  
  1134. 
  1135. File: bison.info,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  1136.  
  1137. Context-Dependent Precedence
  1138. ============================
  1139.  
  1140.    Often the precedence of an operator depends on the context.  This
  1141. sounds outlandish at first, but it is really very common.  For example,
  1142. a minus sign typically has a very high precedence as a unary operator,
  1143. and a somewhat lower precedence (lower than multiplication) as a binary
  1144. operator.
  1145.  
  1146.    The Bison precedence declarations, `%left', `%right' and
  1147. `%nonassoc', can only be used once for a given token; so a token has
  1148. only one precedence declared in this way.  For context-dependent
  1149. precedence, you need to use an additional mechanism: the `%prec'
  1150. modifier for rules.
  1151.  
  1152.    The `%prec' modifier declares the precedence of a particular rule by
  1153. specifying a terminal symbol whose precedence should be used for that
  1154. rule.  It's not necessary for that symbol to appear otherwise in the
  1155. rule.  The modifier's syntax is:
  1156.  
  1157.      %prec TERMINAL-SYMBOL
  1158.  
  1159. and it is written after the components of the rule.  Its effect is to
  1160. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  1161. precedence that would be deduced for it in the ordinary way.  The
  1162. altered rule precedence then affects how conflicts involving that rule
  1163. are resolved (*note Operator Precedence: Precedence.).
  1164.  
  1165.    Here is how `%prec' solves the problem of unary minus.  First,
  1166. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  1167. There are no tokens of this type, but the symbol serves to stand for its
  1168. precedence:
  1169.  
  1170.      ...
  1171.      %left '+' '-'
  1172.      %left '*'
  1173.      %left UMINUS
  1174.  
  1175.    Now the precedence of `UMINUS' can be used in specific rules:
  1176.  
  1177.      exp:    ...
  1178.              | exp '-' exp
  1179.              ...
  1180.              | '-' exp %prec UMINUS
  1181.  
  1182. 
  1183. File: bison.info,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  1184.  
  1185. Parser States
  1186. =============
  1187.  
  1188.    The function `yyparse' is implemented using a finite-state machine.
  1189. The values pushed on the parser stack are not simply token type codes;
  1190. they represent the entire sequence of terminal and nonterminal symbols
  1191. at or near the top of the stack.  The current state collects all the
  1192. information about previous input which is relevant to deciding what to
  1193. do next.
  1194.  
  1195.    Each time a look-ahead token is read, the current parser state
  1196. together with the type of look-ahead token are looked up in a table.
  1197. This table entry can say, "Shift the look-ahead token."  In this case,
  1198. it also specifies the new parser state, which is pushed onto the top of
  1199. the parser stack.  Or it can say, "Reduce using rule number N." This
  1200. means that a certain number of tokens or groupings are taken off the
  1201. top of the stack, and replaced by one grouping.  In other words, that
  1202. number of states are popped from the stack, and one new state is pushed.
  1203.  
  1204.    There is one other alternative: the table can say that the
  1205. look-ahead token is erroneous in the current state.  This causes error
  1206. processing to begin (*note Error Recovery::.).
  1207.  
  1208. 
  1209. File: bison.info,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  1210.  
  1211. Reduce/Reduce Conflicts
  1212. =======================
  1213.  
  1214.    A reduce/reduce conflict occurs if there are two or more rules that
  1215. apply to the same sequence of input.  This usually indicates a serious
  1216. error in the grammar.
  1217.  
  1218.    For example, here is an erroneous attempt to define a sequence of
  1219. zero or more `word' groupings.
  1220.  
  1221.      sequence: /* empty */
  1222.                      { printf ("empty sequence\n"); }
  1223.              | maybeword
  1224.              | sequence word
  1225.                      { printf ("added word %s\n", $2); }
  1226.              ;
  1227.      
  1228.      maybeword: /* empty */
  1229.                      { printf ("empty maybeword\n"); }
  1230.              | word
  1231.                      { printf ("single word %s\n", $1); }
  1232.              ;
  1233.  
  1234. The error is an ambiguity: there is more than one way to parse a single
  1235. `word' into a `sequence'.  It could be reduced to a `maybeword' and
  1236. then into a `sequence' via the second rule.  Alternatively,
  1237. nothing-at-all could be reduced into a `sequence' via the first rule,
  1238. and this could be combined with the `word' using the third rule for
  1239. `sequence'.
  1240.  
  1241.    There is also more than one way to reduce nothing-at-all into a
  1242. `sequence'.  This can be done directly via the first rule, or
  1243. indirectly via `maybeword' and then the second rule.
  1244.  
  1245.    You might think that this is a distinction without a difference,
  1246. because it does not change whether any particular input is valid or
  1247. not.  But it does affect which actions are run.  One parsing order runs
  1248. the second rule's action; the other runs the first rule's action and
  1249. the third rule's action.  In this example, the output of the program
  1250. changes.
  1251.  
  1252.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  1253. that appears first in the grammar, but it is very risky to rely on
  1254. this.  Every reduce/reduce conflict must be studied and usually
  1255. eliminated.  Here is the proper way to define `sequence':
  1256.  
  1257.      sequence: /* empty */
  1258.                      { printf ("empty sequence\n"); }
  1259.              | sequence word
  1260.                      { printf ("added word %s\n", $2); }
  1261.              ;
  1262.  
  1263.    Here is another common error that yields a reduce/reduce conflict:
  1264.  
  1265.      sequence: /* empty */
  1266.              | sequence words
  1267.              | sequence redirects
  1268.              ;
  1269.      
  1270.      words:    /* empty */
  1271.              | words word
  1272.              ;
  1273.      
  1274.      redirects:/* empty */
  1275.              | redirects redirect
  1276.              ;
  1277.  
  1278. The intention here is to define a sequence which can contain either
  1279. `word' or `redirect' groupings.  The individual definitions of
  1280. `sequence', `words' and `redirects' are error-free, but the three
  1281. together make a subtle ambiguity: even an empty input can be parsed in
  1282. infinitely many ways!
  1283.  
  1284.    Consider: nothing-at-all could be a `words'.  Or it could be two
  1285. `words' in a row, or three, or any number.  It could equally well be a
  1286. `redirects', or two, or any number.  Or it could be a `words' followed
  1287. by three `redirects' and another `words'.  And so on.
  1288.  
  1289.    Here are two ways to correct these rules.  First, to make it a
  1290. single level of sequence:
  1291.  
  1292.      sequence: /* empty */
  1293.              | sequence word
  1294.              | sequence redirect
  1295.              ;
  1296.  
  1297.    Second, to prevent either a `words' or a `redirects' from being
  1298. empty:
  1299.  
  1300.      sequence: /* empty */
  1301.              | sequence words
  1302.              | sequence redirects
  1303.              ;
  1304.      
  1305.      words:    word
  1306.              | words word
  1307.              ;
  1308.      
  1309.      redirects:redirect
  1310.              | redirects redirect
  1311.              ;
  1312.  
  1313.