home *** CD-ROM | disk | FTP | other *** search
/ OpenStep 4.2J (Developer) / os42jdev.iso / NextDeveloper / Source / GNU / bison / bison.info-3 < prev    next >
Encoding:
GNU Info File  |  1996-02-17  |  49.7 KB  |  1,302 lines

  1. This is Info file bison.info, produced by Makeinfo-1.64 from the input
  2. file ./bison.texinfo.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 89, 90, 91, 92, 93, 1995 Free Software
  7. Foundation, 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.    You can associate a literal string token with a token type name by
  230. writing the literal string at the end of a `%token' declaration which
  231. declares the name.  For example:
  232.  
  233.      %token arrow "=>"
  234.  
  235. For example, a grammar for the C language might specify these names with
  236. equivalent literal string tokens:
  237.  
  238.      %token  <operator>  OR      "||"
  239.      %token  <operator>  LE 134  "<="
  240.      %left  OR  "<="
  241.  
  242. Once you equate the literal string and the token name, you can use them
  243. interchangeably in further declarations or the grammar rules.  The
  244. `yylex' function can use the token name or the literal string to obtain
  245. the token type code number (*note Calling Convention::.).
  246.  
  247. 
  248. File: bison.info,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  249.  
  250. Operator Precedence
  251. -------------------
  252.  
  253.    Use the `%left', `%right' or `%nonassoc' declaration to declare a
  254. token and specify its precedence and associativity, all at once.  These
  255. are called "precedence declarations".  *Note Operator Precedence:
  256. Precedence, for general information on operator precedence.
  257.  
  258.    The syntax of a precedence declaration is the same as that of
  259. `%token': either
  260.  
  261.      %left SYMBOLS...
  262.  
  263. or
  264.  
  265.      %left <TYPE> SYMBOLS...
  266.  
  267.    And indeed any of these declarations serves the purposes of `%token'.
  268. But in addition, they specify the associativity and relative precedence
  269. for all the SYMBOLS:
  270.  
  271.    * The associativity of an operator OP determines how repeated uses
  272.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  273.      X with Y first or by grouping Y with Z first.  `%left' specifies
  274.      left-associativity (grouping X with Y first) and `%right'
  275.      specifies right-associativity (grouping Y with Z first).
  276.      `%nonassoc' specifies no associativity, which means that `X OP Y
  277.      OP Z' is considered a syntax error.
  278.  
  279.    * The precedence of an operator determines how it nests with other
  280.      operators.  All the tokens declared in a single precedence
  281.      declaration have equal precedence and nest together according to
  282.      their associativity.  When two tokens declared in different
  283.      precedence declarations associate, the one declared later has the
  284.      higher precedence and is grouped first.
  285.  
  286. 
  287. File: bison.info,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  288.  
  289. The Collection of Value Types
  290. -----------------------------
  291.  
  292.    The `%union' declaration specifies the entire collection of possible
  293. data types for semantic values.  The keyword `%union' is followed by a
  294. pair of braces containing the same thing that goes inside a `union' in
  295. C.
  296.  
  297.    For example:
  298.  
  299.      %union {
  300.        double val;
  301.        symrec *tptr;
  302.      }
  303.  
  304. This says that the two alternative types are `double' and `symrec *'.
  305. They are given names `val' and `tptr'; these names are used in the
  306. `%token' and `%type' declarations to pick one of the types for a
  307. terminal or nonterminal symbol (*note Nonterminal Symbols: Type Decl.).
  308.  
  309.    Note that, unlike making a `union' declaration in C, you do not write
  310. a semicolon after the closing brace.
  311.  
  312. 
  313. File: bison.info,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  314.  
  315. Nonterminal Symbols
  316. -------------------
  317.  
  318. When you use `%union' to specify multiple value types, you must declare
  319. the value type of each nonterminal symbol for which values are used.
  320. This is done with a `%type' declaration, like this:
  321.  
  322.      %type <TYPE> NONTERMINAL...
  323.  
  324. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  325. name given in the `%union' to the alternative that you want (*note The
  326. Collection of Value Types: Union Decl.).  You can give any number of
  327. nonterminal symbols in the same `%type' declaration, if they have the
  328. same value type.  Use spaces to separate the symbol names.
  329.  
  330.    You can also declare the value type of a terminal symbol.  To do
  331. this, use the same `<TYPE>' construction in a declaration for the
  332. terminal symbol.  All kinds of token declarations allow `<TYPE>'.
  333.  
  334. 
  335. File: bison.info,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  336.  
  337. Suppressing Conflict Warnings
  338. -----------------------------
  339.  
  340.    Bison normally warns if there are any conflicts in the grammar
  341. (*note Shift/Reduce Conflicts: Shift/Reduce.), but most real grammars
  342. have harmless shift/reduce conflicts which are resolved in a
  343. predictable way and would be difficult to eliminate.  It is desirable
  344. to suppress the warning about these conflicts unless the number of
  345. conflicts changes.  You can do this with the `%expect' declaration.
  346.  
  347.    The declaration looks like this:
  348.  
  349.      %expect N
  350.  
  351.    Here N is a decimal integer.  The declaration says there should be no
  352. warning if there are N shift/reduce conflicts and no reduce/reduce
  353. conflicts.  The usual warning is given if there are either more or fewer
  354. conflicts, or if there are any reduce/reduce conflicts.
  355.  
  356.    In general, using `%expect' involves these steps:
  357.  
  358.    * Compile your grammar without `%expect'.  Use the `-v' option to
  359.      get a verbose list of where the conflicts occur.  Bison will also
  360.      print the number of conflicts.
  361.  
  362.    * Check each of the conflicts to make sure that Bison's default
  363.      resolution is what you really want.  If not, rewrite the grammar
  364.      and go back to the beginning.
  365.  
  366.    * Add an `%expect' declaration, copying the number N from the number
  367.      which Bison printed.
  368.  
  369.    Now Bison will stop annoying you about the conflicts you have
  370. checked, but it will warn you again if changes in the grammar result in
  371. additional conflicts.
  372.  
  373. 
  374. File: bison.info,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  375.  
  376. The Start-Symbol
  377. ----------------
  378.  
  379.    Bison assumes by default that the start symbol for the grammar is
  380. the first nonterminal specified in the grammar specification section.
  381. The programmer may override this restriction with the `%start'
  382. declaration as follows:
  383.  
  384.      %start SYMBOL
  385.  
  386. 
  387. File: bison.info,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  388.  
  389. A Pure (Reentrant) Parser
  390. -------------------------
  391.  
  392.    A "reentrant" program is one which does not alter in the course of
  393. execution; in other words, it consists entirely of "pure" (read-only)
  394. code.  Reentrancy is important whenever asynchronous execution is
  395. possible; for example, a nonreentrant program may not be safe to call
  396. from a signal handler.  In systems with multiple threads of control, a
  397. nonreentrant program must be called only within interlocks.
  398.  
  399.    The Bison parser is not normally a reentrant program, because it uses
  400. statically allocated variables for communication with `yylex'.  These
  401. variables include `yylval' and `yylloc'.
  402.  
  403.    The Bison declaration `%pure_parser' says that you want the parser
  404. to be reentrant.  It looks like this:
  405.  
  406.      %pure_parser
  407.  
  408.    The effect is that the two communication variables become local
  409. variables in `yyparse', and a different calling convention is used for
  410. the lexical analyzer function `yylex'.  *Note Calling Conventions for
  411. Pure Parsers: Pure Calling, for the details of this.  The variable
  412. `yynerrs' also becomes local in `yyparse' (*note The Error Reporting
  413. Function `yyerror': Error Reporting.).  The convention for calling
  414. `yyparse' itself is unchanged.
  415.  
  416. 
  417. File: bison.info,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  418.  
  419. Bison Declaration Summary
  420. -------------------------
  421.  
  422.    Here is a summary of all Bison declarations:
  423.  
  424. `%union'
  425.      Declare the collection of data types that semantic values may have
  426.      (*note The Collection of Value Types: Union Decl.).
  427.  
  428. `%token'
  429.      Declare a terminal symbol (token type name) with no precedence or
  430.      associativity specified (*note Token Type Names: Token Decl.).
  431.  
  432. `%right'
  433.      Declare a terminal symbol (token type name) that is
  434.      right-associative (*note Operator Precedence: Precedence Decl.).
  435.  
  436. `%left'
  437.      Declare a terminal symbol (token type name) that is
  438.      left-associative (*note Operator Precedence: Precedence Decl.).
  439.  
  440. `%nonassoc'
  441.      Declare a terminal symbol (token type name) that is nonassociative
  442.      (using it in a way that would be associative is a syntax error)
  443.      (*note Operator Precedence: Precedence Decl.).
  444.  
  445. `%type'
  446.      Declare the type of semantic values for a nonterminal symbol
  447.      (*note Nonterminal Symbols: Type Decl.).
  448.  
  449. `%start'
  450.      Specify the grammar's start symbol (*note The Start-Symbol: Start
  451.      Decl.).
  452.  
  453. `%expect'
  454.      Declare the expected number of shift-reduce conflicts (*note
  455.      Suppressing Conflict Warnings: Expect Decl.).
  456.  
  457. `%pure_parser'
  458.      Request a pure (reentrant) parser program (*note A Pure
  459.      (Reentrant) Parser: Pure Decl.).
  460.  
  461. `%no_lines'
  462.      Don't generate any `#line' preprocessor commands in the parser
  463.      file.  Ordinarily Bison writes these commands in the parser file
  464.      so that the C compiler and debuggers will associate errors and
  465.      object code with your source file (the grammar file).  This
  466.      directive causes them to associate errors with the parser file,
  467.      treating it an independent source file in its own right.
  468.  
  469. `%raw'
  470.      The output file `NAME.h' normally defines the tokens with
  471.      Yacc-compatible token numbers.  If this option is specified, the
  472.      internal Bison numbers are used instead.  (Yacc-compatible numbers
  473.      start at 257 except for single character tokens; Bison assigns
  474.      token numbers sequentially for all tokens starting at 3.)
  475.  
  476. `%token_table'
  477.      Generate an array of token names in the parser file.  The name of
  478.      the array is `yytname'; `yytname[I]' is the name of the token
  479.      whose internal Bison token code number is I.  The first three
  480.      elements of `yytname' are always `"$"', `"error"', and
  481.      `"$illegal"'; after these come the symbols defined in the grammar
  482.      file.
  483.  
  484.      For single-character literal tokens and literal string tokens, the
  485.      name in the table includes the single-quote or double-quote
  486.      characters: for example, `"'+'"' is a single-character literal and
  487.      `"\"<=\""' is a literal string token.  All the characters of the
  488.      literal string token appear verbatim in the string found in the
  489.      table; even double-quote characters are not escaped.  For example,
  490.      if the token consists of three characters `*"*', its string in
  491.      `yytname' contains `"*"*"'.  (In C, that would be written as
  492.      `"\"*\"*\""').
  493.  
  494.      When you specify `%token_table', Bison also generates macro
  495.      definitions for macros `YYNTOKENS', `YYNNTS', and `YYNRULES', and
  496.      `YYNSTATES':
  497.  
  498.     `YYNTOKENS'
  499.           The highest token number, plus one.
  500.  
  501.     `YYNNTS'
  502.           The number of non-terminal symbols.
  503.  
  504.     `YYNRULES'
  505.           The number of grammar rules,
  506.  
  507.     `YYNSTATES'
  508.           The number of parser states (*note Parser States::.).
  509.  
  510. 
  511. File: bison.info,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  512.  
  513. Multiple Parsers in the Same Program
  514. ====================================
  515.  
  516.    Most programs that use Bison parse only one language and therefore
  517. contain only one Bison parser.  But what if you want to parse more than
  518. one language with the same program?  Then you need to avoid a name
  519. conflict between different definitions of `yyparse', `yylval', and so
  520. on.
  521.  
  522.    The easy way to do this is to use the option `-p PREFIX' (*note
  523. Invoking Bison: Invocation.).  This renames the interface functions and
  524. variables of the Bison parser to start with PREFIX instead of `yy'.
  525. You can use this to give each parser distinct names that do not
  526. conflict.
  527.  
  528.    The precise list of symbols renamed is `yyparse', `yylex',
  529. `yyerror', `yynerrs', `yylval', `yychar' and `yydebug'.  For example,
  530. if you use `-p c', the names become `cparse', `clex', and so on.
  531.  
  532.    *All the other variables and macros associated with Bison are not
  533. renamed.* These others are not global; there is no conflict if the same
  534. name is used in different parsers.  For example, `YYSTYPE' is not
  535. renamed, but defining this in different ways in different parsers causes
  536. no trouble (*note Data Types of Semantic Values: Value Type.).
  537.  
  538.    The `-p' option works by adding macro definitions to the beginning
  539. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  540. on.  This effectively substitutes one name for the other in the entire
  541. parser file.
  542.  
  543. 
  544. File: bison.info,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  545.  
  546. Parser C-Language Interface
  547. ***************************
  548.  
  549.    The Bison parser is actually a C function named `yyparse'.  Here we
  550. describe the interface conventions of `yyparse' and the other functions
  551. that it needs to use.
  552.  
  553.    Keep in mind that the parser uses many C identifiers starting with
  554. `yy' and `YY' for internal purposes.  If you use such an identifier
  555. (aside from those in this manual) in an action or in additional C code
  556. in the grammar file, you are likely to run into trouble.
  557.  
  558. * Menu:
  559.  
  560. * Parser Function::   How to call `yyparse' and what it returns.
  561. * Lexical::           You must supply a function `yylex'
  562.                         which reads tokens.
  563. * Error Reporting::   You must supply a function `yyerror'.
  564. * Action Features::   Special features for use in actions.
  565.  
  566. 
  567. File: bison.info,  Node: Parser Function,  Next: Lexical,  Up: Interface
  568.  
  569. The Parser Function `yyparse'
  570. =============================
  571.  
  572.    You call the function `yyparse' to cause parsing to occur.  This
  573. function reads tokens, executes actions, and ultimately returns when it
  574. encounters end-of-input or an unrecoverable syntax error.  You can also
  575. write an action which directs `yyparse' to return immediately without
  576. reading further.
  577.  
  578.    The value returned by `yyparse' is 0 if parsing was successful
  579. (return is due to end-of-input).
  580.  
  581.    The value is 1 if parsing failed (return is due to a syntax error).
  582.  
  583.    In an action, you can cause immediate return from `yyparse' by using
  584. these macros:
  585.  
  586. `YYACCEPT'
  587.      Return immediately with value 0 (to report success).
  588.  
  589. `YYABORT'
  590.      Return immediately with value 1 (to report failure).
  591.  
  592. 
  593. File: bison.info,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  594.  
  595. The Lexical Analyzer Function `yylex'
  596. =====================================
  597.  
  598.    The "lexical analyzer" function, `yylex', recognizes tokens from the
  599. input stream and returns them to the parser.  Bison does not create
  600. this function automatically; you must write it so that `yyparse' can
  601. call it.  The function is sometimes referred to as a lexical scanner.
  602.  
  603.    In simple programs, `yylex' is often defined at the end of the Bison
  604. grammar file.  If `yylex' is defined in a separate source file, you
  605. need to arrange for the token-type macro definitions to be available
  606. there.  To do this, use the `-d' option when you run Bison, so that it
  607. will write these macro definitions into a separate header file
  608. `NAME.tab.h' which you can include in the other source files that need
  609. it.  *Note Invoking Bison: Invocation.
  610.  
  611. * Menu:
  612.  
  613. * Calling Convention::  How `yyparse' calls `yylex'.
  614. * Token Values::      How `yylex' must return the semantic value
  615.                         of the token it has read.
  616. * Token Positions::   How `yylex' must return the text position
  617.                         (line number, etc.) of the token, if the
  618.                         actions want that.
  619. * Pure Calling::      How the calling convention differs
  620.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  621.  
  622. 
  623. File: bison.info,  Node: Calling Convention,  Next: Token Values,  Up: Lexical
  624.  
  625. Calling Convention for `yylex'
  626. ------------------------------
  627.  
  628.    The value that `yylex' returns must be the numeric code for the type
  629. of token it has just found, or 0 for end-of-input.
  630.  
  631.    When a token is referred to in the grammar rules by a name, that name
  632. in the parser file becomes a C macro whose definition is the proper
  633. numeric code for that token type.  So `yylex' can use the name to
  634. indicate that type.  *Note Symbols::.
  635.  
  636.    When a token is referred to in the grammar rules by a character
  637. literal, the numeric code for that character is also the code for the
  638. token type.  So `yylex' can simply return that character code.  The
  639. null character must not be used this way, because its code is zero and
  640. that is what signifies end-of-input.
  641.  
  642.    Here is an example showing these things:
  643.  
  644.      yylex ()
  645.      {
  646.        ...
  647.        if (c == EOF)     /* Detect end of file. */
  648.          return 0;
  649.        ...
  650.        if (c == '+' || c == '-')
  651.          return c;      /* Assume token type for `+' is '+'. */
  652.        ...
  653.        return INT;      /* Return the type of the token. */
  654.        ...
  655.      }
  656.  
  657. This interface has been designed so that the output from the `lex'
  658. utility can be used without change as the definition of `yylex'.
  659.  
  660.    If the grammar uses literal string tokens, there are two ways that
  661. `yylex' can determine the token type codes for them:
  662.  
  663.    * If the grammar defines symbolic token names as aliases for the
  664.      literal string tokens, `yylex' can use these symbolic names like
  665.      all others.  In this case, the use of the literal string tokens in
  666.      the grammar file has no effect on `yylex'.
  667.  
  668.    * `yylex' can find the multi-character token in the `yytname' table.
  669.      The index of the token in the table is the token type's code.
  670.      The name of a multi-character token is recorded in `yytname' with a
  671.      double-quote, the token's characters, and another double-quote.
  672.      The token's characters are not escaped in any way; they appear
  673.      verbatim in the contents of the string in the table.
  674.  
  675.      Here's code for looking up a token in `yytname', assuming that the
  676.      characters of the token are stored in `token_buffer'.
  677.  
  678.           for (i = 0; i < YYNTOKENS; i++)
  679.             {
  680.               if (yytname[i] != 0
  681.                   && yytname[i][0] == '"'
  682.                   && strncmp (yytname[i] + 1, token_buffer, strlen (token_buffer))
  683.                   && yytname[i][strlen (token_buffer) + 1] == '"'
  684.                   && yytname[i][strlen (token_buffer) + 2] == 0)
  685.                 break;
  686.             }
  687.  
  688.      The `yytname' table is generated only if you use the
  689.      `%token_table' declaration.  *Note Decl Summary::.
  690.  
  691. 
  692. File: bison.info,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  693.  
  694. Semantic Values of Tokens
  695. -------------------------
  696.  
  697.    In an ordinary (nonreentrant) parser, the semantic value of the
  698. token must be stored into the global variable `yylval'.  When you are
  699. using just one data type for semantic values, `yylval' has that type.
  700. Thus, if the type is `int' (the default), you might write this in
  701. `yylex':
  702.  
  703.        ...
  704.        yylval = value;  /* Put value onto Bison stack. */
  705.        return INT;      /* Return the type of the token. */
  706.        ...
  707.  
  708.    When you are using multiple data types, `yylval''s type is a union
  709. made from the `%union' declaration (*note The Collection of Value
  710. Types: Union Decl.).  So when you store a token's value, you must use
  711. the proper member of the union.  If the `%union' declaration looks like
  712. this:
  713.  
  714.      %union {
  715.        int intval;
  716.        double val;
  717.        symrec *tptr;
  718.      }
  719.  
  720. then the code in `yylex' might look like this:
  721.  
  722.        ...
  723.        yylval.intval = value; /* Put value onto Bison stack. */
  724.        return INT;          /* Return the type of the token. */
  725.        ...
  726.  
  727. 
  728. File: bison.info,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  729.  
  730. Textual Positions of Tokens
  731. ---------------------------
  732.  
  733.    If you are using the `@N'-feature (*note Special Features for Use in
  734. Actions: Action Features.) in actions to keep track of the textual
  735. locations of tokens and groupings, then you must provide this
  736. information in `yylex'.  The function `yyparse' expects to find the
  737. textual location of a token just parsed in the global variable
  738. `yylloc'.  So `yylex' must store the proper data in that variable.  The
  739. value of `yylloc' is a structure and you need only initialize the
  740. members that are going to be used by the actions.  The four members are
  741. called `first_line', `first_column', `last_line' and `last_column'.
  742. Note that the use of this feature makes the parser noticeably slower.
  743.  
  744.    The data type of `yylloc' has the name `YYLTYPE'.
  745.  
  746. 
  747. File: bison.info,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  748.  
  749. Calling Conventions for Pure Parsers
  750. ------------------------------------
  751.  
  752.    When you use the Bison declaration `%pure_parser' to request a pure,
  753. reentrant parser, the global communication variables `yylval' and
  754. `yylloc' cannot be used.  (*Note A Pure (Reentrant) Parser: Pure Decl.)
  755. In such parsers the two global variables are replaced by pointers
  756. passed as arguments to `yylex'.  You must declare them as shown here,
  757. and pass the information back by storing it through those pointers.
  758.  
  759.      yylex (lvalp, llocp)
  760.           YYSTYPE *lvalp;
  761.           YYLTYPE *llocp;
  762.      {
  763.        ...
  764.        *lvalp = value;  /* Put value onto Bison stack.  */
  765.        return INT;      /* Return the type of the token.  */
  766.        ...
  767.      }
  768.  
  769.    If the grammar file does not use the `@' constructs to refer to
  770. textual positions, then the type `YYLTYPE' will not be defined.  In
  771. this case, omit the second argument; `yylex' will be called with only
  772. one argument.
  773.  
  774.    If you use a reentrant parser, you can optionally pass additional
  775. parameter information to it in a reentrant way.  To do so, define the
  776. macro `YYPARSE_PARAM' as a variable name.  This modifies the `yyparse'
  777. function to accept one argument, of type `void *', with that name.
  778.  
  779.    When you call `yyparse', pass the address of an object, casting the
  780. address to `void *'.  The grammar actions can refer to the contents of
  781. the object by casting the pointer value back to its proper type and
  782. then dereferencing it.  Here's an example.  Write this in the parser:
  783.  
  784.      %{
  785.      struct parser_control
  786.      {
  787.        int nastiness;
  788.        int randomness;
  789.      };
  790.      
  791.      #define YYPARSE_PARAM parm
  792.      %}
  793.  
  794. Then call the parser like this:
  795.  
  796.      struct parser_control
  797.      {
  798.        int nastiness;
  799.        int randomness;
  800.      };
  801.      
  802.      ...
  803.      
  804.      {
  805.        struct parser_control foo;
  806.        ...  /* Store proper data in `foo'.  */
  807.        value = yyparse ((void *) &foo);
  808.        ...
  809.      }
  810.  
  811. In the grammar actions, use expressions like this to refer to the data:
  812.  
  813.      ((struct parser_control *) parm)->randomness
  814.  
  815.    If you wish to pass the additional parameter data to `yylex', define
  816. the macro `YYLEX_PARAM' just like `YYPARSE_PARAM', as shown here:
  817.  
  818.      %{
  819.      struct parser_control
  820.      {
  821.        int nastiness;
  822.        int randomness;
  823.      };
  824.      
  825.      #define YYPARSE_PARAM parm
  826.      #define YYLEX_PARAM parm
  827.      %}
  828.  
  829.    You should then define `yylex' to accept one additional
  830. argument--the value of `parm'.  (This makes either two or three
  831. arguments in total, depending on whether an argument of type `YYLTYPE'
  832. is passed.)  You can declare the argument as a pointer to the proper
  833. object type, or you can declare it as `void *' and access the contents
  834. as shown above.
  835.  
  836.    You can use `%pure_parser' to request a reentrant parser without
  837. also using `YYPARSE_PARAM'.  Then you should call `yyparse' with no
  838. arguments, as usual.
  839.  
  840. 
  841. File: bison.info,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  842.  
  843. The Error Reporting Function `yyerror'
  844. ======================================
  845.  
  846.    The Bison parser detects a "parse error" or "syntax error" whenever
  847. it reads a token which cannot satisfy any syntax rule.  A action in the
  848. grammar can also explicitly proclaim an error, using the macro
  849. `YYERROR' (*note Special Features for Use in Actions: Action Features.).
  850.  
  851.    The Bison parser expects to report the error by calling an error
  852. reporting function named `yyerror', which you must supply.  It is
  853. called by `yyparse' whenever a syntax error is found, and it receives
  854. one argument.  For a parse error, the string is normally
  855. `"parse error"'.
  856.  
  857.    If you define the macro `YYERROR_VERBOSE' in the Bison declarations
  858. section (*note The Bison Declarations Section: Bison Declarations.),
  859. then Bison provides a more verbose and specific error message string
  860. instead of just plain `"parse error"'.  It doesn't matter what
  861. definition you use for `YYERROR_VERBOSE', just whether you define it.
  862.  
  863.    The parser can detect one other kind of error: stack overflow.  This
  864. happens when the input contains constructions that are very deeply
  865. nested.  It isn't likely you will encounter this, since the Bison
  866. parser extends its stack automatically up to a very large limit.  But
  867. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  868. except that the argument string is `"parser stack overflow"'.
  869.  
  870.    The following definition suffices in simple programs:
  871.  
  872.      yyerror (s)
  873.           char *s;
  874.      {
  875.        fprintf (stderr, "%s\n", s);
  876.      }
  877.  
  878.    After `yyerror' returns to `yyparse', the latter will attempt error
  879. recovery if you have written suitable error recovery grammar rules
  880. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  881. immediately return 1.
  882.  
  883.    The variable `yynerrs' contains the number of syntax errors
  884. encountered so far.  Normally this variable is global; but if you
  885. request a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.)
  886. then it is a local variable which only the actions can access.
  887.  
  888. 
  889. File: bison.info,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  890.  
  891. Special Features for Use in Actions
  892. ===================================
  893.  
  894.    Here is a table of Bison constructs, variables and macros that are
  895. useful in actions.
  896.  
  897. `$$'
  898.      Acts like a variable that contains the semantic value for the
  899.      grouping made by the current rule.  *Note Actions::.
  900.  
  901. `$N'
  902.      Acts like a variable that contains the semantic value for the Nth
  903.      component of the current rule.  *Note Actions::.
  904.  
  905. `$<TYPEALT>$'
  906.      Like `$$' but specifies alternative TYPEALT in the union specified
  907.      by the `%union' declaration.  *Note Data Types of Values in
  908.      Actions: Action Types.
  909.  
  910. `$<TYPEALT>N'
  911.      Like `$N' but specifies alternative TYPEALT in the union specified
  912.      by the `%union' declaration.  *Note Data Types of Values in
  913.      Actions: Action Types.
  914.  
  915. `YYABORT;'
  916.      Return immediately from `yyparse', indicating failure.  *Note The
  917.      Parser Function `yyparse': Parser Function.
  918.  
  919. `YYACCEPT;'
  920.      Return immediately from `yyparse', indicating success.  *Note The
  921.      Parser Function `yyparse': Parser Function.
  922.  
  923. `YYBACKUP (TOKEN, VALUE);'
  924.      Unshift a token.  This macro is allowed only for rules that reduce
  925.      a single value, and only when there is no look-ahead token.  It
  926.      installs a look-ahead token with token type TOKEN and semantic
  927.      value VALUE; then it discards the value that was going to be
  928.      reduced by this rule.
  929.  
  930.      If the macro is used when it is not valid, such as when there is a
  931.      look-ahead token already, then it reports a syntax error with a
  932.      message `cannot back up' and performs ordinary error recovery.
  933.  
  934.      In either case, the rest of the action is not executed.
  935.  
  936. `YYEMPTY'
  937.      Value stored in `yychar' when there is no look-ahead token.
  938.  
  939. `YYERROR;'
  940.      Cause an immediate syntax error.  This statement initiates error
  941.      recovery just as if the parser itself had detected an error;
  942.      however, it does not call `yyerror', and does not print any
  943.      message.  If you want to print an error message, call `yyerror'
  944.      explicitly before the `YYERROR;' statement.  *Note Error
  945.      Recovery::.
  946.  
  947. `YYRECOVERING'
  948.      This macro stands for an expression that has the value 1 when the
  949.      parser is recovering from a syntax error, and 0 the rest of the
  950.      time.  *Note Error Recovery::.
  951.  
  952. `yychar'
  953.      Variable containing the current look-ahead token.  (In a pure
  954.      parser, this is actually a local variable within `yyparse'.)  When
  955.      there is no look-ahead token, the value `YYEMPTY' is stored in the
  956.      variable.  *Note Look-Ahead Tokens: Look-Ahead.
  957.  
  958. `yyclearin;'
  959.      Discard the current look-ahead token.  This is useful primarily in
  960.      error rules.  *Note Error Recovery::.
  961.  
  962. `yyerrok;'
  963.      Resume generating error messages immediately for subsequent syntax
  964.      errors.  This is useful primarily in error rules.  *Note Error
  965.      Recovery::.
  966.  
  967. `@N'
  968.      Acts like a structure variable containing information on the line
  969.      numbers and column numbers of the Nth component of the current
  970.      rule.  The structure has four members, like this:
  971.  
  972.           struct {
  973.             int first_line, last_line;
  974.             int first_column, last_column;
  975.           };
  976.  
  977.      Thus, to get the starting line number of the third component, use
  978.      `@3.first_line'.
  979.  
  980.      In order for the members of this structure to contain valid
  981.      information, you must make `yylex' supply this information about
  982.      each token.  If you need only certain members, then `yylex' need
  983.      only fill in those members.
  984.  
  985.      The use of this feature makes the parser noticeably slower.
  986.  
  987. 
  988. File: bison.info,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  989.  
  990. The Bison Parser Algorithm
  991. **************************
  992.  
  993.    As Bison reads tokens, it pushes them onto a stack along with their
  994. semantic values.  The stack is called the "parser stack".  Pushing a
  995. token is traditionally called "shifting".
  996.  
  997.    For example, suppose the infix calculator has read `1 + 5 *', with a
  998. `3' to come.  The stack will have four elements, one for each token
  999. that was shifted.
  1000.  
  1001.    But the stack does not always have an element for each token read.
  1002. When the last N tokens and groupings shifted match the components of a
  1003. grammar rule, they can be combined according to that rule.  This is
  1004. called "reduction".  Those tokens and groupings are replaced on the
  1005. stack by a single grouping whose symbol is the result (left hand side)
  1006. of that rule.  Running the rule's action is part of the process of
  1007. reduction, because this is what computes the semantic value of the
  1008. resulting grouping.
  1009.  
  1010.    For example, if the infix calculator's parser stack contains this:
  1011.  
  1012.      1 + 5 * 3
  1013.  
  1014. and the next input token is a newline character, then the last three
  1015. elements can be reduced to 15 via the rule:
  1016.  
  1017.      expr: expr '*' expr;
  1018.  
  1019. Then the stack contains just these three elements:
  1020.  
  1021.      1 + 15
  1022.  
  1023. At this point, another reduction can be made, resulting in the single
  1024. value 16.  Then the newline token can be shifted.
  1025.  
  1026.    The parser tries, by shifts and reductions, to reduce the entire
  1027. input down to a single grouping whose symbol is the grammar's
  1028. start-symbol (*note Languages and Context-Free Grammars: Language and
  1029. Grammar.).
  1030.  
  1031.    This kind of parser is known in the literature as a bottom-up parser.
  1032.  
  1033. * Menu:
  1034.  
  1035. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  1036. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  1037. * Precedence::        Operator precedence works by resolving conflicts.
  1038. * Contextual Precedence::  When an operator's precedence depends on context.
  1039. * Parser States::     The parser is a finite-state-machine with stack.
  1040. * Reduce/Reduce::     When two rules are applicable in the same situation.
  1041. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  1042. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  1043.  
  1044. 
  1045. File: bison.info,  Node: Look-Ahead,  Next: Shift/Reduce,  Up: Algorithm
  1046.  
  1047. Look-Ahead Tokens
  1048. =================
  1049.  
  1050.    The Bison parser does *not* always reduce immediately as soon as the
  1051. last N tokens and groupings match a rule.  This is because such a
  1052. simple strategy is inadequate to handle most languages.  Instead, when a
  1053. reduction is possible, the parser sometimes "looks ahead" at the next
  1054. token in order to decide what to do.
  1055.  
  1056.    When a token is read, it is not immediately shifted; first it
  1057. becomes the "look-ahead token", which is not on the stack.  Now the
  1058. parser can perform one or more reductions of tokens and groupings on
  1059. the stack, while the look-ahead token remains off to the side.  When no
  1060. more reductions should take place, the look-ahead token is shifted onto
  1061. the stack.  This does not mean that all possible reductions have been
  1062. done; depending on the token type of the look-ahead token, some rules
  1063. may choose to delay their application.
  1064.  
  1065.    Here is a simple case where look-ahead is needed.  These three rules
  1066. define expressions which contain binary addition operators and postfix
  1067. unary factorial operators (`!'), and allow parentheses for grouping.
  1068.  
  1069.      expr:     term '+' expr
  1070.              | term
  1071.              ;
  1072.      
  1073.      term:     '(' expr ')'
  1074.              | term '!'
  1075.              | NUMBER
  1076.              ;
  1077.  
  1078.    Suppose that the tokens `1 + 2' have been read and shifted; what
  1079. should be done?  If the following token is `)', then the first three
  1080. tokens must be reduced to form an `expr'.  This is the only valid
  1081. course, because shifting the `)' would produce a sequence of symbols
  1082. `term ')'', and no rule allows this.
  1083.  
  1084.    If the following token is `!', then it must be shifted immediately so
  1085. that `2 !' can be reduced to make a `term'.  If instead the parser were
  1086. to reduce before shifting, `1 + 2' would become an `expr'.  It would
  1087. then be impossible to shift the `!' because doing so would produce on
  1088. the stack the sequence of symbols `expr '!''.  No rule allows that
  1089. sequence.
  1090.  
  1091.    The current look-ahead token is stored in the variable `yychar'.
  1092. *Note Special Features for Use in Actions: Action Features.
  1093.  
  1094. 
  1095. File: bison.info,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  1096.  
  1097. Shift/Reduce Conflicts
  1098. ======================
  1099.  
  1100.    Suppose we are parsing a language which has if-then and if-then-else
  1101. statements, with a pair of rules like this:
  1102.  
  1103.      if_stmt:
  1104.                IF expr THEN stmt
  1105.              | IF expr THEN stmt ELSE stmt
  1106.              ;
  1107.  
  1108. Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  1109. specific keyword tokens.
  1110.  
  1111.    When the `ELSE' token is read and becomes the look-ahead token, the
  1112. contents of the stack (assuming the input is valid) are just right for
  1113. reduction by the first rule.  But it is also legitimate to shift the
  1114. `ELSE', because that would lead to eventual reduction by the second
  1115. rule.
  1116.  
  1117.    This situation, where either a shift or a reduction would be valid,
  1118. is called a "shift/reduce conflict".  Bison is designed to resolve
  1119. these conflicts by choosing to shift, unless otherwise directed by
  1120. operator precedence declarations.  To see the reason for this, let's
  1121. contrast it with the other alternative.
  1122.  
  1123.    Since the parser prefers to shift the `ELSE', the result is to attach
  1124. the else-clause to the innermost if-statement, making these two inputs
  1125. equivalent:
  1126.  
  1127.      if x then if y then win (); else lose;
  1128.      
  1129.      if x then do; if y then win (); else lose; end;
  1130.  
  1131.    But if the parser chose to reduce when possible rather than shift,
  1132. the result would be to attach the else-clause to the outermost
  1133. if-statement, making these two inputs equivalent:
  1134.  
  1135.      if x then if y then win (); else lose;
  1136.      
  1137.      if x then do; if y then win (); end; else lose;
  1138.  
  1139.    The conflict exists because the grammar as written is ambiguous:
  1140. either parsing of the simple nested if-statement is legitimate.  The
  1141. established convention is that these ambiguities are resolved by
  1142. attaching the else-clause to the innermost if-statement; this is what
  1143. Bison accomplishes by choosing to shift rather than reduce.  (It would
  1144. ideally be cleaner to write an unambiguous grammar, but that is very
  1145. hard to do in this case.) This particular ambiguity was first
  1146. encountered in the specifications of Algol 60 and is called the
  1147. "dangling `else'" ambiguity.
  1148.  
  1149.    To avoid warnings from Bison about predictable, legitimate
  1150. shift/reduce conflicts, use the `%expect N' declaration.  There will be
  1151. no warning as long as the number of shift/reduce conflicts is exactly N.
  1152. *Note Suppressing Conflict Warnings: Expect Decl.
  1153.  
  1154.    The definition of `if_stmt' above is solely to blame for the
  1155. conflict, but the conflict does not actually appear without additional
  1156. rules.  Here is a complete Bison input file that actually manifests the
  1157. conflict:
  1158.  
  1159.      %token IF THEN ELSE variable
  1160.      %%
  1161.      stmt:     expr
  1162.              | if_stmt
  1163.              ;
  1164.      
  1165.      if_stmt:
  1166.                IF expr THEN stmt
  1167.              | IF expr THEN stmt ELSE stmt
  1168.              ;
  1169.      
  1170.      expr:     variable
  1171.              ;
  1172.  
  1173. 
  1174. File: bison.info,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  1175.  
  1176. Operator Precedence
  1177. ===================
  1178.  
  1179.    Another situation where shift/reduce conflicts appear is in
  1180. arithmetic expressions.  Here shifting is not always the preferred
  1181. resolution; the Bison declarations for operator precedence allow you to
  1182. specify when to shift and when to reduce.
  1183.  
  1184. * Menu:
  1185.  
  1186. * Why Precedence::    An example showing why precedence is needed.
  1187. * Using Precedence::  How to specify precedence in Bison grammars.
  1188. * Precedence Examples::  How these features are used in the previous example.
  1189. * How Precedence::    How they work.
  1190.  
  1191. 
  1192. File: bison.info,  Node: Why Precedence,  Next: Using Precedence,  Up: Precedence
  1193.  
  1194. When Precedence is Needed
  1195. -------------------------
  1196.  
  1197.    Consider the following ambiguous grammar fragment (ambiguous because
  1198. the input `1 - 2 * 3' can be parsed in two different ways):
  1199.  
  1200.      expr:     expr '-' expr
  1201.              | expr '*' expr
  1202.              | expr '<' expr
  1203.              | '(' expr ')'
  1204.              ...
  1205.              ;
  1206.  
  1207. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  1208. reduce them via the rule for the addition operator?  It depends on the
  1209. next token.  Of course, if the next token is `)', we must reduce;
  1210. shifting is invalid because no single rule can reduce the token
  1211. sequence `- 2 )' or anything starting with that.  But if the next token
  1212. is `*' or `<', we have a choice: either shifting or reduction would
  1213. allow the parse to complete, but with different results.
  1214.  
  1215.    To decide which one Bison should do, we must consider the results.
  1216. If the next operator token OP is shifted, then it must be reduced first
  1217. in order to permit another opportunity to reduce the sum.  The result
  1218. is (in effect) `1 - (2 OP 3)'.  On the other hand, if the subtraction
  1219. is reduced before shifting OP, the result is `(1 - 2) OP 3'.  Clearly,
  1220. then, the choice of shift or reduce should depend on the relative
  1221. precedence of the operators `-' and OP: `*' should be shifted first,
  1222. but not `<'.
  1223.  
  1224.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  1225. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  1226. former, which is called "left association".  The latter alternative,
  1227. "right association", is desirable for assignment operators.  The choice
  1228. of left or right association is a matter of whether the parser chooses
  1229. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  1230. token is `-': shifting makes right-associativity.
  1231.  
  1232. 
  1233. File: bison.info,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  1234.  
  1235. Specifying Operator Precedence
  1236. ------------------------------
  1237.  
  1238.    Bison allows you to specify these choices with the operator
  1239. precedence declarations `%left' and `%right'.  Each such declaration
  1240. contains a list of tokens, which are operators whose precedence and
  1241. associativity is being declared.  The `%left' declaration makes all
  1242. those operators left-associative and the `%right' declaration makes
  1243. them right-associative.  A third alternative is `%nonassoc', which
  1244. declares that it is a syntax error to find the same operator twice "in a
  1245. row".
  1246.  
  1247.    The relative precedence of different operators is controlled by the
  1248. order in which they are declared.  The first `%left' or `%right'
  1249. declaration in the file declares the operators whose precedence is
  1250. lowest, the next such declaration declares the operators whose
  1251. precedence is a little higher, and so on.
  1252.  
  1253. 
  1254. File: bison.info,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  1255.  
  1256. Precedence Examples
  1257. -------------------
  1258.  
  1259.    In our example, we would want the following declarations:
  1260.  
  1261.      %left '<'
  1262.      %left '-'
  1263.      %left '*'
  1264.  
  1265.    In a more complete example, which supports other operators as well,
  1266. we would declare them in groups of equal precedence.  For example,
  1267. `'+'' is declared with `'-'':
  1268.  
  1269.      %left '<' '>' '=' NE LE GE
  1270.      %left '+' '-'
  1271.      %left '*' '/'
  1272.  
  1273. (Here `NE' and so on stand for the operators for "not equal" and so on.
  1274. We assume that these tokens are more than one character long and
  1275. therefore are represented by names, not character literals.)
  1276.  
  1277. 
  1278. File: bison.info,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  1279.  
  1280. How Precedence Works
  1281. --------------------
  1282.  
  1283.    The first effect of the precedence declarations is to assign
  1284. precedence levels to the terminal symbols declared.  The second effect
  1285. is to assign precedence levels to certain rules: each rule gets its
  1286. precedence from the last terminal symbol mentioned in the components.
  1287. (You can also specify explicitly the precedence of a rule.  *Note
  1288. Context-Dependent Precedence: Contextual Precedence.)
  1289.  
  1290.    Finally, the resolution of conflicts works by comparing the
  1291. precedence of the rule being considered with that of the look-ahead
  1292. token.  If the token's precedence is higher, the choice is to shift.
  1293. If the rule's precedence is higher, the choice is to reduce.  If they
  1294. have equal precedence, the choice is made based on the associativity of
  1295. that precedence level.  The verbose output file made by `-v' (*note
  1296. Invoking Bison: Invocation.) says how each conflict was resolved.
  1297.  
  1298.    Not all rules and not all tokens have precedence.  If either the
  1299. rule or the look-ahead token has no precedence, then the default is to
  1300. shift.
  1301.  
  1302.