home *** CD-ROM | disk | FTP | other *** search
/ Frozen Fish 1: Amiga / FrozenFish-Apr94.iso / bbs / gnu / bison-1.22-bin.lha / info / bison.info-2 (.txt) < prev    next >
GNU Info File  |  1994-02-21  |  48KB  |  1,024 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.    This file documents the Bison parser generator.
  4.    Copyright (C) 1988, 1989, 1990, 1991, 1992 Free Software Foundation,
  5.    Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8.    Permission is granted to copy and distribute modified versions of
  9. this manual under the conditions for verbatim copying, provided also
  10. that the sections entitled "GNU General Public License" and "Conditions
  11. for Using Bison" are included exactly as in the original, and provided
  12. that the entire resulting derived work is distributed under the terms
  13. of a permission notice identical to this one.
  14.    Permission is granted to copy and distribute translations of this
  15. manual into another language, under the above conditions for modified
  16. versions, except that the sections entitled "GNU General Public
  17. License", "Conditions for Using Bison" and this permission notice may be
  18. included in translations approved by the Free Software Foundation
  19. instead of in the original English.
  20. File: bison.info,  Node: Rpcalc Rules,  Next: Rpcalc Lexer,  Prev: Rpcalc Decls,  Up: RPN Calc
  21. Grammar Rules for `rpcalc'
  22. --------------------------
  23.    Here are the grammar rules for the reverse polish notation
  24. calculator.
  25.      input:    /* empty */
  26.              | input line
  27.      ;
  28.      
  29.      line:     '\n'
  30.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  31.      ;
  32.      
  33.      exp:      NUM             { $$ = $1;         }
  34.              | exp exp '+'     { $$ = $1 + $2;    }
  35.              | exp exp '-'     { $$ = $1 - $2;    }
  36.              | exp exp '*'     { $$ = $1 * $2;    }
  37.              | exp exp '/'     { $$ = $1 / $2;    }
  38.            /* Exponentiation */
  39.              | exp exp '^'     { $$ = pow ($1, $2); }
  40.            /* Unary minus    */
  41.              | exp 'n'         { $$ = -$1;        }
  42.      ;
  43.      %%
  44.    The groupings of the rpcalc "language" defined here are the
  45. expression (given the name `exp'), the line of input (`line'), and the
  46. complete input transcript (`input').  Each of these nonterminal symbols
  47. has several alternate rules, joined by the `|' punctuator which is read
  48. as "or".  The following sections explain what these rules mean.
  49.    The semantics of the language is determined by the actions taken
  50. when a grouping is recognized.  The actions are the C code that appears
  51. inside braces.  *Note Actions::.
  52.    You must specify these actions in C, but Bison provides the means for
  53. passing semantic values between the rules.  In each action, the
  54. pseudo-variable `$$' stands for the semantic value for the grouping
  55. that the rule is going to construct.  Assigning a value to `$$' is the
  56. main job of most actions.  The semantic values of the components of the
  57. rule are referred to as `$1', `$2', and so on.
  58. * Menu:
  59. * Rpcalc Input::
  60. * Rpcalc Line::
  61. * Rpcalc Expr::
  62. File: bison.info,  Node: Rpcalc Input,  Next: Rpcalc Line,  Up: Rpcalc Rules
  63. Explanation of `input'
  64. ......................
  65.    Consider the definition of `input':
  66.      input:    /* empty */
  67.              | input line
  68.      ;
  69.    This definition reads as follows: "A complete input is either an
  70. empty string, or a complete input followed by an input line".  Notice
  71. that "complete input" is defined in terms of itself.  This definition
  72. is said to be "left recursive" since `input' appears always as the
  73. leftmost symbol in the sequence.  *Note Recursive Rules: Recursion.
  74.    The first alternative is empty because there are no symbols between
  75. the colon and the first `|'; this means that `input' can match an empty
  76. string of input (no tokens).  We write the rules this way because it is
  77. legitimate to type `Ctrl-d' right after you start the calculator.  It's
  78. conventional to put an empty alternative first and write the comment
  79. `/* empty */' in it.
  80.    The second alternate rule (`input line') handles all nontrivial
  81. input.  It means, "After reading any number of lines, read one more
  82. line if possible."  The left recursion makes this rule into a loop.
  83. Since the first alternative matches empty input, the loop can be
  84. executed zero or more times.
  85.    The parser function `yyparse' continues to process input until a
  86. grammatical error is seen or the lexical analyzer says there are no more
  87. input tokens; we will arrange for the latter to happen at end of file.
  88. File: bison.info,  Node: Rpcalc Line,  Next: Rpcalc Expr,  Prev: Rpcalc Input,  Up: Rpcalc Rules
  89. Explanation of `line'
  90. .....................
  91.    Now consider the definition of `line':
  92.      line:     '\n'
  93.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  94.      ;
  95.    The first alternative is a token which is a newline character; this
  96. means that rpcalc accepts a blank line (and ignores it, since there is
  97. no action).  The second alternative is an expression followed by a
  98. newline.  This is the alternative that makes rpcalc useful.  The
  99. semantic value of the `exp' grouping is the value of `$1' because the
  100. `exp' in question is the first symbol in the alternative.  The action
  101. prints this value, which is the result of the computation the user
  102. asked for.
  103.    This action is unusual because it does not assign a value to `$$'.
  104. As a consequence, the semantic value associated with the `line' is
  105. uninitialized (its value will be unpredictable).  This would be a bug if
  106. that value were ever used, but we don't use it: once rpcalc has printed
  107. the value of the user's input line, that value is no longer needed.
  108. File: bison.info,  Node: Rpcalc Expr,  Prev: Rpcalc Line,  Up: Rpcalc Rules
  109. Explanation of `expr'
  110. .....................
  111.    The `exp' grouping has several rules, one for each kind of
  112. expression.  The first rule handles the simplest expressions: those
  113. that are just numbers.  The second handles an addition-expression,
  114. which looks like two expressions followed by a plus-sign.  The third
  115. handles subtraction, and so on.
  116.      exp:      NUM
  117.              | exp exp '+'     { $$ = $1 + $2;    }
  118.              | exp exp '-'     { $$ = $1 - $2;    }
  119.              ...
  120.              ;
  121.    We have used `|' to join all the rules for `exp', but we could
  122. equally well have written them separately:
  123.      exp:      NUM ;
  124.      exp:      exp exp '+'     { $$ = $1 + $2;    } ;
  125.      exp:      exp exp '-'     { $$ = $1 - $2;    } ;
  126.              ...
  127.    Most of the rules have actions that compute the value of the
  128. expression in terms of the value of its parts.  For example, in the
  129. rule for addition, `$1' refers to the first component `exp' and `$2'
  130. refers to the second one.  The third component, `'+'', has no meaningful
  131. associated semantic value, but if it had one you could refer to it as
  132. `$3'.  When `yyparse' recognizes a sum expression using this rule, the
  133. sum of the two subexpressions' values is produced as the value of the
  134. entire expression.  *Note Actions::.
  135.    You don't have to give an action for every rule.  When a rule has no
  136. action, Bison by default copies the value of `$1' into `$$'.  This is
  137. what happens in the first rule (the one that uses `NUM').
  138.    The formatting shown here is the recommended convention, but Bison
  139. does not require it.  You can add or change whitespace as much as you
  140. wish.  For example, this:
  141.      exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  142. means the same thing as this:
  143.      exp:      NUM
  144.              | exp exp '+'    { $$ = $1 + $2; }
  145.              | ...
  146. The latter, however, is much more readable.
  147. File: bison.info,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Rules,  Up: RPN Calc
  148. The `rpcalc' Lexical Analyzer
  149. -----------------------------
  150.    The lexical analyzer's job is low-level parsing: converting
  151. characters or sequences of characters into tokens.  The Bison parser
  152. gets its tokens by calling the lexical analyzer.  *Note The Lexical
  153. Analyzer Function `yylex': Lexical.
  154.    Only a simple lexical analyzer is needed for the RPN calculator.
  155. This lexical analyzer skips blanks and tabs, then reads in numbers as
  156. `double' and returns them as `NUM' tokens.  Any other character that
  157. isn't part of a number is a separate token.  Note that the token-code
  158. for such a single-character token is the character itself.
  159.    The return value of the lexical analyzer function is a numeric code
  160. which represents a token type.  The same text used in Bison rules to
  161. stand for this token type is also a C expression for the numeric code
  162. for the type.  This works in two ways.  If the token type is a
  163. character literal, then its numeric code is the ASCII code for that
  164. character; you can use the same character literal in the lexical
  165. analyzer to express the number.  If the token type is an identifier,
  166. that identifier is defined by Bison as a C macro whose definition is
  167. the appropriate number.  In this example, therefore, `NUM' becomes a
  168. macro for `yylex' to use.
  169.    The semantic value of the token (if it has one) is stored into the
  170. global variable `yylval', which is where the Bison parser will look for
  171. it.  (The C data type of `yylval' is `YYSTYPE', which was defined at
  172. the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
  173. Decls..)
  174.    A token type code of zero is returned if the end-of-file is
  175. encountered.  (Bison recognizes any nonpositive value as indicating the
  176. end of the input.)
  177.    Here is the code for the lexical analyzer:
  178.      /* Lexical analyzer returns a double floating point
  179.         number on the stack and the token NUM, or the ASCII
  180.         character read if not a number.  Skips all blanks
  181.         and tabs, returns 0 for EOF. */
  182.      
  183.      #include <ctype.h>
  184.      
  185.      yylex ()
  186.      {
  187.        int c;
  188.      
  189.        /* skip white space  */
  190.        while ((c = getchar ()) == ' ' || c == '\t')
  191.          ;
  192.        /* process numbers   */
  193.        if (c == '.' || isdigit (c))
  194.          {
  195.            ungetc (c, stdin);
  196.            scanf ("%lf", &yylval);
  197.            return NUM;
  198.          }
  199.        /* return end-of-file  */
  200.        if (c == EOF)
  201.          return 0;
  202.        /* return single chars */
  203.        return c;
  204.      }
  205. File: bison.info,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  206. The Controlling Function
  207. ------------------------
  208.    In keeping with the spirit of this example, the controlling function
  209. is kept to the bare minimum.  The only requirement is that it call
  210. `yyparse' to start the process of parsing.
  211.      main ()
  212.      {
  213.        yyparse ();
  214.      }
  215. File: bison.info,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  216. The Error Reporting Routine
  217. ---------------------------
  218.    When `yyparse' detects a syntax error, it calls the error reporting
  219. function `yyerror' to print an error message (usually but not always
  220. `"parse error"').  It is up to the programmer to supply `yyerror'
  221. (*note Parser C-Language Interface: Interface.), so here is the
  222. definition we will use:
  223.      #include <stdio.h>
  224.      
  225.      yyerror (s)  /* Called by yyparse on error */
  226.           char *s;
  227.      {
  228.        printf ("%s\n", s);
  229.      }
  230.    After `yyerror' returns, the Bison parser may recover from the error
  231. and continue parsing if the grammar contains a suitable error rule
  232. (*note Error Recovery::.).  Otherwise, `yyparse' returns nonzero.  We
  233. have not written any error rules in this example, so any invalid input
  234. will cause the calculator program to exit.  This is not clean behavior
  235. for a real calculator, but it is adequate in the first example.
  236. File: bison.info,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  237. Running Bison to Make the Parser
  238. --------------------------------
  239.    Before running Bison to produce a parser, we need to decide how to
  240. arrange all the source code in one or more source files.  For such a
  241. simple example, the easiest thing is to put everything in one file.
  242. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  243. "additional C code" section of the file (*note The Overall Layout of a
  244. Bison Grammar: Grammar Layout.).
  245.    For a large project, you would probably have several source files,
  246. and use `make' to arrange to recompile them.
  247.    With all the source in a single file, you use the following command
  248. to convert it into a parser file:
  249.      bison FILE_NAME.y
  250. In this example the file was called `rpcalc.y' (for "Reverse Polish
  251. CALCulator").  Bison produces a file named `FILE_NAME.tab.c', removing
  252. the `.y' from the original file name. The file output by Bison contains
  253. the source code for `yyparse'.  The additional functions in the input
  254. file (`yylex', `yyerror' and `main') are copied verbatim to the output.
  255. File: bison.info,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  256. Compiling the Parser File
  257. -------------------------
  258.    Here is how to compile and run the parser file:
  259.      # List files in current directory.
  260.      % ls
  261.      rpcalc.tab.c  rpcalc.y
  262.      
  263.      # Compile the Bison parser.
  264.      # `-lm' tells compiler to search math library for `pow'.
  265.      % cc rpcalc.tab.c -lm -o rpcalc
  266.      
  267.      # List files again.
  268.      % ls
  269.      rpcalc  rpcalc.tab.c  rpcalc.y
  270.    The file `rpcalc' now contains the executable code.  Here is an
  271. example session using `rpcalc'.
  272.      % rpcalc
  273.      4 9 +
  274.      13
  275.      3 7 + 3 4 5 *+-
  276.      -13
  277.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  278.      13
  279.      5 6 / 4 n +
  280.      -3.166666667
  281.      3 4 ^                            Exponentiation
  282.      81
  283.      ^D                               End-of-file indicator
  284.      %
  285. File: bison.info,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Examples
  286. Infix Notation Calculator: `calc'
  287. =================================
  288.    We now modify rpcalc to handle infix operators instead of postfix.
  289. Infix notation involves the concept of operator precedence and the need
  290. for parentheses nested to arbitrary depth.  Here is the Bison code for
  291. `calc.y', an infix desk-top calculator.
  292.      /* Infix notation calculator--calc */
  293.      
  294.      %{
  295.      #define YYSTYPE double
  296.      #include <math.h>
  297.      %}
  298.      
  299.      /* BISON Declarations */
  300.      %token NUM
  301.      %left '-' '+'
  302.      %left '*' '/'
  303.      %left NEG     /* negation--unary minus */
  304.      %right '^'    /* exponentiation        */
  305.      
  306.      /* Grammar follows */
  307.      %%
  308.      input:    /* empty string */
  309.              | input line
  310.      ;
  311.      
  312.      line:     '\n'
  313.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  314.      ;
  315.      
  316.      exp:      NUM                { $$ = $1;         }
  317.              | exp '+' exp        { $$ = $1 + $3;    }
  318.              | exp '-' exp        { $$ = $1 - $3;    }
  319.              | exp '*' exp        { $$ = $1 * $3;    }
  320.              | exp '/' exp        { $$ = $1 / $3;    }
  321.              | '-' exp  %prec NEG { $$ = -$2;        }
  322.              | exp '^' exp        { $$ = pow ($1, $3); }
  323.              | '(' exp ')'        { $$ = $2;         }
  324.      ;
  325.      %%
  326. The functions `yylex', `yyerror' and `main' can be the same as before.
  327.    There are two important new features shown in this code.
  328.    In the second section (Bison declarations), `%left' declares token
  329. types and says they are left-associative operators.  The declarations
  330. `%left' and `%right' (right associativity) take the place of `%token'
  331. which is used to declare a token type name without associativity.
  332. (These tokens are single-character literals, which ordinarily don't
  333. need to be declared.  We declare them here to specify the
  334. associativity.)
  335.    Operator precedence is determined by the line ordering of the
  336. declarations; the higher the line number of the declaration (lower on
  337. the page or screen), the higher the precedence.  Hence, exponentiation
  338. has the highest precedence, unary minus (`NEG') is next, followed by
  339. `*' and `/', and so on.  *Note Operator Precedence: Precedence.
  340.    The other important new feature is the `%prec' in the grammar section
  341. for the unary minus operator.  The `%prec' simply instructs Bison that
  342. the rule `| '-' exp' has the same precedence as `NEG'--in this case the
  343. next-to-highest.  *Note Context-Dependent Precedence: Contextual
  344. Precedence.
  345.    Here is a sample run of `calc.y':
  346.      % calc
  347.      4 + 4.5 - (34/(8*3+-3))
  348.      6.880952381
  349.      -56 + 2
  350.      -54
  351.      3 ^ 2
  352.      9
  353. File: bison.info,  Node: Simple Error Recovery,  Next: Multi-function Calc,  Prev: Infix Calc,  Up: Examples
  354. Simple Error Recovery
  355. =====================
  356.    Up to this point, this manual has not addressed the issue of "error
  357. recovery"--how to continue parsing after the parser detects a syntax
  358. error.  All we have handled is error reporting with `yyerror'.  Recall
  359. that by default `yyparse' returns after calling `yyerror'.  This means
  360. that an erroneous input line causes the calculator program to exit.
  361. Now we show how to rectify this deficiency.
  362.    The Bison language itself includes the reserved word `error', which
  363. may be included in the grammar rules.  In the example below it has been
  364. added to one of the alternatives for `line':
  365.      line:     '\n'
  366.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  367.              | error '\n' { yyerrok;                  }
  368.      ;
  369.    This addition to the grammar allows for simple error recovery in the
  370. event of a parse error.  If an expression that cannot be evaluated is
  371. read, the error will be recognized by the third rule for `line', and
  372. parsing will continue.  (The `yyerror' function is still called upon to
  373. print its message as well.)  The action executes the statement
  374. `yyerrok', a macro defined automatically by Bison; its meaning is that
  375. error recovery is complete (*note Error Recovery::.).  Note the
  376. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  377.    This form of error recovery deals with syntax errors.  There are
  378. other kinds of errors; for example, division by zero, which raises an
  379. exception signal that is normally fatal.  A real calculator program
  380. must handle this signal and use `longjmp' to return to `main' and
  381. resume parsing input lines; it would also have to discard the rest of
  382. the current line of input.  We won't discuss this issue further because
  383. it is not specific to Bison programs.
  384. File: bison.info,  Node: Multi-function Calc,  Next: Exercises,  Prev: Simple Error Recovery,  Up: Examples
  385. Multi-Function Calculator: `mfcalc'
  386. ===================================
  387.    Now that the basics of Bison have been discussed, it is time to move
  388. on to a more advanced problem.  The above calculators provided only five
  389. functions, `+', `-', `*', `/' and `^'.  It would be nice to have a
  390. calculator that provides other mathematical functions such as `sin',
  391. `cos', etc.
  392.    It is easy to add new operators to the infix calculator as long as
  393. they are only single-character literals.  The lexical analyzer `yylex'
  394. passes back all non-number characters as tokens, so new grammar rules
  395. suffice for adding a new operator.  But we want something more
  396. flexible: built-in functions whose syntax has this form:
  397.      FUNCTION_NAME (ARGUMENT)
  398. At the same time, we will add memory to the calculator, by allowing you
  399. to create named variables, store values in them, and use them later.
  400. Here is a sample session with the multi-function calculator:
  401.      % acalc
  402.      pi = 3.141592653589
  403.      3.1415926536
  404.      sin(pi)
  405.      0.0000000000
  406.      alpha = beta1 = 2.3
  407.      2.3000000000
  408.      alpha
  409.      2.3000000000
  410.      ln(alpha)
  411.      0.8329091229
  412.      exp(ln(beta1))
  413.      2.3000000000
  414.      %
  415.    Note that multiple assignment and nested function calls are
  416. permitted.
  417. * Menu:
  418. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  419. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  420. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  421. File: bison.info,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Up: Multi-function Calc
  422. Declarations for `mfcalc'
  423. -------------------------
  424.    Here are the C and Bison declarations for the multi-function
  425. calculator.
  426.      %{
  427.      #include <math.h>  /* For math functions, cos(), sin(), etc. */
  428.      #include "calc.h"  /* Contains definition of `symrec'        */
  429.      %}
  430.      %union {
  431.      double     val;  /* For returning numbers.                   */
  432.      symrec  *tptr;   /* For returning symbol-table pointers      */
  433.      }
  434.      
  435.      %token <val>  NUM        /* Simple double precision number   */
  436.      %token <tptr> VAR FNCT   /* Variable and Function            */
  437.      %type  <val>  exp
  438.      
  439.      %right '='
  440.      %left '-' '+'
  441.      %left '*' '/'
  442.      %left NEG     /* Negation--unary minus */
  443.      %right '^'    /* Exponentiation        */
  444.      
  445.      /* Grammar follows */
  446.      
  447.      %%
  448.    The above grammar introduces only two new features of the Bison
  449. language.  These features allow semantic values to have various data
  450. types (*note More Than One Value Type: Multiple Types.).
  451.    The `%union' declaration specifies the entire list of possible types;
  452. this is instead of defining `YYSTYPE'.  The allowable types are now
  453. double-floats (for `exp' and `NUM') and pointers to entries in the
  454. symbol table.  *Note The Collection of Value Types: Union Decl.
  455.    Since values can now have various types, it is necessary to
  456. associate a type with each grammar symbol whose semantic value is used.
  457. These symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations
  458. are augmented with information about their data type (placed between
  459. angle brackets).
  460.    The Bison construct `%type' is used for declaring nonterminal
  461. symbols, just as `%token' is used for declaring token types.  We have
  462. not used `%type' before because nonterminal symbols are normally
  463. declared implicitly by the rules that define them.  But `exp' must be
  464. declared explicitly so we can specify its value type.  *Note
  465. Nonterminal Symbols: Type Decl.
  466. File: bison.info,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  467. Grammar Rules for `mfcalc'
  468. --------------------------
  469.    Here are the grammar rules for the multi-function calculator.  Most
  470. of them are copied directly from `calc'; three rules, those which
  471. mention `VAR' or `FNCT', are new.
  472.      input:   /* empty */
  473.              | input line
  474.      ;
  475.      
  476.      line:
  477.                '\n'
  478.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  479.              | error '\n' { yyerrok;                  }
  480.      ;
  481.      
  482.      exp:      NUM                { $$ = $1;                         }
  483.              | VAR                { $$ = $1->value.var;              }
  484.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  485.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  486.              | exp '+' exp        { $$ = $1 + $3;                    }
  487.              | exp '-' exp        { $$ = $1 - $3;                    }
  488.              | exp '*' exp        { $$ = $1 * $3;                    }
  489.              | exp '/' exp        { $$ = $1 / $3;                    }
  490.              | '-' exp  %prec NEG { $$ = -$2;                        }
  491.              | exp '^' exp        { $$ = pow ($1, $3);               }
  492.              | '(' exp ')'        { $$ = $2;                         }
  493.      ;
  494.      /* End of grammar */
  495.      %%
  496. File: bison.info,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  497. The `mfcalc' Symbol Table
  498. -------------------------
  499.    The multi-function calculator requires a symbol table to keep track
  500. of the names and meanings of variables and functions.  This doesn't
  501. affect the grammar rules (except for the actions) or the Bison
  502. declarations, but it requires some additional C functions for support.
  503.    The symbol table itself consists of a linked list of records.  Its
  504. definition, which is kept in the header `calc.h', is as follows.  It
  505. provides for either functions or variables to be placed in the table.
  506.      /* Data type for links in the chain of symbols.      */
  507.      struct symrec
  508.      {
  509.        char *name;  /* name of symbol                     */
  510.        int type;    /* type of symbol: either VAR or FNCT */
  511.        union {
  512.          double var;           /* value of a VAR          */
  513.          double (*fnctptr)();  /* value of a FNCT         */
  514.        } value;
  515.        struct symrec *next;    /* link field              */
  516.      };
  517.      typedef struct symrec symrec;
  518.      
  519.      /* The symbol table: a chain of `struct symrec'.     */
  520.      extern symrec *sym_table;
  521.      
  522.      symrec *putsym ();
  523.      symrec *getsym ();
  524.    The new version of `main' includes a call to `init_table', a
  525. function that initializes the symbol table.  Here it is, and
  526. `init_table' as well:
  527.      #include <stdio.h>
  528.      
  529.      main ()
  530.      {
  531.        init_table ();
  532.        yyparse ();
  533.      }
  534.      yyerror (s)  /* Called by yyparse on error */
  535.           char *s;
  536.      {
  537.        printf ("%s\n", s);
  538.      }
  539.      
  540.      struct init
  541.      {
  542.        char *fname;
  543.        double (*fnct)();
  544.      };
  545.      struct init arith_fncts[]
  546.        = {
  547.            "sin", sin,
  548.            "cos", cos,
  549.            "atan", atan,
  550.            "ln", log,
  551.            "exp", exp,
  552.            "sqrt", sqrt,
  553.            0, 0
  554.          };
  555.      
  556.      /* The symbol table: a chain of `struct symrec'.  */
  557.      symrec *sym_table = (symrec *)0;
  558.      init_table ()  /* puts arithmetic functions in table. */
  559.      {
  560.        int i;
  561.        symrec *ptr;
  562.        for (i = 0; arith_fncts[i].fname != 0; i++)
  563.          {
  564.            ptr = putsym (arith_fncts[i].fname, FNCT);
  565.            ptr->value.fnctptr = arith_fncts[i].fnct;
  566.          }
  567.      }
  568.    By simply editing the initialization list and adding the necessary
  569. include files, you can add additional functions to the calculator.
  570.    Two important functions allow look-up and installation of symbols in
  571. the symbol table.  The function `putsym' is passed a name and the type
  572. (`VAR' or `FNCT') of the object to be installed.  The object is linked
  573. to the front of the list, and a pointer to the object is returned.  The
  574. function `getsym' is passed the name of the symbol to look up.  If
  575. found, a pointer to that symbol is returned; otherwise zero is returned.
  576.      symrec *
  577.      putsym (sym_name,sym_type)
  578.           char *sym_name;
  579.           int sym_type;
  580.      {
  581.        symrec *ptr;
  582.        ptr = (symrec *) malloc (sizeof (symrec));
  583.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  584.        strcpy (ptr->name,sym_name);
  585.        ptr->type = sym_type;
  586.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  587.        ptr->next = (struct symrec *)sym_table;
  588.        sym_table = ptr;
  589.        return ptr;
  590.      }
  591.      
  592.      symrec *
  593.      getsym (sym_name)
  594.           char *sym_name;
  595.      {
  596.        symrec *ptr;
  597.        for (ptr = sym_table; ptr != (symrec *) 0;
  598.             ptr = (symrec *)ptr->next)
  599.          if (strcmp (ptr->name,sym_name) == 0)
  600.            return ptr;
  601.        return 0;
  602.      }
  603.    The function `yylex' must now recognize variables, numeric values,
  604. and the single-character arithmetic operators.  Strings of alphanumeric
  605. characters with a leading nondigit are recognized as either variables or
  606. functions depending on what the symbol table says about them.
  607.    The string is passed to `getsym' for look up in the symbol table.  If
  608. the name appears in the table, a pointer to its location and its type
  609. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  610. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  611. pointer and its type (which must be `VAR') is returned to `yyparse'.
  612.    No change is needed in the handling of numeric values and arithmetic
  613. operators in `yylex'.
  614.      #include <ctype.h>
  615.      yylex ()
  616.      {
  617.        int c;
  618.      
  619.        /* Ignore whitespace, get first nonwhite character.  */
  620.        while ((c = getchar ()) == ' ' || c == '\t');
  621.      
  622.        if (c == EOF)
  623.          return 0;
  624.      /* Char starts a number => parse the number.         */
  625.        if (c == '.' || isdigit (c))
  626.          {
  627.            ungetc (c, stdin);
  628.            scanf ("%lf", &yylval.val);
  629.            return NUM;
  630.          }
  631.      /* Char starts an identifier => read the name.       */
  632.        if (isalpha (c))
  633.          {
  634.            symrec *s;
  635.            static char *symbuf = 0;
  636.            static int length = 0;
  637.            int i;
  638.      /* Initially make the buffer long enough
  639.               for a 40-character symbol name.  */
  640.            if (length == 0)
  641.              length = 40, symbuf = (char *)malloc (length + 1);
  642.      
  643.            i = 0;
  644.            do
  645.      {
  646.                /* If buffer is full, make it bigger.        */
  647.                if (i == length)
  648.                  {
  649.                    length *= 2;
  650.                    symbuf = (char *)realloc (symbuf, length + 1);
  651.                  }
  652.                /* Add this character to the buffer.         */
  653.                symbuf[i++] = c;
  654.                /* Get another character.                    */
  655.                c = getchar ();
  656.              }
  657.      while (c != EOF && isalnum (c));
  658.      
  659.            ungetc (c, stdin);
  660.            symbuf[i] = '\0';
  661.      s = getsym (symbuf);
  662.            if (s == 0)
  663.              s = putsym (symbuf, VAR);
  664.            yylval.tptr = s;
  665.            return s->type;
  666.          }
  667.      
  668.        /* Any other character is a token by itself.        */
  669.        return c;
  670.      }
  671.    This program is both powerful and flexible. You may easily add new
  672. functions, and it is a simple job to modify this code to install
  673. predefined variables such as `pi' or `e' as well.
  674. File: bison.info,  Node: Exercises,  Prev: Multi-function Calc,  Up: Examples
  675. Exercises
  676. =========
  677.   1. Add some new functions from `math.h' to the initialization list.
  678.   2. Add another array that contains constants and their values.  Then
  679.      modify `init_table' to add these constants to the symbol table.
  680.      It will be easiest to give the constants type `VAR'.
  681.   3. Make the program report an error if the user refers to an
  682.      uninitialized variable in any way except to store a value in it.
  683. File: bison.info,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  684. Bison Grammar Files
  685. *******************
  686.    Bison takes as input a context-free grammar specification and
  687. produces a C-language function that recognizes correct instances of the
  688. grammar.
  689.    The Bison grammar input file conventionally has a name ending in
  690. `.y'.
  691. * Menu:
  692. * Grammar Outline::   Overall layout of the grammar file.
  693. * Symbols::           Terminal and nonterminal symbols.
  694. * Rules::             How to write grammar rules.
  695. * Recursion::         Writing recursive rules.
  696. * Semantics::         Semantic values and actions.
  697. * Declarations::      All kinds of Bison declarations are described here.
  698. * Multiple Parsers::  Putting more than one Bison parser in one program.
  699. File: bison.info,  Node: Grammar Outline,  Next: Symbols,  Up: Grammar File
  700. Outline of a Bison Grammar
  701. ==========================
  702.    A Bison grammar file has four main sections, shown here with the
  703. appropriate delimiters:
  704.      %{
  705.      C DECLARATIONS
  706.      %}
  707.      
  708.      BISON DECLARATIONS
  709.      
  710.      %%
  711.      GRAMMAR RULES
  712.      %%
  713.      
  714.      ADDITIONAL C CODE
  715.    Comments enclosed in `/* ... */' may appear in any of the sections.
  716. * Menu:
  717. * C Declarations::    Syntax and usage of the C declarations section.
  718. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  719. * Grammar Rules::     Syntax and usage of the grammar rules section.
  720. * C Code::            Syntax and usage of the additional C code section.
  721. File: bison.info,  Node: C Declarations,  Next: Bison Declarations,  Up: Grammar Outline
  722. The C Declarations Section
  723. --------------------------
  724.    The C DECLARATIONS section contains macro definitions and
  725. declarations of functions and variables that are used in the actions in
  726. the grammar rules.  These are copied to the beginning of the parser
  727. file so that they precede the definition of `yyparse'.  You can use
  728. `#include' to get the declarations from a header file.  If you don't
  729. need any C declarations, you may omit the `%{' and `%}' delimiters that
  730. bracket this section.
  731. File: bison.info,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  732. The Bison Declarations Section
  733. ------------------------------
  734.    The BISON DECLARATIONS section contains declarations that define
  735. terminal and nonterminal symbols, specify precedence, and so on.  In
  736. some simple grammars you may not need any declarations.  *Note Bison
  737. Declarations: Declarations.
  738. File: bison.info,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  739. The Grammar Rules Section
  740. -------------------------
  741.    The "grammar rules" section contains one or more Bison grammar
  742. rules, and nothing else.  *Note Syntax of Grammar Rules: Rules.
  743.    There must always be at least one grammar rule, and the first `%%'
  744. (which precedes the grammar rules) may never be omitted even if it is
  745. the first thing in the file.
  746. File: bison.info,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  747. The Additional C Code Section
  748. -----------------------------
  749.    The ADDITIONAL C CODE section is copied verbatim to the end of the
  750. parser file, just as the C DECLARATIONS section is copied to the
  751. beginning.  This is the most convenient place to put anything that you
  752. want to have in the parser file but which need not come before the
  753. definition of `yyparse'.  For example, the definitions of `yylex' and
  754. `yyerror' often go here.  *Note Parser C-Language Interface: Interface.
  755.    If the last section is empty, you may omit the `%%' that separates it
  756. from the grammar rules.
  757.    The Bison parser itself contains many static variables whose names
  758. start with `yy' and many macros whose names start with `YY'.  It is a
  759. good idea to avoid using any such names (except those documented in this
  760. manual) in the additional C code section of the grammar file.
  761. File: bison.info,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  762. Symbols, Terminal and Nonterminal
  763. =================================
  764.    "Symbols" in Bison grammars represent the grammatical classifications
  765. of the language.
  766.    A "terminal symbol" (also known as a "token type") represents a
  767. class of syntactically equivalent tokens.  You use the symbol in grammar
  768. rules to mean that a token in that class is allowed.  The symbol is
  769. represented in the Bison parser by a numeric code, and the `yylex'
  770. function returns a token type code to indicate what kind of token has
  771. been read.  You don't need to know what the code value is; you can use
  772. the symbol to stand for it.
  773.    A "nonterminal symbol" stands for a class of syntactically equivalent
  774. groupings.  The symbol name is used in writing grammar rules.  By
  775. convention, it should be all lower case.
  776.    Symbol names can contain letters, digits (not at the beginning),
  777. underscores and periods.  Periods make sense only in nonterminals.
  778.    There are two ways of writing terminal symbols in the grammar:
  779.    * A "named token type" is written with an identifier, like an
  780.      identifier in C.  By convention, it should be all upper case.  Each
  781.      such name must be defined with a Bison declaration such as
  782.      `%token'.  *Note Token Type Names: Token Decl.
  783.    * A "character token type" (or "literal token") is written in the
  784.      grammar using the same syntax used in C for character constants;
  785.      for example, `'+'' is a character token type.  A character token
  786.      type doesn't need to be declared unless you need to specify its
  787.      semantic value data type (*note Data Types of Semantic Values:
  788.      Value Type.), associativity, or precedence (*note Operator
  789.      Precedence: Precedence.).
  790.      By convention, a character token type is used only to represent a
  791.      token that consists of that particular character.  Thus, the token
  792.      type `'+'' is used to represent the character `+' as a token.
  793.      Nothing enforces this convention, but if you depart from it, your
  794.      program will confuse other readers.
  795.      All the usual escape sequences used in character literals in C can
  796.      be used in Bison as well, but you must not use the null character
  797.      as a character literal because its ASCII code, zero, is the code
  798.      `yylex' returns for end-of-input (*note Calling Convention for
  799.      `yylex': Calling Convention.).
  800.    How you choose to write a terminal symbol has no effect on its
  801. grammatical meaning.  That depends only on where it appears in rules and
  802. on when the parser function returns that symbol.
  803.    The value returned by `yylex' is always one of the terminal symbols
  804. (or 0 for end-of-input).  Whichever way you write the token type in the
  805. grammar rules, you write it the same way in the definition of `yylex'.
  806. The numeric code for a character token type is simply the ASCII code for
  807. the character, so `yylex' can use the identical character constant to
  808. generate the requisite code.  Each named token type becomes a C macro in
  809. the parser file, so `yylex' can use the name to stand for the code.
  810. (This is why periods don't make sense in terminal symbols.) *Note
  811. Calling Convention for `yylex': Calling Convention.
  812.    If `yylex' is defined in a separate file, you need to arrange for the
  813. token-type macro definitions to be available there.  Use the `-d'
  814. option when you run Bison, so that it will write these macro definitions
  815. into a separate header file `NAME.tab.h' which you can include in the
  816. other source files that need it.  *Note Invoking Bison: Invocation.
  817.    The symbol `error' is a terminal symbol reserved for error recovery
  818. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  819. In particular, `yylex' should never return this value.
  820. File: bison.info,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  821. Syntax of Grammar Rules
  822. =======================
  823.    A Bison grammar rule has the following general form:
  824.      RESULT: COMPONENTS...
  825.              ;
  826. where RESULT is the nonterminal symbol that this rule describes and
  827. COMPONENTS are various terminal and nonterminal symbols that are put
  828. together by this rule (*note Symbols::.).
  829.    For example,
  830.      exp:      exp '+' exp
  831.              ;
  832. says that two groupings of type `exp', with a `+' token in between, can
  833. be combined into a larger grouping of type `exp'.
  834.    Whitespace in rules is significant only to separate symbols.  You
  835. can add extra whitespace as you wish.
  836.    Scattered among the components can be ACTIONS that determine the
  837. semantics of the rule.  An action looks like this:
  838.      {C STATEMENTS}
  839. Usually there is only one action and it follows the components.  *Note
  840. Actions::.
  841.    Multiple rules for the same RESULT can be written separately or can
  842. be joined with the vertical-bar character `|' as follows:
  843.      RESULT:   RULE1-COMPONENTS...
  844.              | RULE2-COMPONENTS...
  845.              ...
  846.              ;
  847. They are still considered distinct rules even when joined in this way.
  848.    If COMPONENTS in a rule is empty, it means that RESULT can match the
  849. empty string.  For example, here is how to define a comma-separated
  850. sequence of zero or more `exp' groupings:
  851.      expseq:   /* empty */
  852.              | expseq1
  853.              ;
  854.      
  855.      expseq1:  exp
  856.              | expseq1 ',' exp
  857.              ;
  858. It is customary to write a comment `/* empty */' in each rule with no
  859. components.
  860. File: bison.info,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  861. Recursive Rules
  862. ===============
  863.    A rule is called "recursive" when its RESULT nonterminal appears
  864. also on its right hand side.  Nearly all Bison grammars need to use
  865. recursion, because that is the only way to define a sequence of any
  866. number of somethings.  Consider this recursive definition of a
  867. comma-separated sequence of one or more expressions:
  868.      expseq1:  exp
  869.              | expseq1 ',' exp
  870.              ;
  871. Since the recursive use of `expseq1' is the leftmost symbol in the
  872. right hand side, we call this "left recursion".  By contrast, here the
  873. same construct is defined using "right recursion":
  874.      expseq1:  exp
  875.              | exp ',' expseq1
  876.              ;
  877. Any kind of sequence can be defined using either left recursion or
  878. right recursion, but you should always use left recursion, because it
  879. can parse a sequence of any number of elements with bounded stack
  880. space.  Right recursion uses up space on the Bison stack in proportion
  881. to the number of elements in the sequence, because all the elements
  882. must be shifted onto the stack before the rule can be applied even
  883. once.  *Note The Bison Parser Algorithm: Algorithm, for further
  884. explanation of this.
  885.    "Indirect" or "mutual" recursion occurs when the result of the rule
  886. does not appear directly on its right hand side, but does appear in
  887. rules for other nonterminals which do appear on its right hand side.
  888.    For example:
  889.      expr:     primary
  890.              | primary '+' primary
  891.              ;
  892.      
  893.      primary:  constant
  894.              | '(' expr ')'
  895.              ;
  896. defines two mutually-recursive nonterminals, since each refers to the
  897. other.
  898. File: bison.info,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  899. Defining Language Semantics
  900. ===========================
  901.    The grammar rules for a language determine only the syntax.  The
  902. semantics are determined by the semantic values associated with various
  903. tokens and groupings, and by the actions taken when various groupings
  904. are recognized.
  905.    For example, the calculator calculates properly because the value
  906. associated with each expression is the proper number; it adds properly
  907. because the action for the grouping `X + Y' is to add the numbers
  908. associated with X and Y.
  909. * Menu:
  910. * Value Type::        Specifying one data type for all semantic values.
  911. * Multiple Types::    Specifying several alternative data types.
  912. * Actions::           An action is the semantic definition of a grammar rule.
  913. * Action Types::      Specifying data types for actions to operate on.
  914. * Mid-Rule Actions::  Most actions go at the end of a rule.
  915.                       This says when, why and how to use the exceptional
  916.                         action in the middle of a rule.
  917. File: bison.info,  Node: Value Type,  Next: Multiple Types,  Up: Semantics
  918. Data Types of Semantic Values
  919. -----------------------------
  920.    In a simple program it may be sufficient to use the same data type
  921. for the semantic values of all language constructs.  This was true in
  922. the RPN and infix calculator examples (*note Reverse Polish Notation
  923. Calculator: RPN Calc.).
  924.    Bison's default is to use type `int' for all semantic values.  To
  925. specify some other type, define `YYSTYPE' as a macro, like this:
  926.      #define YYSTYPE double
  927. This macro definition must go in the C declarations section of the
  928. grammar file (*note Outline of a Bison Grammar: Grammar Outline.).
  929. File: bison.info,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  930. More Than One Value Type
  931. ------------------------
  932.    In most programs, you will need different data types for different
  933. kinds of tokens and groupings.  For example, a numeric constant may
  934. need type `int' or `long', while a string constant needs type `char *',
  935. and an identifier might need a pointer to an entry in the symbol table.
  936.    To use more than one data type for semantic values in one parser,
  937. Bison requires you to do two things:
  938.    * Specify the entire collection of possible data types, with the
  939.      `%union' Bison declaration (*note The Collection of Value Types:
  940.      Union Decl.).
  941.    * Choose one of those types for each symbol (terminal or nonterminal)
  942.      for which semantic values are used.  This is done for tokens with
  943.      the `%token' Bison declaration (*note Token Type Names: Token
  944.      Decl.) and for groupings with the `%type' Bison declaration (*note
  945.      Nonterminal Symbols: Type Decl.).
  946. File: bison.info,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  947. Actions
  948. -------
  949.    An action accompanies a syntactic rule and contains C code to be
  950. executed each time an instance of that rule is recognized.  The task of
  951. most actions is to compute a semantic value for the grouping built by
  952. the rule from the semantic values associated with tokens or smaller
  953. groupings.
  954.    An action consists of C statements surrounded by braces, much like a
  955. compound statement in C.  It can be placed at any position in the rule;
  956. it is executed at that position.  Most rules have just one action at
  957. the end of the rule, following all the components.  Actions in the
  958. middle of a rule are tricky and used only for special purposes (*note
  959. Actions in Mid-Rule: Mid-Rule Actions.).
  960.    The C code in an action can refer to the semantic values of the
  961. components matched by the rule with the construct `$N', which stands for
  962. the value of the Nth component.  The semantic value for the grouping
  963. being constructed is `$$'.  (Bison translates both of these constructs
  964. into array element references when it copies the actions into the parser
  965. file.)
  966.    Here is a typical example:
  967.      exp:    ...
  968.              | exp '+' exp
  969.                  { $$ = $1 + $3; }
  970. This rule constructs an `exp' from two smaller `exp' groupings
  971. connected by a plus-sign token.  In the action, `$1' and `$3' refer to
  972. the semantic values of the two component `exp' groupings, which are the
  973. first and third symbols on the right hand side of the rule.  The sum is
  974. stored into `$$' so that it becomes the semantic value of the
  975. addition-expression just recognized by the rule.  If there were a
  976. useful semantic value associated with the `+' token, it could be
  977. referred to as `$2'.
  978.    If you don't specify an action for a rule, Bison supplies a default:
  979. `$$ = $1'.  Thus, the value of the first symbol in the rule becomes the
  980. value of the whole rule.  Of course, the default rule is valid only if
  981. the two data types match.  There is no meaningful default action for an
  982. empty rule; every empty rule must have an explicit action unless the
  983. rule's value does not matter.
  984.    `$N' with N zero or negative is allowed for reference to tokens and
  985. groupings on the stack *before* those that match the current rule.
  986. This is a very risky practice, and to use it reliably you must be
  987. certain of the context in which the rule is applied.  Here is a case in
  988. which you can use this reliably:
  989.      foo:      expr bar '+' expr  { ... }
  990.              | expr bar '-' expr  { ... }
  991.              ;
  992.      
  993.      bar:      /* empty */
  994.              { previous_expr = $0; }
  995.              ;
  996.    As long as `bar' is used only in the fashion shown here, `$0' always
  997. refers to the `expr' which precedes `bar' in the definition of `foo'.
  998. File: bison.info,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  999. Data Types of Values in Actions
  1000. -------------------------------
  1001.    If you have chosen a single data type for semantic values, the `$$'
  1002. and `$N' constructs always have that data type.
  1003.    If you have used `%union' to specify a variety of data types, then
  1004. you must declare a choice among these types for each terminal or
  1005. nonterminal symbol that can have a semantic value.  Then each time you
  1006. use `$$' or `$N', its data type is determined by which symbol it refers
  1007. to in the rule.  In this example,
  1008.      exp:    ...
  1009.              | exp '+' exp
  1010.                  { $$ = $1 + $3; }
  1011. `$1' and `$3' refer to instances of `exp', so they all have the data
  1012. type declared for the nonterminal symbol `exp'.  If `$2' were used, it
  1013. would have the data type declared for the terminal symbol `'+'',
  1014. whatever that might be.
  1015.    Alternatively, you can specify the data type when you refer to the
  1016. value, by inserting `<TYPE>' after the `$' at the beginning of the
  1017. reference.  For example, if you have defined types as shown here:
  1018.      %union {
  1019.        int itype;
  1020.        double dtype;
  1021.      }
  1022. then you can write `$<itype>1' to refer to the first subunit of the
  1023. rule as an integer, or `$<dtype>1' to refer to it as a double.
  1024.