1 Ceci est le fichier Info bison.info, produit par Makeinfo version 4.0b
2 à partir bison.texinfo.
5 * bison: (bison). GNU Project parser generator (yacc replacement).
8 This file documents the Bison parser generator.
10 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 1999,
11 2000 Free Software Foundation, Inc.
13 Permission is granted to make and distribute verbatim copies of this
14 manual provided the copyright notice and this permission notice are
15 preserved on all copies.
17 Permission is granted to copy and distribute modified versions of
18 this manual under the conditions for verbatim copying, provided also
19 that the sections entitled "GNU General Public License" and "Conditions
20 for Using Bison" are included exactly as in the original, and provided
21 that the entire resulting derived work is distributed under the terms
22 of a permission notice identical to this one.
24 Permission is granted to copy and distribute translations of this
25 manual into another language, under the above conditions for modified
26 versions, except that the sections entitled "GNU General Public
27 License", "Conditions for Using Bison" and this permission notice may be
28 included in translations approved by the Free Software Foundation
29 instead of in the original English.
32 File: bison.info, Node: Rpcalc Decls, Next: Rpcalc Rules, Up: RPN Calc
34 Declarations for `rpcalc'
35 -------------------------
37 Here are the C and Bison declarations for the reverse polish notation
38 calculator. As in C, comments are placed between `/*...*/'.
40 /* Reverse polish notation calculator. */
43 #define YYSTYPE double
49 %% /* Grammar rules and actions follow */
51 The C declarations section (*note The C Declarations Section: C
52 Declarations.) contains two preprocessor directives.
54 The `#define' directive defines the macro `YYSTYPE', thus specifying
55 the C data type for semantic values of both tokens and groupings (*note
56 Data Types of Semantic Values: Value Type.). The Bison parser will use
57 whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
58 the default. Because we specify `double', each token and each
59 expression has an associated value, which is a floating point number.
61 The `#include' directive is used to declare the exponentiation
64 The second section, Bison declarations, provides information to
65 Bison about the token types (*note The Bison Declarations Section:
66 Bison Declarations.). Each terminal symbol that is not a
67 single-character literal must be declared here. (Single-character
68 literals normally don't need to be declared.) In this example, all the
69 arithmetic operators are designated by single-character literals, so the
70 only terminal symbol that needs to be declared is `NUM', the token type
71 for numeric constants.
74 File: bison.info, Node: Rpcalc Rules, Next: Rpcalc Lexer, Prev: Rpcalc Decls, Up: RPN Calc
76 Grammar Rules for `rpcalc'
77 --------------------------
79 Here are the grammar rules for the reverse polish notation
87 | exp '\n' { printf ("\t%.10g\n", $1); }
91 | exp exp '+' { $$ = $1 + $2; }
92 | exp exp '-' { $$ = $1 - $2; }
93 | exp exp '*' { $$ = $1 * $2; }
94 | exp exp '/' { $$ = $1 / $2; }
96 | exp exp '^' { $$ = pow ($1, $2); }
98 | exp 'n' { $$ = -$1; }
102 The groupings of the rpcalc "language" defined here are the
103 expression (given the name `exp'), the line of input (`line'), and the
104 complete input transcript (`input'). Each of these nonterminal symbols
105 has several alternate rules, joined by the `|' punctuator which is read
106 as "or". The following sections explain what these rules mean.
108 The semantics of the language is determined by the actions taken
109 when a grouping is recognized. The actions are the C code that appears
110 inside braces. *Note Actions::.
112 You must specify these actions in C, but Bison provides the means for
113 passing semantic values between the rules. In each action, the
114 pseudo-variable `$$' stands for the semantic value for the grouping
115 that the rule is going to construct. Assigning a value to `$$' is the
116 main job of most actions. The semantic values of the components of the
117 rule are referred to as `$1', `$2', and so on.
126 File: bison.info, Node: Rpcalc Input, Next: Rpcalc Line, Up: Rpcalc Rules
128 Explanation of `input'
129 ......................
131 Consider the definition of `input':
137 This definition reads as follows: "A complete input is either an
138 empty string, or a complete input followed by an input line". Notice
139 that "complete input" is defined in terms of itself. This definition
140 is said to be "left recursive" since `input' appears always as the
141 leftmost symbol in the sequence. *Note Recursive Rules: Recursion.
143 The first alternative is empty because there are no symbols between
144 the colon and the first `|'; this means that `input' can match an empty
145 string of input (no tokens). We write the rules this way because it is
146 legitimate to type `Ctrl-d' right after you start the calculator. It's
147 conventional to put an empty alternative first and write the comment
150 The second alternate rule (`input line') handles all nontrivial
151 input. It means, "After reading any number of lines, read one more
152 line if possible." The left recursion makes this rule into a loop.
153 Since the first alternative matches empty input, the loop can be
154 executed zero or more times.
156 The parser function `yyparse' continues to process input until a
157 grammatical error is seen or the lexical analyzer says there are no more
158 input tokens; we will arrange for the latter to happen at end of file.
161 File: bison.info, Node: Rpcalc Line, Next: Rpcalc Expr, Prev: Rpcalc Input, Up: Rpcalc Rules
163 Explanation of `line'
164 .....................
166 Now consider the definition of `line':
169 | exp '\n' { printf ("\t%.10g\n", $1); }
172 The first alternative is a token which is a newline character; this
173 means that rpcalc accepts a blank line (and ignores it, since there is
174 no action). The second alternative is an expression followed by a
175 newline. This is the alternative that makes rpcalc useful. The
176 semantic value of the `exp' grouping is the value of `$1' because the
177 `exp' in question is the first symbol in the alternative. The action
178 prints this value, which is the result of the computation the user
181 This action is unusual because it does not assign a value to `$$'.
182 As a consequence, the semantic value associated with the `line' is
183 uninitialized (its value will be unpredictable). This would be a bug if
184 that value were ever used, but we don't use it: once rpcalc has printed
185 the value of the user's input line, that value is no longer needed.
188 File: bison.info, Node: Rpcalc Expr, Prev: Rpcalc Line, Up: Rpcalc Rules
190 Explanation of `expr'
191 .....................
193 The `exp' grouping has several rules, one for each kind of
194 expression. The first rule handles the simplest expressions: those
195 that are just numbers. The second handles an addition-expression,
196 which looks like two expressions followed by a plus-sign. The third
197 handles subtraction, and so on.
200 | exp exp '+' { $$ = $1 + $2; }
201 | exp exp '-' { $$ = $1 - $2; }
205 We have used `|' to join all the rules for `exp', but we could
206 equally well have written them separately:
209 exp: exp exp '+' { $$ = $1 + $2; } ;
210 exp: exp exp '-' { $$ = $1 - $2; } ;
213 Most of the rules have actions that compute the value of the
214 expression in terms of the value of its parts. For example, in the
215 rule for addition, `$1' refers to the first component `exp' and `$2'
216 refers to the second one. The third component, `'+'', has no meaningful
217 associated semantic value, but if it had one you could refer to it as
218 `$3'. When `yyparse' recognizes a sum expression using this rule, the
219 sum of the two subexpressions' values is produced as the value of the
220 entire expression. *Note Actions::.
222 You don't have to give an action for every rule. When a rule has no
223 action, Bison by default copies the value of `$1' into `$$'. This is
224 what happens in the first rule (the one that uses `NUM').
226 The formatting shown here is the recommended convention, but Bison
227 does not require it. You can add or change whitespace as much as you
228 wish. For example, this:
230 exp : NUM | exp exp '+' {$$ = $1 + $2; } | ...
232 means the same thing as this:
235 | exp exp '+' { $$ = $1 + $2; }
238 The latter, however, is much more readable.
241 File: bison.info, Node: Rpcalc Lexer, Next: Rpcalc Main, Prev: Rpcalc Rules, Up: RPN Calc
243 The `rpcalc' Lexical Analyzer
244 -----------------------------
246 The lexical analyzer's job is low-level parsing: converting
247 characters or sequences of characters into tokens. The Bison parser
248 gets its tokens by calling the lexical analyzer. *Note The Lexical
249 Analyzer Function `yylex': Lexical.
251 Only a simple lexical analyzer is needed for the RPN calculator.
252 This lexical analyzer skips blanks and tabs, then reads in numbers as
253 `double' and returns them as `NUM' tokens. Any other character that
254 isn't part of a number is a separate token. Note that the token-code
255 for such a single-character token is the character itself.
257 The return value of the lexical analyzer function is a numeric code
258 which represents a token type. The same text used in Bison rules to
259 stand for this token type is also a C expression for the numeric code
260 for the type. This works in two ways. If the token type is a
261 character literal, then its numeric code is the ASCII code for that
262 character; you can use the same character literal in the lexical
263 analyzer to express the number. If the token type is an identifier,
264 that identifier is defined by Bison as a C macro whose definition is
265 the appropriate number. In this example, therefore, `NUM' becomes a
266 macro for `yylex' to use.
268 The semantic value of the token (if it has one) is stored into the
269 global variable `yylval', which is where the Bison parser will look for
270 it. (The C data type of `yylval' is `YYSTYPE', which was defined at
271 the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
274 A token type code of zero is returned if the end-of-file is
275 encountered. (Bison recognizes any nonpositive value as indicating the
278 Here is the code for the lexical analyzer:
280 /* Lexical analyzer returns a double floating point
281 number on the stack and the token NUM, or the ASCII
282 character read if not a number. Skips all blanks
283 and tabs, returns 0 for EOF. */
292 /* skip white space */
293 while ((c = getchar ()) == ' ' || c == '\t')
295 /* process numbers */
296 if (c == '.' || isdigit (c))
299 scanf ("%lf", &yylval);
302 /* return end-of-file */
305 /* return single chars */
310 File: bison.info, Node: Rpcalc Main, Next: Rpcalc Error, Prev: Rpcalc Lexer, Up: RPN Calc
312 The Controlling Function
313 ------------------------
315 In keeping with the spirit of this example, the controlling function
316 is kept to the bare minimum. The only requirement is that it call
317 `yyparse' to start the process of parsing.
326 File: bison.info, Node: Rpcalc Error, Next: Rpcalc Gen, Prev: Rpcalc Main, Up: RPN Calc
328 The Error Reporting Routine
329 ---------------------------
331 When `yyparse' detects a syntax error, it calls the error reporting
332 function `yyerror' to print an error message (usually but not always
333 `"parse error"'). It is up to the programmer to supply `yyerror'
334 (*note Parser C-Language Interface: Interface.), so here is the
335 definition we will use:
340 yyerror (const char *s) /* Called by yyparse on error */
345 After `yyerror' returns, the Bison parser may recover from the error
346 and continue parsing if the grammar contains a suitable error rule
347 (*note Error Recovery::). Otherwise, `yyparse' returns nonzero. We
348 have not written any error rules in this example, so any invalid input
349 will cause the calculator program to exit. This is not clean behavior
350 for a real calculator, but it is adequate for the first example.
353 File: bison.info, Node: Rpcalc Gen, Next: Rpcalc Compile, Prev: Rpcalc Error, Up: RPN Calc
355 Running Bison to Make the Parser
356 --------------------------------
358 Before running Bison to produce a parser, we need to decide how to
359 arrange all the source code in one or more source files. For such a
360 simple example, the easiest thing is to put everything in one file. The
361 definitions of `yylex', `yyerror' and `main' go at the end, in the
362 "additional C code" section of the file (*note The Overall Layout of a
363 Bison Grammar: Grammar Layout.).
365 For a large project, you would probably have several source files,
366 and use `make' to arrange to recompile them.
368 With all the source in a single file, you use the following command
369 to convert it into a parser file:
373 In this example the file was called `rpcalc.y' (for "Reverse Polish
374 CALCulator"). Bison produces a file named `FILE_NAME.tab.c', removing
375 the `.y' from the original file name. The file output by Bison contains
376 the source code for `yyparse'. The additional functions in the input
377 file (`yylex', `yyerror' and `main') are copied verbatim to the output.
380 File: bison.info, Node: Rpcalc Compile, Prev: Rpcalc Gen, Up: RPN Calc
382 Compiling the Parser File
383 -------------------------
385 Here is how to compile and run the parser file:
387 # List files in current directory.
389 rpcalc.tab.c rpcalc.y
391 # Compile the Bison parser.
392 # `-lm' tells compiler to search math library for `pow'.
393 % cc rpcalc.tab.c -lm -o rpcalc
397 rpcalc rpcalc.tab.c rpcalc.y
399 The file `rpcalc' now contains the executable code. Here is an
400 example session using `rpcalc'.
407 3 7 + 3 4 5 * + - n Note the unary minus, `n'
413 ^D End-of-file indicator
417 File: bison.info, Node: Infix Calc, Next: Simple Error Recovery, Prev: RPN Calc, Up: Examples
419 Infix Notation Calculator: `calc'
420 =================================
422 We now modify rpcalc to handle infix operators instead of postfix.
423 Infix notation involves the concept of operator precedence and the need
424 for parentheses nested to arbitrary depth. Here is the Bison code for
425 `calc.y', an infix desk-top calculator.
427 /* Infix notation calculator--calc */
430 #define YYSTYPE double
434 /* BISON Declarations */
438 %left NEG /* negation--unary minus */
439 %right '^' /* exponentiation */
441 /* Grammar follows */
443 input: /* empty string */
448 | exp '\n' { printf ("\t%.10g\n", $1); }
451 exp: NUM { $$ = $1; }
452 | exp '+' exp { $$ = $1 + $3; }
453 | exp '-' exp { $$ = $1 - $3; }
454 | exp '*' exp { $$ = $1 * $3; }
455 | exp '/' exp { $$ = $1 / $3; }
456 | '-' exp %prec NEG { $$ = -$2; }
457 | exp '^' exp { $$ = pow ($1, $3); }
458 | '(' exp ')' { $$ = $2; }
462 The functions `yylex', `yyerror' and `main' can be the same as before.
464 There are two important new features shown in this code.
466 In the second section (Bison declarations), `%left' declares token
467 types and says they are left-associative operators. The declarations
468 `%left' and `%right' (right associativity) take the place of `%token'
469 which is used to declare a token type name without associativity.
470 (These tokens are single-character literals, which ordinarily don't
471 need to be declared. We declare them here to specify the
474 Operator precedence is determined by the line ordering of the
475 declarations; the higher the line number of the declaration (lower on
476 the page or screen), the higher the precedence. Hence, exponentiation
477 has the highest precedence, unary minus (`NEG') is next, followed by
478 `*' and `/', and so on. *Note Operator Precedence: Precedence.
480 The other important new feature is the `%prec' in the grammar section
481 for the unary minus operator. The `%prec' simply instructs Bison that
482 the rule `| '-' exp' has the same precedence as `NEG'--in this case the
483 next-to-highest. *Note Context-Dependent Precedence: Contextual
486 Here is a sample run of `calc.y':
489 4 + 4.5 - (34/(8*3+-3))
497 File: bison.info, Node: Simple Error Recovery, Next: Multi-function Calc, Prev: Infix Calc, Up: Examples
499 Simple Error Recovery
500 =====================
502 Up to this point, this manual has not addressed the issue of "error
503 recovery"--how to continue parsing after the parser detects a syntax
504 error. All we have handled is error reporting with `yyerror'. Recall
505 that by default `yyparse' returns after calling `yyerror'. This means
506 that an erroneous input line causes the calculator program to exit.
507 Now we show how to rectify this deficiency.
509 The Bison language itself includes the reserved word `error', which
510 may be included in the grammar rules. In the example below it has been
511 added to one of the alternatives for `line':
514 | exp '\n' { printf ("\t%.10g\n", $1); }
515 | error '\n' { yyerrok; }
518 This addition to the grammar allows for simple error recovery in the
519 event of a parse error. If an expression that cannot be evaluated is
520 read, the error will be recognized by the third rule for `line', and
521 parsing will continue. (The `yyerror' function is still called upon to
522 print its message as well.) The action executes the statement
523 `yyerrok', a macro defined automatically by Bison; its meaning is that
524 error recovery is complete (*note Error Recovery::). Note the
525 difference between `yyerrok' and `yyerror'; neither one is a misprint.
527 This form of error recovery deals with syntax errors. There are
528 other kinds of errors; for example, division by zero, which raises an
529 exception signal that is normally fatal. A real calculator program
530 must handle this signal and use `longjmp' to return to `main' and
531 resume parsing input lines; it would also have to discard the rest of
532 the current line of input. We won't discuss this issue further because
533 it is not specific to Bison programs.
536 File: bison.info, Node: Multi-function Calc, Next: Exercises, Prev: Simple Error Recovery, Up: Examples
538 Multi-Function Calculator: `mfcalc'
539 ===================================
541 Now that the basics of Bison have been discussed, it is time to move
542 on to a more advanced problem. The above calculators provided only five
543 functions, `+', `-', `*', `/' and `^'. It would be nice to have a
544 calculator that provides other mathematical functions such as `sin',
547 It is easy to add new operators to the infix calculator as long as
548 they are only single-character literals. The lexical analyzer `yylex'
549 passes back all nonnumber characters as tokens, so new grammar rules
550 suffice for adding a new operator. But we want something more
551 flexible: built-in functions whose syntax has this form:
553 FUNCTION_NAME (ARGUMENT)
555 At the same time, we will add memory to the calculator, by allowing you
556 to create named variables, store values in them, and use them later.
557 Here is a sample session with the multi-function calculator:
574 Note that multiple assignment and nested function calls are
579 * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
580 * Rules: Mfcalc Rules. Grammar rules for the calculator.
581 * Symtab: Mfcalc Symtab. Symbol table management subroutines.
584 File: bison.info, Node: Mfcalc Decl, Next: Mfcalc Rules, Up: Multi-function Calc
586 Declarations for `mfcalc'
587 -------------------------
589 Here are the C and Bison declarations for the multi-function
593 #include <math.h> /* For math functions, cos(), sin(), etc. */
594 #include "calc.h" /* Contains definition of `symrec' */
597 double val; /* For returning numbers. */
598 symrec *tptr; /* For returning symbol-table pointers */
601 %token <val> NUM /* Simple double precision number */
602 %token <tptr> VAR FNCT /* Variable and Function */
608 %left NEG /* Negation--unary minus */
609 %right '^' /* Exponentiation */
611 /* Grammar follows */
615 The above grammar introduces only two new features of the Bison
616 language. These features allow semantic values to have various data
617 types (*note More Than One Value Type: Multiple Types.).
619 The `%union' declaration specifies the entire list of possible types;
620 this is instead of defining `YYSTYPE'. The allowable types are now
621 double-floats (for `exp' and `NUM') and pointers to entries in the
622 symbol table. *Note The Collection of Value Types: Union Decl.
624 Since values can now have various types, it is necessary to
625 associate a type with each grammar symbol whose semantic value is used.
626 These symbols are `NUM', `VAR', `FNCT', and `exp'. Their declarations
627 are augmented with information about their data type (placed between
630 The Bison construct `%type' is used for declaring nonterminal
631 symbols, just as `%token' is used for declaring token types. We have
632 not used `%type' before because nonterminal symbols are normally
633 declared implicitly by the rules that define them. But `exp' must be
634 declared explicitly so we can specify its value type. *Note
635 Nonterminal Symbols: Type Decl.
638 File: bison.info, Node: Mfcalc Rules, Next: Mfcalc Symtab, Prev: Mfcalc Decl, Up: Multi-function Calc
640 Grammar Rules for `mfcalc'
641 --------------------------
643 Here are the grammar rules for the multi-function calculator. Most
644 of them are copied directly from `calc'; three rules, those which
645 mention `VAR' or `FNCT', are new.
653 | exp '\n' { printf ("\t%.10g\n", $1); }
654 | error '\n' { yyerrok; }
657 exp: NUM { $$ = $1; }
658 | VAR { $$ = $1->value.var; }
659 | VAR '=' exp { $$ = $3; $1->value.var = $3; }
660 | FNCT '(' exp ')' { $$ = (*($1->value.fnctptr))($3); }
661 | exp '+' exp { $$ = $1 + $3; }
662 | exp '-' exp { $$ = $1 - $3; }
663 | exp '*' exp { $$ = $1 * $3; }
664 | exp '/' exp { $$ = $1 / $3; }
665 | '-' exp %prec NEG { $$ = -$2; }
666 | exp '^' exp { $$ = pow ($1, $3); }
667 | '(' exp ')' { $$ = $2; }
673 File: bison.info, Node: Mfcalc Symtab, Prev: Mfcalc Rules, Up: Multi-function Calc
675 The `mfcalc' Symbol Table
676 -------------------------
678 The multi-function calculator requires a symbol table to keep track
679 of the names and meanings of variables and functions. This doesn't
680 affect the grammar rules (except for the actions) or the Bison
681 declarations, but it requires some additional C functions for support.
683 The symbol table itself consists of a linked list of records. Its
684 definition, which is kept in the header `calc.h', is as follows. It
685 provides for either functions or variables to be placed in the table.
687 /* Fonctions type. */
688 typedef double (*func_t) (double);
690 /* Data type for links in the chain of symbols. */
693 char *name; /* name of symbol */
694 int type; /* type of symbol: either VAR or FNCT */
697 double var; /* value of a VAR */
698 func_t fnctptr; /* value of a FNCT */
700 struct symrec *next; /* link field */
703 typedef struct symrec symrec;
705 /* The symbol table: a chain of `struct symrec'. */
706 extern symrec *sym_table;
708 symrec *putsym (const char *, func_t);
709 symrec *getsym (const char *);
711 The new version of `main' includes a call to `init_table', a
712 function that initializes the symbol table. Here it is, and
713 `init_table' as well:
725 yyerror (const char *s) /* Called by yyparse on error */
733 double (*fnct)(double);
736 struct init arith_fncts[] =
747 /* The symbol table: a chain of `struct symrec'. */
748 symrec *sym_table = (symrec *) 0;
750 /* Put arithmetic functions in table. */
756 for (i = 0; arith_fncts[i].fname != 0; i++)
758 ptr = putsym (arith_fncts[i].fname, FNCT);
759 ptr->value.fnctptr = arith_fncts[i].fnct;
763 By simply editing the initialization list and adding the necessary
764 include files, you can add additional functions to the calculator.
766 Two important functions allow look-up and installation of symbols in
767 the symbol table. The function `putsym' is passed a name and the type
768 (`VAR' or `FNCT') of the object to be installed. The object is linked
769 to the front of the list, and a pointer to the object is returned. The
770 function `getsym' is passed the name of the symbol to look up. If
771 found, a pointer to that symbol is returned; otherwise zero is returned.
774 putsym (char *sym_name, int sym_type)
777 ptr = (symrec *) malloc (sizeof (symrec));
778 ptr->name = (char *) malloc (strlen (sym_name) + 1);
779 strcpy (ptr->name,sym_name);
780 ptr->type = sym_type;
781 ptr->value.var = 0; /* set value to 0 even if fctn. */
782 ptr->next = (struct symrec *)sym_table;
788 getsym (const char *sym_name)
791 for (ptr = sym_table; ptr != (symrec *) 0;
792 ptr = (symrec *)ptr->next)
793 if (strcmp (ptr->name,sym_name) == 0)
798 The function `yylex' must now recognize variables, numeric values,
799 and the single-character arithmetic operators. Strings of alphanumeric
800 characters with a leading non-digit are recognized as either variables
801 or functions depending on what the symbol table says about them.
803 The string is passed to `getsym' for look up in the symbol table. If
804 the name appears in the table, a pointer to its location and its type
805 (`VAR' or `FNCT') is returned to `yyparse'. If it is not already in
806 the table, then it is installed as a `VAR' using `putsym'. Again, a
807 pointer and its type (which must be `VAR') is returned to `yyparse'.
809 No change is needed in the handling of numeric values and arithmetic
810 operators in `yylex'.
819 /* Ignore whitespace, get first nonwhite character. */
820 while ((c = getchar ()) == ' ' || c == '\t');
825 /* Char starts a number => parse the number. */
826 if (c == '.' || isdigit (c))
829 scanf ("%lf", &yylval.val);
833 /* Char starts an identifier => read the name. */
837 static char *symbuf = 0;
838 static int length = 0;
841 /* Initially make the buffer long enough
842 for a 40-character symbol name. */
844 length = 40, symbuf = (char *)malloc (length + 1);
849 /* If buffer is full, make it bigger. */
853 symbuf = (char *)realloc (symbuf, length + 1);
855 /* Add this character to the buffer. */
857 /* Get another character. */
860 while (c != EOF && isalnum (c));
867 s = putsym (symbuf, VAR);
872 /* Any other character is a token by itself. */
876 This program is both powerful and flexible. You may easily add new
877 functions, and it is a simple job to modify this code to install
878 predefined variables such as `pi' or `e' as well.
881 File: bison.info, Node: Exercises, Prev: Multi-function Calc, Up: Examples
886 1. Add some new functions from `math.h' to the initialization list.
888 2. Add another array that contains constants and their values. Then
889 modify `init_table' to add these constants to the symbol table.
890 It will be easiest to give the constants type `VAR'.
892 3. Make the program report an error if the user refers to an
893 uninitialized variable in any way except to store a value in it.
896 File: bison.info, Node: Grammar File, Next: Interface, Prev: Examples, Up: Top
901 Bison takes as input a context-free grammar specification and
902 produces a C-language function that recognizes correct instances of the
905 The Bison grammar input file conventionally has a name ending in
906 `.y'. *Note Invoking Bison: Invocation.
910 * Grammar Outline:: Overall layout of the grammar file.
911 * Symbols:: Terminal and nonterminal symbols.
912 * Rules:: How to write grammar rules.
913 * Recursion:: Writing recursive rules.
914 * Semantics:: Semantic values and actions.
915 * Locations:: Locations and actions.
916 * Declarations:: All kinds of Bison declarations are described here.
917 * Multiple Parsers:: Putting more than one Bison parser in one program.
920 File: bison.info, Node: Grammar Outline, Next: Symbols, Up: Grammar File
922 Outline of a Bison Grammar
923 ==========================
925 A Bison grammar file has four main sections, shown here with the
926 appropriate delimiters:
940 Comments enclosed in `/* ... */' may appear in any of the sections.
944 * C Declarations:: Syntax and usage of the C declarations section.
945 * Bison Declarations:: Syntax and usage of the Bison declarations section.
946 * Grammar Rules:: Syntax and usage of the grammar rules section.
947 * C Code:: Syntax and usage of the additional C code section.
950 File: bison.info, Node: C Declarations, Next: Bison Declarations, Up: Grammar Outline
952 The C Declarations Section
953 --------------------------
955 The C DECLARATIONS section contains macro definitions and
956 declarations of functions and variables that are used in the actions in
957 the grammar rules. These are copied to the beginning of the parser
958 file so that they precede the definition of `yyparse'. You can use
959 `#include' to get the declarations from a header file. If you don't
960 need any C declarations, you may omit the `%{' and `%}' delimiters that
961 bracket this section.
964 File: bison.info, Node: Bison Declarations, Next: Grammar Rules, Prev: C Declarations, Up: Grammar Outline
966 The Bison Declarations Section
967 ------------------------------
969 The BISON DECLARATIONS section contains declarations that define
970 terminal and nonterminal symbols, specify precedence, and so on. In
971 some simple grammars you may not need any declarations. *Note Bison
972 Declarations: Declarations.
975 File: bison.info, Node: Grammar Rules, Next: C Code, Prev: Bison Declarations, Up: Grammar Outline
977 The Grammar Rules Section
978 -------------------------
980 The "grammar rules" section contains one or more Bison grammar
981 rules, and nothing else. *Note Syntax of Grammar Rules: Rules.
983 There must always be at least one grammar rule, and the first `%%'
984 (which precedes the grammar rules) may never be omitted even if it is
985 the first thing in the file.
988 File: bison.info, Node: C Code, Prev: Grammar Rules, Up: Grammar Outline
990 The Additional C Code Section
991 -----------------------------
993 The ADDITIONAL C CODE section is copied verbatim to the end of the
994 parser file, just as the C DECLARATIONS section is copied to the
995 beginning. This is the most convenient place to put anything that you
996 want to have in the parser file but which need not come before the
997 definition of `yyparse'. For example, the definitions of `yylex' and
998 `yyerror' often go here. *Note Parser C-Language Interface: Interface.
1000 If the last section is empty, you may omit the `%%' that separates it
1001 from the grammar rules.
1003 The Bison parser itself contains many static variables whose names
1004 start with `yy' and many macros whose names start with `YY'. It is a
1005 good idea to avoid using any such names (except those documented in this
1006 manual) in the additional C code section of the grammar file.
1009 File: bison.info, Node: Symbols, Next: Rules, Prev: Grammar Outline, Up: Grammar File
1011 Symbols, Terminal and Nonterminal
1012 =================================
1014 "Symbols" in Bison grammars represent the grammatical classifications
1017 A "terminal symbol" (also known as a "token type") represents a
1018 class of syntactically equivalent tokens. You use the symbol in grammar
1019 rules to mean that a token in that class is allowed. The symbol is
1020 represented in the Bison parser by a numeric code, and the `yylex'
1021 function returns a token type code to indicate what kind of token has
1022 been read. You don't need to know what the code value is; you can use
1023 the symbol to stand for it.
1025 A "nonterminal symbol" stands for a class of syntactically equivalent
1026 groupings. The symbol name is used in writing grammar rules. By
1027 convention, it should be all lower case.
1029 Symbol names can contain letters, digits (not at the beginning),
1030 underscores and periods. Periods make sense only in nonterminals.
1032 There are three ways of writing terminal symbols in the grammar:
1034 * A "named token type" is written with an identifier, like an
1035 identifier in C. By convention, it should be all upper case. Each
1036 such name must be defined with a Bison declaration such as
1037 `%token'. *Note Token Type Names: Token Decl.
1039 * A "character token type" (or "literal character token") is written
1040 in the grammar using the same syntax used in C for character
1041 constants; for example, `'+'' is a character token type. A
1042 character token type doesn't need to be declared unless you need to
1043 specify its semantic value data type (*note Data Types of Semantic
1044 Values: Value Type.), associativity, or precedence (*note Operator
1045 Precedence: Precedence.).
1047 By convention, a character token type is used only to represent a
1048 token that consists of that particular character. Thus, the token
1049 type `'+'' is used to represent the character `+' as a token.
1050 Nothing enforces this convention, but if you depart from it, your
1051 program will confuse other readers.
1053 All the usual escape sequences used in character literals in C can
1054 be used in Bison as well, but you must not use the null character
1055 as a character literal because its ASCII code, zero, is the code
1056 `yylex' returns for end-of-input (*note Calling Convention for
1057 `yylex': Calling Convention.).
1059 * A "literal string token" is written like a C string constant; for
1060 example, `"<="' is a literal string token. A literal string token
1061 doesn't need to be declared unless you need to specify its semantic
1062 value data type (*note Value Type::), associativity, or precedence
1063 (*note Precedence::).
1065 You can associate the literal string token with a symbolic name as
1066 an alias, using the `%token' declaration (*note Token
1067 Declarations: Token Decl.). If you don't do that, the lexical
1068 analyzer has to retrieve the token number for the literal string
1069 token from the `yytname' table (*note Calling Convention::).
1071 *WARNING*: literal string tokens do not work in Yacc.
1073 By convention, a literal string token is used only to represent a
1074 token that consists of that particular string. Thus, you should
1075 use the token type `"<="' to represent the string `<=' as a token.
1076 Bison does not enforce this convention, but if you depart from
1077 it, people who read your program will be confused.
1079 All the escape sequences used in string literals in C can be used
1080 in Bison as well. A literal string token must contain two or more
1081 characters; for a token containing just one character, use a
1082 character token (see above).
1084 How you choose to write a terminal symbol has no effect on its
1085 grammatical meaning. That depends only on where it appears in rules and
1086 on when the parser function returns that symbol.
1088 The value returned by `yylex' is always one of the terminal symbols
1089 (or 0 for end-of-input). Whichever way you write the token type in the
1090 grammar rules, you write it the same way in the definition of `yylex'.
1091 The numeric code for a character token type is simply the ASCII code for
1092 the character, so `yylex' can use the identical character constant to
1093 generate the requisite code. Each named token type becomes a C macro in
1094 the parser file, so `yylex' can use the name to stand for the code.
1095 (This is why periods don't make sense in terminal symbols.) *Note
1096 Calling Convention for `yylex': Calling Convention.
1098 If `yylex' is defined in a separate file, you need to arrange for the
1099 token-type macro definitions to be available there. Use the `-d'
1100 option when you run Bison, so that it will write these macro definitions
1101 into a separate header file `NAME.tab.h' which you can include in the
1102 other source files that need it. *Note Invoking Bison: Invocation.
1104 The symbol `error' is a terminal symbol reserved for error recovery
1105 (*note Error Recovery::); you shouldn't use it for any other purpose.
1106 In particular, `yylex' should never return this value.
1109 File: bison.info, Node: Rules, Next: Recursion, Prev: Symbols, Up: Grammar File
1111 Syntax of Grammar Rules
1112 =======================
1114 A Bison grammar rule has the following general form:
1116 RESULT: COMPONENTS...
1119 where RESULT is the nonterminal symbol that this rule describes, and
1120 COMPONENTS are various terminal and nonterminal symbols that are put
1121 together by this rule (*note Symbols::).
1128 says that two groupings of type `exp', with a `+' token in between, can
1129 be combined into a larger grouping of type `exp'.
1131 Whitespace in rules is significant only to separate symbols. You
1132 can add extra whitespace as you wish.
1134 Scattered among the components can be ACTIONS that determine the
1135 semantics of the rule. An action looks like this:
1139 Usually there is only one action and it follows the components. *Note
1142 Multiple rules for the same RESULT can be written separately or can
1143 be joined with the vertical-bar character `|' as follows:
1145 RESULT: RULE1-COMPONENTS...
1146 | RULE2-COMPONENTS...
1150 They are still considered distinct rules even when joined in this way.
1152 If COMPONENTS in a rule is empty, it means that RESULT can match the
1153 empty string. For example, here is how to define a comma-separated
1154 sequence of zero or more `exp' groupings:
1164 It is customary to write a comment `/* empty */' in each rule with no
1168 File: bison.info, Node: Recursion, Next: Semantics, Prev: Rules, Up: Grammar File
1173 A rule is called "recursive" when its RESULT nonterminal appears
1174 also on its right hand side. Nearly all Bison grammars need to use
1175 recursion, because that is the only way to define a sequence of any
1176 number of a particular thing. Consider this recursive definition of a
1177 comma-separated sequence of one or more expressions:
1183 Since the recursive use of `expseq1' is the leftmost symbol in the
1184 right hand side, we call this "left recursion". By contrast, here the
1185 same construct is defined using "right recursion":
1191 Any kind of sequence can be defined using either left recursion or
1192 right recursion, but you should always use left recursion, because it
1193 can parse a sequence of any number of elements with bounded stack
1194 space. Right recursion uses up space on the Bison stack in proportion
1195 to the number of elements in the sequence, because all the elements
1196 must be shifted onto the stack before the rule can be applied even
1197 once. *Note The Bison Parser Algorithm: Algorithm, for further
1198 explanation of this.
1200 "Indirect" or "mutual" recursion occurs when the result of the rule
1201 does not appear directly on its right hand side, but does appear in
1202 rules for other nonterminals which do appear on its right hand side.
1207 | primary '+' primary
1214 defines two mutually-recursive nonterminals, since each refers to the
1218 File: bison.info, Node: Semantics, Next: Locations, Prev: Recursion, Up: Grammar File
1220 Defining Language Semantics
1221 ===========================
1223 The grammar rules for a language determine only the syntax. The
1224 semantics are determined by the semantic values associated with various
1225 tokens and groupings, and by the actions taken when various groupings
1228 For example, the calculator calculates properly because the value
1229 associated with each expression is the proper number; it adds properly
1230 because the action for the grouping `X + Y' is to add the numbers
1231 associated with X and Y.
1235 * Value Type:: Specifying one data type for all semantic values.
1236 * Multiple Types:: Specifying several alternative data types.
1237 * Actions:: An action is the semantic definition of a grammar rule.
1238 * Action Types:: Specifying data types for actions to operate on.
1239 * Mid-Rule Actions:: Most actions go at the end of a rule.
1240 This says when, why and how to use the exceptional
1241 action in the middle of a rule.
1244 File: bison.info, Node: Value Type, Next: Multiple Types, Up: Semantics
1246 Data Types of Semantic Values
1247 -----------------------------
1249 In a simple program it may be sufficient to use the same data type
1250 for the semantic values of all language constructs. This was true in
1251 the RPN and infix calculator examples (*note Reverse Polish Notation
1252 Calculator: RPN Calc.).
1254 Bison's default is to use type `int' for all semantic values. To
1255 specify some other type, define `YYSTYPE' as a macro, like this:
1257 #define YYSTYPE double
1259 This macro definition must go in the C declarations section of the
1260 grammar file (*note Outline of a Bison Grammar: Grammar Outline.).
1263 File: bison.info, Node: Multiple Types, Next: Actions, Prev: Value Type, Up: Semantics
1265 More Than One Value Type
1266 ------------------------
1268 In most programs, you will need different data types for different
1269 kinds of tokens and groupings. For example, a numeric constant may
1270 need type `int' or `long', while a string constant needs type `char *',
1271 and an identifier might need a pointer to an entry in the symbol table.
1273 To use more than one data type for semantic values in one parser,
1274 Bison requires you to do two things:
1276 * Specify the entire collection of possible data types, with the
1277 `%union' Bison declaration (*note The Collection of Value Types:
1280 * Choose one of those types for each symbol (terminal or
1281 nonterminal) for which semantic values are used. This is done for
1282 tokens with the `%token' Bison declaration (*note Token Type
1283 Names: Token Decl.) and for groupings with the `%type' Bison
1284 declaration (*note Nonterminal Symbols: Type Decl.).
1287 File: bison.info, Node: Actions, Next: Action Types, Prev: Multiple Types, Up: Semantics
1292 An action accompanies a syntactic rule and contains C code to be
1293 executed each time an instance of that rule is recognized. The task of
1294 most actions is to compute a semantic value for the grouping built by
1295 the rule from the semantic values associated with tokens or smaller
1298 An action consists of C statements surrounded by braces, much like a
1299 compound statement in C. It can be placed at any position in the rule;
1300 it is executed at that position. Most rules have just one action at
1301 the end of the rule, following all the components. Actions in the
1302 middle of a rule are tricky and used only for special purposes (*note
1303 Actions in Mid-Rule: Mid-Rule Actions.).
1305 The C code in an action can refer to the semantic values of the
1306 components matched by the rule with the construct `$N', which stands for
1307 the value of the Nth component. The semantic value for the grouping
1308 being constructed is `$$'. (Bison translates both of these constructs
1309 into array element references when it copies the actions into the parser
1312 Here is a typical example:
1318 This rule constructs an `exp' from two smaller `exp' groupings
1319 connected by a plus-sign token. In the action, `$1' and `$3' refer to
1320 the semantic values of the two component `exp' groupings, which are the
1321 first and third symbols on the right hand side of the rule. The sum is
1322 stored into `$$' so that it becomes the semantic value of the
1323 addition-expression just recognized by the rule. If there were a
1324 useful semantic value associated with the `+' token, it could be
1325 referred to as `$2'.
1327 If you don't specify an action for a rule, Bison supplies a default:
1328 `$$ = $1'. Thus, the value of the first symbol in the rule becomes the
1329 value of the whole rule. Of course, the default rule is valid only if
1330 the two data types match. There is no meaningful default action for an
1331 empty rule; every empty rule must have an explicit action unless the
1332 rule's value does not matter.
1334 `$N' with N zero or negative is allowed for reference to tokens and
1335 groupings on the stack _before_ those that match the current rule.
1336 This is a very risky practice, and to use it reliably you must be
1337 certain of the context in which the rule is applied. Here is a case in
1338 which you can use this reliably:
1340 foo: expr bar '+' expr { ... }
1341 | expr bar '-' expr { ... }
1345 { previous_expr = $0; }
1348 As long as `bar' is used only in the fashion shown here, `$0' always
1349 refers to the `expr' which precedes `bar' in the definition of `foo'.
1352 File: bison.info, Node: Action Types, Next: Mid-Rule Actions, Prev: Actions, Up: Semantics
1354 Data Types of Values in Actions
1355 -------------------------------
1357 If you have chosen a single data type for semantic values, the `$$'
1358 and `$N' constructs always have that data type.
1360 If you have used `%union' to specify a variety of data types, then
1361 you must declare a choice among these types for each terminal or
1362 nonterminal symbol that can have a semantic value. Then each time you
1363 use `$$' or `$N', its data type is determined by which symbol it refers
1364 to in the rule. In this example,
1370 `$1' and `$3' refer to instances of `exp', so they all have the data
1371 type declared for the nonterminal symbol `exp'. If `$2' were used, it
1372 would have the data type declared for the terminal symbol `'+'',
1373 whatever that might be.
1375 Alternatively, you can specify the data type when you refer to the
1376 value, by inserting `<TYPE>' after the `$' at the beginning of the
1377 reference. For example, if you have defined types as shown here:
1384 then you can write `$<itype>1' to refer to the first subunit of the
1385 rule as an integer, or `$<dtype>1' to refer to it as a double.