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