]> git.saurik.com Git - bison.git/blob - doc/bison.info-4
Version 1.30d.
[bison.git] / doc / bison.info-4
1 Ceci est le fichier Info bison.info, produit par Makeinfo version 4.0b
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, 2001 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: Action Features, Prev: Error Reporting, Up: Interface
33
34 Special Features for Use in Actions
35 ===================================
36
37 Here is a table of Bison constructs, variables and macros that are
38 useful in actions.
39
40 `$$'
41 Acts like a variable that contains the semantic value for the
42 grouping made by the current rule. *Note Actions::.
43
44 `$N'
45 Acts like a variable that contains the semantic value for the Nth
46 component of the current rule. *Note Actions::.
47
48 `$<TYPEALT>$'
49 Like `$$' but specifies alternative TYPEALT in the union specified
50 by the `%union' declaration. *Note Data Types of Values in
51 Actions: Action Types.
52
53 `$<TYPEALT>N'
54 Like `$N' but specifies alternative TYPEALT in the union specified
55 by the `%union' declaration. *Note Data Types of Values in
56 Actions: Action Types.
57
58 `YYABORT;'
59 Return immediately from `yyparse', indicating failure. *Note The
60 Parser Function `yyparse': Parser Function.
61
62 `YYACCEPT;'
63 Return immediately from `yyparse', indicating success. *Note The
64 Parser Function `yyparse': Parser Function.
65
66 `YYBACKUP (TOKEN, VALUE);'
67 Unshift a token. This macro is allowed only for rules that reduce
68 a single value, and only when there is no look-ahead token. It
69 installs a look-ahead token with token type TOKEN and semantic
70 value VALUE; then it discards the value that was going to be
71 reduced by this rule.
72
73 If the macro is used when it is not valid, such as when there is a
74 look-ahead token already, then it reports a syntax error with a
75 message `cannot back up' and performs ordinary error recovery.
76
77 In either case, the rest of the action is not executed.
78
79 `YYEMPTY'
80 Value stored in `yychar' when there is no look-ahead token.
81
82 `YYERROR;'
83 Cause an immediate syntax error. This statement initiates error
84 recovery just as if the parser itself had detected an error;
85 however, it does not call `yyerror', and does not print any
86 message. If you want to print an error message, call `yyerror'
87 explicitly before the `YYERROR;' statement. *Note Error
88 Recovery::.
89
90 `YYRECOVERING'
91 This macro stands for an expression that has the value 1 when the
92 parser is recovering from a syntax error, and 0 the rest of the
93 time. *Note Error Recovery::.
94
95 `yychar'
96 Variable containing the current look-ahead token. (In a pure
97 parser, this is actually a local variable within `yyparse'.) When
98 there is no look-ahead token, the value `YYEMPTY' is stored in the
99 variable. *Note Look-Ahead Tokens: Look-Ahead.
100
101 `yyclearin;'
102 Discard the current look-ahead token. This is useful primarily in
103 error rules. *Note Error Recovery::.
104
105 `yyerrok;'
106 Resume generating error messages immediately for subsequent syntax
107 errors. This is useful primarily in error rules. *Note Error
108 Recovery::.
109
110 `@$'
111 Acts like a structure variable containing information on the
112 textual position of the grouping made by the current rule. *Note
113 Tracking Locations: Locations.
114
115 `@N'
116 Acts like a structure variable containing information on the
117 textual position of the Nth component of the current rule. *Note
118 Tracking Locations: Locations.
119
120 \1f
121 File: bison.info, Node: Algorithm, Next: Error Recovery, Prev: Interface, Up: Top
122
123 The Bison Parser Algorithm
124 **************************
125
126 As Bison reads tokens, it pushes them onto a stack along with their
127 semantic values. The stack is called the "parser stack". Pushing a
128 token is traditionally called "shifting".
129
130 For example, suppose the infix calculator has read `1 + 5 *', with a
131 `3' to come. The stack will have four elements, one for each token
132 that was shifted.
133
134 But the stack does not always have an element for each token read.
135 When the last N tokens and groupings shifted match the components of a
136 grammar rule, they can be combined according to that rule. This is
137 called "reduction". Those tokens and groupings are replaced on the
138 stack by a single grouping whose symbol is the result (left hand side)
139 of that rule. Running the rule's action is part of the process of
140 reduction, because this is what computes the semantic value of the
141 resulting grouping.
142
143 For example, if the infix calculator's parser stack contains this:
144
145 1 + 5 * 3
146
147 and the next input token is a newline character, then the last three
148 elements can be reduced to 15 via the rule:
149
150 expr: expr '*' expr;
151
152 Then the stack contains just these three elements:
153
154 1 + 15
155
156 At this point, another reduction can be made, resulting in the single
157 value 16. Then the newline token can be shifted.
158
159 The parser tries, by shifts and reductions, to reduce the entire
160 input down to a single grouping whose symbol is the grammar's
161 start-symbol (*note Languages and Context-Free Grammars: Language and
162 Grammar.).
163
164 This kind of parser is known in the literature as a bottom-up parser.
165
166 * Menu:
167
168 * Look-Ahead:: Parser looks one token ahead when deciding what to do.
169 * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
170 * Precedence:: Operator precedence works by resolving conflicts.
171 * Contextual Precedence:: When an operator's precedence depends on context.
172 * Parser States:: The parser is a finite-state-machine with stack.
173 * Reduce/Reduce:: When two rules are applicable in the same situation.
174 * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
175 * Stack Overflow:: What happens when stack gets full. How to avoid it.
176
177 \1f
178 File: bison.info, Node: Look-Ahead, Next: Shift/Reduce, Up: Algorithm
179
180 Look-Ahead Tokens
181 =================
182
183 The Bison parser does _not_ always reduce immediately as soon as the
184 last N tokens and groupings match a rule. This is because such a
185 simple strategy is inadequate to handle most languages. Instead, when a
186 reduction is possible, the parser sometimes "looks ahead" at the next
187 token in order to decide what to do.
188
189 When a token is read, it is not immediately shifted; first it
190 becomes the "look-ahead token", which is not on the stack. Now the
191 parser can perform one or more reductions of tokens and groupings on
192 the stack, while the look-ahead token remains off to the side. When no
193 more reductions should take place, the look-ahead token is shifted onto
194 the stack. This does not mean that all possible reductions have been
195 done; depending on the token type of the look-ahead token, some rules
196 may choose to delay their application.
197
198 Here is a simple case where look-ahead is needed. These three rules
199 define expressions which contain binary addition operators and postfix
200 unary factorial operators (`!'), and allow parentheses for grouping.
201
202 expr: term '+' expr
203 | term
204 ;
205
206 term: '(' expr ')'
207 | term '!'
208 | NUMBER
209 ;
210
211 Suppose that the tokens `1 + 2' have been read and shifted; what
212 should be done? If the following token is `)', then the first three
213 tokens must be reduced to form an `expr'. This is the only valid
214 course, because shifting the `)' would produce a sequence of symbols
215 `term ')'', and no rule allows this.
216
217 If the following token is `!', then it must be shifted immediately so
218 that `2 !' can be reduced to make a `term'. If instead the parser were
219 to reduce before shifting, `1 + 2' would become an `expr'. It would
220 then be impossible to shift the `!' because doing so would produce on
221 the stack the sequence of symbols `expr '!''. No rule allows that
222 sequence.
223
224 The current look-ahead token is stored in the variable `yychar'.
225 *Note Special Features for Use in Actions: Action Features.
226
227 \1f
228 File: bison.info, Node: Shift/Reduce, Next: Precedence, Prev: Look-Ahead, Up: Algorithm
229
230 Shift/Reduce Conflicts
231 ======================
232
233 Suppose we are parsing a language which has if-then and if-then-else
234 statements, with a pair of rules like this:
235
236 if_stmt:
237 IF expr THEN stmt
238 | IF expr THEN stmt ELSE stmt
239 ;
240
241 Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
242 specific keyword tokens.
243
244 When the `ELSE' token is read and becomes the look-ahead token, the
245 contents of the stack (assuming the input is valid) are just right for
246 reduction by the first rule. But it is also legitimate to shift the
247 `ELSE', because that would lead to eventual reduction by the second
248 rule.
249
250 This situation, where either a shift or a reduction would be valid,
251 is called a "shift/reduce conflict". Bison is designed to resolve
252 these conflicts by choosing to shift, unless otherwise directed by
253 operator precedence declarations. To see the reason for this, let's
254 contrast it with the other alternative.
255
256 Since the parser prefers to shift the `ELSE', the result is to attach
257 the else-clause to the innermost if-statement, making these two inputs
258 equivalent:
259
260 if x then if y then win (); else lose;
261
262 if x then do; if y then win (); else lose; end;
263
264 But if the parser chose to reduce when possible rather than shift,
265 the result would be to attach the else-clause to the outermost
266 if-statement, making these two inputs equivalent:
267
268 if x then if y then win (); else lose;
269
270 if x then do; if y then win (); end; else lose;
271
272 The conflict exists because the grammar as written is ambiguous:
273 either parsing of the simple nested if-statement is legitimate. The
274 established convention is that these ambiguities are resolved by
275 attaching the else-clause to the innermost if-statement; this is what
276 Bison accomplishes by choosing to shift rather than reduce. (It would
277 ideally be cleaner to write an unambiguous grammar, but that is very
278 hard to do in this case.) This particular ambiguity was first
279 encountered in the specifications of Algol 60 and is called the
280 "dangling `else'" ambiguity.
281
282 To avoid warnings from Bison about predictable, legitimate
283 shift/reduce conflicts, use the `%expect N' declaration. There will be
284 no warning as long as the number of shift/reduce conflicts is exactly N.
285 *Note Suppressing Conflict Warnings: Expect Decl.
286
287 The definition of `if_stmt' above is solely to blame for the
288 conflict, but the conflict does not actually appear without additional
289 rules. Here is a complete Bison input file that actually manifests the
290 conflict:
291
292 %token IF THEN ELSE variable
293 %%
294 stmt: expr
295 | if_stmt
296 ;
297
298 if_stmt:
299 IF expr THEN stmt
300 | IF expr THEN stmt ELSE stmt
301 ;
302
303 expr: variable
304 ;
305
306 \1f
307 File: bison.info, Node: Precedence, Next: Contextual Precedence, Prev: Shift/Reduce, Up: Algorithm
308
309 Operator Precedence
310 ===================
311
312 Another situation where shift/reduce conflicts appear is in
313 arithmetic expressions. Here shifting is not always the preferred
314 resolution; the Bison declarations for operator precedence allow you to
315 specify when to shift and when to reduce.
316
317 * Menu:
318
319 * Why Precedence:: An example showing why precedence is needed.
320 * Using Precedence:: How to specify precedence in Bison grammars.
321 * Precedence Examples:: How these features are used in the previous example.
322 * How Precedence:: How they work.
323
324 \1f
325 File: bison.info, Node: Why Precedence, Next: Using Precedence, Up: Precedence
326
327 When Precedence is Needed
328 -------------------------
329
330 Consider the following ambiguous grammar fragment (ambiguous because
331 the input `1 - 2 * 3' can be parsed in two different ways):
332
333 expr: expr '-' expr
334 | expr '*' expr
335 | expr '<' expr
336 | '(' expr ')'
337 ...
338 ;
339
340 Suppose the parser has seen the tokens `1', `-' and `2'; should it
341 reduce them via the rule for the subtraction operator? It depends on
342 the next token. Of course, if the next token is `)', we must reduce;
343 shifting is invalid because no single rule can reduce the token
344 sequence `- 2 )' or anything starting with that. But if the next token
345 is `*' or `<', we have a choice: either shifting or reduction would
346 allow the parse to complete, but with different results.
347
348 To decide which one Bison should do, we must consider the results.
349 If the next operator token OP is shifted, then it must be reduced first
350 in order to permit another opportunity to reduce the difference. The
351 result is (in effect) `1 - (2 OP 3)'. On the other hand, if the
352 subtraction is reduced before shifting OP, the result is
353 `(1 - 2) OP 3'. Clearly, then, the choice of shift or reduce should
354 depend on the relative precedence of the operators `-' and OP: `*'
355 should be shifted first, but not `<'.
356
357 What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
358 or should it be `1 - (2 - 5)'? For most operators we prefer the
359 former, which is called "left association". The latter alternative,
360 "right association", is desirable for assignment operators. The choice
361 of left or right association is a matter of whether the parser chooses
362 to shift or reduce when the stack contains `1 - 2' and the look-ahead
363 token is `-': shifting makes right-associativity.
364
365 \1f
366 File: bison.info, Node: Using Precedence, Next: Precedence Examples, Prev: Why Precedence, Up: Precedence
367
368 Specifying Operator Precedence
369 ------------------------------
370
371 Bison allows you to specify these choices with the operator
372 precedence declarations `%left' and `%right'. Each such declaration
373 contains a list of tokens, which are operators whose precedence and
374 associativity is being declared. The `%left' declaration makes all
375 those operators left-associative and the `%right' declaration makes
376 them right-associative. A third alternative is `%nonassoc', which
377 declares that it is a syntax error to find the same operator twice "in a
378 row".
379
380 The relative precedence of different operators is controlled by the
381 order in which they are declared. The first `%left' or `%right'
382 declaration in the file declares the operators whose precedence is
383 lowest, the next such declaration declares the operators whose
384 precedence is a little higher, and so on.
385
386 \1f
387 File: bison.info, Node: Precedence Examples, Next: How Precedence, Prev: Using Precedence, Up: Precedence
388
389 Precedence Examples
390 -------------------
391
392 In our example, we would want the following declarations:
393
394 %left '<'
395 %left '-'
396 %left '*'
397
398 In a more complete example, which supports other operators as well,
399 we would declare them in groups of equal precedence. For example,
400 `'+'' is declared with `'-'':
401
402 %left '<' '>' '=' NE LE GE
403 %left '+' '-'
404 %left '*' '/'
405
406 (Here `NE' and so on stand for the operators for "not equal" and so on.
407 We assume that these tokens are more than one character long and
408 therefore are represented by names, not character literals.)
409
410 \1f
411 File: bison.info, Node: How Precedence, Prev: Precedence Examples, Up: Precedence
412
413 How Precedence Works
414 --------------------
415
416 The first effect of the precedence declarations is to assign
417 precedence levels to the terminal symbols declared. The second effect
418 is to assign precedence levels to certain rules: each rule gets its
419 precedence from the last terminal symbol mentioned in the components.
420 (You can also specify explicitly the precedence of a rule. *Note
421 Context-Dependent Precedence: Contextual Precedence.)
422
423 Finally, the resolution of conflicts works by comparing the
424 precedence of the rule being considered with that of the look-ahead
425 token. If the token's precedence is higher, the choice is to shift.
426 If the rule's precedence is higher, the choice is to reduce. If they
427 have equal precedence, the choice is made based on the associativity of
428 that precedence level. The verbose output file made by `-v' (*note
429 Invoking Bison: Invocation.) says how each conflict was resolved.
430
431 Not all rules and not all tokens have precedence. If either the
432 rule or the look-ahead token has no precedence, then the default is to
433 shift.
434
435 \1f
436 File: bison.info, Node: Contextual Precedence, Next: Parser States, Prev: Precedence, Up: Algorithm
437
438 Context-Dependent Precedence
439 ============================
440
441 Often the precedence of an operator depends on the context. This
442 sounds outlandish at first, but it is really very common. For example,
443 a minus sign typically has a very high precedence as a unary operator,
444 and a somewhat lower precedence (lower than multiplication) as a binary
445 operator.
446
447 The Bison precedence declarations, `%left', `%right' and
448 `%nonassoc', can only be used once for a given token; so a token has
449 only one precedence declared in this way. For context-dependent
450 precedence, you need to use an additional mechanism: the `%prec'
451 modifier for rules.
452
453 The `%prec' modifier declares the precedence of a particular rule by
454 specifying a terminal symbol whose precedence should be used for that
455 rule. It's not necessary for that symbol to appear otherwise in the
456 rule. The modifier's syntax is:
457
458 %prec TERMINAL-SYMBOL
459
460 and it is written after the components of the rule. Its effect is to
461 assign the rule the precedence of TERMINAL-SYMBOL, overriding the
462 precedence that would be deduced for it in the ordinary way. The
463 altered rule precedence then affects how conflicts involving that rule
464 are resolved (*note Operator Precedence: Precedence.).
465
466 Here is how `%prec' solves the problem of unary minus. First,
467 declare a precedence for a fictitious terminal symbol named `UMINUS'.
468 There are no tokens of this type, but the symbol serves to stand for its
469 precedence:
470
471 ...
472 %left '+' '-'
473 %left '*'
474 %left UMINUS
475
476 Now the precedence of `UMINUS' can be used in specific rules:
477
478 exp: ...
479 | exp '-' exp
480 ...
481 | '-' exp %prec UMINUS
482
483 \1f
484 File: bison.info, Node: Parser States, Next: Reduce/Reduce, Prev: Contextual Precedence, Up: Algorithm
485
486 Parser States
487 =============
488
489 The function `yyparse' is implemented using a finite-state machine.
490 The values pushed on the parser stack are not simply token type codes;
491 they represent the entire sequence of terminal and nonterminal symbols
492 at or near the top of the stack. The current state collects all the
493 information about previous input which is relevant to deciding what to
494 do next.
495
496 Each time a look-ahead token is read, the current parser state
497 together with the type of look-ahead token are looked up in a table.
498 This table entry can say, "Shift the look-ahead token." In this case,
499 it also specifies the new parser state, which is pushed onto the top of
500 the parser stack. Or it can say, "Reduce using rule number N." This
501 means that a certain number of tokens or groupings are taken off the
502 top of the stack, and replaced by one grouping. In other words, that
503 number of states are popped from the stack, and one new state is pushed.
504
505 There is one other alternative: the table can say that the
506 look-ahead token is erroneous in the current state. This causes error
507 processing to begin (*note Error Recovery::).
508
509 \1f
510 File: bison.info, Node: Reduce/Reduce, Next: Mystery Conflicts, Prev: Parser States, Up: Algorithm
511
512 Reduce/Reduce Conflicts
513 =======================
514
515 A reduce/reduce conflict occurs if there are two or more rules that
516 apply to the same sequence of input. This usually indicates a serious
517 error in the grammar.
518
519 For example, here is an erroneous attempt to define a sequence of
520 zero or more `word' groupings.
521
522 sequence: /* empty */
523 { printf ("empty sequence\n"); }
524 | maybeword
525 | sequence word
526 { printf ("added word %s\n", $2); }
527 ;
528
529 maybeword: /* empty */
530 { printf ("empty maybeword\n"); }
531 | word
532 { printf ("single word %s\n", $1); }
533 ;
534
535 The error is an ambiguity: there is more than one way to parse a single
536 `word' into a `sequence'. It could be reduced to a `maybeword' and
537 then into a `sequence' via the second rule. Alternatively,
538 nothing-at-all could be reduced into a `sequence' via the first rule,
539 and this could be combined with the `word' using the third rule for
540 `sequence'.
541
542 There is also more than one way to reduce nothing-at-all into a
543 `sequence'. This can be done directly via the first rule, or
544 indirectly via `maybeword' and then the second rule.
545
546 You might think that this is a distinction without a difference,
547 because it does not change whether any particular input is valid or
548 not. But it does affect which actions are run. One parsing order runs
549 the second rule's action; the other runs the first rule's action and
550 the third rule's action. In this example, the output of the program
551 changes.
552
553 Bison resolves a reduce/reduce conflict by choosing to use the rule
554 that appears first in the grammar, but it is very risky to rely on
555 this. Every reduce/reduce conflict must be studied and usually
556 eliminated. Here is the proper way to define `sequence':
557
558 sequence: /* empty */
559 { printf ("empty sequence\n"); }
560 | sequence word
561 { printf ("added word %s\n", $2); }
562 ;
563
564 Here is another common error that yields a reduce/reduce conflict:
565
566 sequence: /* empty */
567 | sequence words
568 | sequence redirects
569 ;
570
571 words: /* empty */
572 | words word
573 ;
574
575 redirects:/* empty */
576 | redirects redirect
577 ;
578
579 The intention here is to define a sequence which can contain either
580 `word' or `redirect' groupings. The individual definitions of
581 `sequence', `words' and `redirects' are error-free, but the three
582 together make a subtle ambiguity: even an empty input can be parsed in
583 infinitely many ways!
584
585 Consider: nothing-at-all could be a `words'. Or it could be two
586 `words' in a row, or three, or any number. It could equally well be a
587 `redirects', or two, or any number. Or it could be a `words' followed
588 by three `redirects' and another `words'. And so on.
589
590 Here are two ways to correct these rules. First, to make it a
591 single level of sequence:
592
593 sequence: /* empty */
594 | sequence word
595 | sequence redirect
596 ;
597
598 Second, to prevent either a `words' or a `redirects' from being
599 empty:
600
601 sequence: /* empty */
602 | sequence words
603 | sequence redirects
604 ;
605
606 words: word
607 | words word
608 ;
609
610 redirects:redirect
611 | redirects redirect
612 ;
613
614 \1f
615 File: bison.info, Node: Mystery Conflicts, Next: Stack Overflow, Prev: Reduce/Reduce, Up: Algorithm
616
617 Mysterious Reduce/Reduce Conflicts
618 ==================================
619
620 Sometimes reduce/reduce conflicts can occur that don't look
621 warranted. Here is an example:
622
623 %token ID
624
625 %%
626 def: param_spec return_spec ','
627 ;
628 param_spec:
629 type
630 | name_list ':' type
631 ;
632 return_spec:
633 type
634 | name ':' type
635 ;
636 type: ID
637 ;
638 name: ID
639 ;
640 name_list:
641 name
642 | name ',' name_list
643 ;
644
645 It would seem that this grammar can be parsed with only a single
646 token of look-ahead: when a `param_spec' is being read, an `ID' is a
647 `name' if a comma or colon follows, or a `type' if another `ID'
648 follows. In other words, this grammar is LR(1).
649
650 However, Bison, like most parser generators, cannot actually handle
651 all LR(1) grammars. In this grammar, two contexts, that after an `ID'
652 at the beginning of a `param_spec' and likewise at the beginning of a
653 `return_spec', are similar enough that Bison assumes they are the same.
654 They appear similar because the same set of rules would be active--the
655 rule for reducing to a `name' and that for reducing to a `type'. Bison
656 is unable to determine at that stage of processing that the rules would
657 require different look-ahead tokens in the two contexts, so it makes a
658 single parser state for them both. Combining the two contexts causes a
659 conflict later. In parser terminology, this occurrence means that the
660 grammar is not LALR(1).
661
662 In general, it is better to fix deficiencies than to document them.
663 But this particular deficiency is intrinsically hard to fix; parser
664 generators that can handle LR(1) grammars are hard to write and tend to
665 produce parsers that are very large. In practice, Bison is more useful
666 as it is now.
667
668 When the problem arises, you can often fix it by identifying the two
669 parser states that are being confused, and adding something to make them
670 look distinct. In the above example, adding one rule to `return_spec'
671 as follows makes the problem go away:
672
673 %token BOGUS
674 ...
675 %%
676 ...
677 return_spec:
678 type
679 | name ':' type
680 /* This rule is never used. */
681 | ID BOGUS
682 ;
683
684 This corrects the problem because it introduces the possibility of an
685 additional active rule in the context after the `ID' at the beginning of
686 `return_spec'. This rule is not active in the corresponding context in
687 a `param_spec', so the two contexts receive distinct parser states. As
688 long as the token `BOGUS' is never generated by `yylex', the added rule
689 cannot alter the way actual input is parsed.
690
691 In this particular example, there is another way to solve the
692 problem: rewrite the rule for `return_spec' to use `ID' directly
693 instead of via `name'. This also causes the two confusing contexts to
694 have different sets of active rules, because the one for `return_spec'
695 activates the altered rule for `return_spec' rather than the one for
696 `name'.
697
698 param_spec:
699 type
700 | name_list ':' type
701 ;
702 return_spec:
703 type
704 | ID ':' type
705 ;
706
707 \1f
708 File: bison.info, Node: Stack Overflow, Prev: Mystery Conflicts, Up: Algorithm
709
710 Stack Overflow, and How to Avoid It
711 ===================================
712
713 The Bison parser stack can overflow if too many tokens are shifted
714 and not reduced. When this happens, the parser function `yyparse'
715 returns a nonzero value, pausing only to call `yyerror' to report the
716 overflow.
717
718 By defining the macro `YYMAXDEPTH', you can control how deep the
719 parser stack can become before a stack overflow occurs. Define the
720 macro with a value that is an integer. This value is the maximum number
721 of tokens that can be shifted (and not reduced) before overflow. It
722 must be a constant expression whose value is known at compile time.
723
724 The stack space allowed is not necessarily allocated. If you
725 specify a large value for `YYMAXDEPTH', the parser actually allocates a
726 small stack at first, and then makes it bigger by stages as needed.
727 This increasing allocation happens automatically and silently.
728 Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
729 to save space for ordinary inputs that do not need much stack.
730
731 The default value of `YYMAXDEPTH', if you do not define it, is 10000.
732
733 You can control how much stack is allocated initially by defining the
734 macro `YYINITDEPTH'. This value too must be a compile-time constant
735 integer. The default is 200.
736
737 \1f
738 File: bison.info, Node: Error Recovery, Next: Context Dependency, Prev: Algorithm, Up: Top
739
740 Error Recovery
741 **************
742
743 It is not usually acceptable to have a program terminate on a parse
744 error. For example, a compiler should recover sufficiently to parse the
745 rest of the input file and check it for errors; a calculator should
746 accept another expression.
747
748 In a simple interactive command parser where each input is one line,
749 it may be sufficient to allow `yyparse' to return 1 on error and have
750 the caller ignore the rest of the input line when that happens (and
751 then call `yyparse' again). But this is inadequate for a compiler,
752 because it forgets all the syntactic context leading up to the error.
753 A syntax error deep within a function in the compiler input should not
754 cause the compiler to treat the following line like the beginning of a
755 source file.
756
757 You can define how to recover from a syntax error by writing rules to
758 recognize the special token `error'. This is a terminal symbol that is
759 always defined (you need not declare it) and reserved for error
760 handling. The Bison parser generates an `error' token whenever a
761 syntax error happens; if you have provided a rule to recognize this
762 token in the current context, the parse can continue.
763
764 For example:
765
766 stmnts: /* empty string */
767 | stmnts '\n'
768 | stmnts exp '\n'
769 | stmnts error '\n'
770
771 The fourth rule in this example says that an error followed by a
772 newline makes a valid addition to any `stmnts'.
773
774 What happens if a syntax error occurs in the middle of an `exp'? The
775 error recovery rule, interpreted strictly, applies to the precise
776 sequence of a `stmnts', an `error' and a newline. If an error occurs in
777 the middle of an `exp', there will probably be some additional tokens
778 and subexpressions on the stack after the last `stmnts', and there will
779 be tokens to read before the next newline. So the rule is not
780 applicable in the ordinary way.
781
782 But Bison can force the situation to fit the rule, by discarding
783 part of the semantic context and part of the input. First it discards
784 states and objects from the stack until it gets back to a state in
785 which the `error' token is acceptable. (This means that the
786 subexpressions already parsed are discarded, back to the last complete
787 `stmnts'.) At this point the `error' token can be shifted. Then, if
788 the old look-ahead token is not acceptable to be shifted next, the
789 parser reads tokens and discards them until it finds a token which is
790 acceptable. In this example, Bison reads and discards input until the
791 next newline so that the fourth rule can apply.
792
793 The choice of error rules in the grammar is a choice of strategies
794 for error recovery. A simple and useful strategy is simply to skip the
795 rest of the current input line or current statement if an error is
796 detected:
797
798 stmnt: error ';' /* on error, skip until ';' is read */
799
800 It is also useful to recover to the matching close-delimiter of an
801 opening-delimiter that has already been parsed. Otherwise the
802 close-delimiter will probably appear to be unmatched, and generate
803 another, spurious error message:
804
805 primary: '(' expr ')'
806 | '(' error ')'
807 ...
808 ;
809
810 Error recovery strategies are necessarily guesses. When they guess
811 wrong, one syntax error often leads to another. In the above example,
812 the error recovery rule guesses that an error is due to bad input
813 within one `stmnt'. Suppose that instead a spurious semicolon is
814 inserted in the middle of a valid `stmnt'. After the error recovery
815 rule recovers from the first error, another syntax error will be found
816 straightaway, since the text following the spurious semicolon is also
817 an invalid `stmnt'.
818
819 To prevent an outpouring of error messages, the parser will output
820 no error message for another syntax error that happens shortly after
821 the first; only after three consecutive input tokens have been
822 successfully shifted will error messages resume.
823
824 Note that rules which accept the `error' token may have actions, just
825 as any other rules can.
826
827 You can make error messages resume immediately by using the macro
828 `yyerrok' in an action. If you do this in the error rule's action, no
829 error messages will be suppressed. This macro requires no arguments;
830 `yyerrok;' is a valid C statement.
831
832 The previous look-ahead token is reanalyzed immediately after an
833 error. If this is unacceptable, then the macro `yyclearin' may be used
834 to clear this token. Write the statement `yyclearin;' in the error
835 rule's action.
836
837 For example, suppose that on a parse error, an error handling
838 routine is called that advances the input stream to some point where
839 parsing should once again commence. The next symbol returned by the
840 lexical scanner is probably correct. The previous look-ahead token
841 ought to be discarded with `yyclearin;'.
842
843 The macro `YYRECOVERING' stands for an expression that has the value
844 1 when the parser is recovering from a syntax error, and 0 the rest of
845 the time. A value of 1 indicates that error messages are currently
846 suppressed for new syntax errors.
847
848 \1f
849 File: bison.info, Node: Context Dependency, Next: Debugging, Prev: Error Recovery, Up: Top
850
851 Handling Context Dependencies
852 *****************************
853
854 The Bison paradigm is to parse tokens first, then group them into
855 larger syntactic units. In many languages, the meaning of a token is
856 affected by its context. Although this violates the Bison paradigm,
857 certain techniques (known as "kludges") may enable you to write Bison
858 parsers for such languages.
859
860 * Menu:
861
862 * Semantic Tokens:: Token parsing can depend on the semantic context.
863 * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
864 * Tie-in Recovery:: Lexical tie-ins have implications for how
865 error recovery rules must be written.
866
867 (Actually, "kludge" means any technique that gets its job done but is
868 neither clean nor robust.)
869
870 \1f
871 File: bison.info, Node: Semantic Tokens, Next: Lexical Tie-ins, Up: Context Dependency
872
873 Semantic Info in Token Types
874 ============================
875
876 The C language has a context dependency: the way an identifier is
877 used depends on what its current meaning is. For example, consider
878 this:
879
880 foo (x);
881
882 This looks like a function call statement, but if `foo' is a typedef
883 name, then this is actually a declaration of `x'. How can a Bison
884 parser for C decide how to parse this input?
885
886 The method used in GNU C is to have two different token types,
887 `IDENTIFIER' and `TYPENAME'. When `yylex' finds an identifier, it
888 looks up the current declaration of the identifier in order to decide
889 which token type to return: `TYPENAME' if the identifier is declared as
890 a typedef, `IDENTIFIER' otherwise.
891
892 The grammar rules can then express the context dependency by the
893 choice of token type to recognize. `IDENTIFIER' is accepted as an
894 expression, but `TYPENAME' is not. `TYPENAME' can start a declaration,
895 but `IDENTIFIER' cannot. In contexts where the meaning of the
896 identifier is _not_ significant, such as in declarations that can
897 shadow a typedef name, either `TYPENAME' or `IDENTIFIER' is
898 accepted--there is one rule for each of the two token types.
899
900 This technique is simple to use if the decision of which kinds of
901 identifiers to allow is made at a place close to where the identifier is
902 parsed. But in C this is not always so: C allows a declaration to
903 redeclare a typedef name provided an explicit type has been specified
904 earlier:
905
906 typedef int foo, bar, lose;
907 static foo (bar); /* redeclare `bar' as static variable */
908 static int foo (lose); /* redeclare `foo' as function */
909
910 Unfortunately, the name being declared is separated from the
911 declaration construct itself by a complicated syntactic structure--the
912 "declarator".
913
914 As a result, part of the Bison parser for C needs to be duplicated,
915 with all the nonterminal names changed: once for parsing a declaration
916 in which a typedef name can be redefined, and once for parsing a
917 declaration in which that can't be done. Here is a part of the
918 duplication, with actions omitted for brevity:
919
920 initdcl:
921 declarator maybeasm '='
922 init
923 | declarator maybeasm
924 ;
925
926 notype_initdcl:
927 notype_declarator maybeasm '='
928 init
929 | notype_declarator maybeasm
930 ;
931
932 Here `initdcl' can redeclare a typedef name, but `notype_initdcl'
933 cannot. The distinction between `declarator' and `notype_declarator'
934 is the same sort of thing.
935
936 There is some similarity between this technique and a lexical tie-in
937 (described next), in that information which alters the lexical analysis
938 is changed during parsing by other parts of the program. The
939 difference is here the information is global, and is used for other
940 purposes in the program. A true lexical tie-in has a special-purpose
941 flag controlled by the syntactic context.
942
943 \1f
944 File: bison.info, Node: Lexical Tie-ins, Next: Tie-in Recovery, Prev: Semantic Tokens, Up: Context Dependency
945
946 Lexical Tie-ins
947 ===============
948
949 One way to handle context-dependency is the "lexical tie-in": a flag
950 which is set by Bison actions, whose purpose is to alter the way tokens
951 are parsed.
952
953 For example, suppose we have a language vaguely like C, but with a
954 special construct `hex (HEX-EXPR)'. After the keyword `hex' comes an
955 expression in parentheses in which all integers are hexadecimal. In
956 particular, the token `a1b' must be treated as an integer rather than
957 as an identifier if it appears in that context. Here is how you can do
958 it:
959
960 %{
961 int hexflag;
962 %}
963 %%
964 ...
965 expr: IDENTIFIER
966 | constant
967 | HEX '('
968 { hexflag = 1; }
969 expr ')'
970 { hexflag = 0;
971 $$ = $4; }
972 | expr '+' expr
973 { $$ = make_sum ($1, $3); }
974 ...
975 ;
976
977 constant:
978 INTEGER
979 | STRING
980 ;
981
982 Here we assume that `yylex' looks at the value of `hexflag'; when it is
983 nonzero, all integers are parsed in hexadecimal, and tokens starting
984 with letters are parsed as integers if possible.
985
986 The declaration of `hexflag' shown in the C declarations section of
987 the parser file is needed to make it accessible to the actions (*note
988 The C Declarations Section: C Declarations.). You must also write the
989 code in `yylex' to obey the flag.
990
991 \1f
992 File: bison.info, Node: Tie-in Recovery, Prev: Lexical Tie-ins, Up: Context Dependency
993
994 Lexical Tie-ins and Error Recovery
995 ==================================
996
997 Lexical tie-ins make strict demands on any error recovery rules you
998 have. *Note Error Recovery::.
999
1000 The reason for this is that the purpose of an error recovery rule is
1001 to abort the parsing of one construct and resume in some larger
1002 construct. For example, in C-like languages, a typical error recovery
1003 rule is to skip tokens until the next semicolon, and then start a new
1004 statement, like this:
1005
1006 stmt: expr ';'
1007 | IF '(' expr ')' stmt { ... }
1008 ...
1009 error ';'
1010 { hexflag = 0; }
1011 ;
1012
1013 If there is a syntax error in the middle of a `hex (EXPR)'
1014 construct, this error rule will apply, and then the action for the
1015 completed `hex (EXPR)' will never run. So `hexflag' would remain set
1016 for the entire rest of the input, or until the next `hex' keyword,
1017 causing identifiers to be misinterpreted as integers.
1018
1019 To avoid this problem the error recovery rule itself clears
1020 `hexflag'.
1021
1022 There may also be an error recovery rule that works within
1023 expressions. For example, there could be a rule which applies within
1024 parentheses and skips to the close-parenthesis:
1025
1026 expr: ...
1027 | '(' expr ')'
1028 { $$ = $2; }
1029 | '(' error ')'
1030 ...
1031
1032 If this rule acts within the `hex' construct, it is not going to
1033 abort that construct (since it applies to an inner level of parentheses
1034 within the construct). Therefore, it should not clear the flag: the
1035 rest of the `hex' construct should be parsed with the flag still in
1036 effect.
1037
1038 What if there is an error recovery rule which might abort out of the
1039 `hex' construct or might not, depending on circumstances? There is no
1040 way you can write the action to determine whether a `hex' construct is
1041 being aborted or not. So if you are using a lexical tie-in, you had
1042 better make sure your error recovery rules are not of this kind. Each
1043 rule must be such that you can be sure that it always will, or always
1044 won't, have to clear the flag.
1045
1046 \1f
1047 File: bison.info, Node: Debugging, Next: Invocation, Prev: Context Dependency, Up: Top
1048
1049 Debugging Your Parser
1050 *********************
1051
1052 If a Bison grammar compiles properly but doesn't do what you want
1053 when it runs, the `yydebug' parser-trace feature can help you figure
1054 out why.
1055
1056 To enable compilation of trace facilities, you must define the macro
1057 `YYDEBUG' when you compile the parser. You could use `-DYYDEBUG=1' as
1058 a compiler option or you could put `#define YYDEBUG 1' in the C
1059 declarations section of the grammar file (*note The C Declarations
1060 Section: C Declarations.). Alternatively, use the `-t' option when you
1061 run Bison (*note Invoking Bison: Invocation.). We always define
1062 `YYDEBUG' so that debugging is always possible.
1063
1064 The trace facility uses `stderr', so you must add
1065 `#include <stdio.h>' to the C declarations section unless it is already
1066 there.
1067
1068 Once you have compiled the program with trace facilities, the way to
1069 request a trace is to store a nonzero value in the variable `yydebug'.
1070 You can do this by making the C code do it (in `main', perhaps), or you
1071 can alter the value with a C debugger.
1072
1073 Each step taken by the parser when `yydebug' is nonzero produces a
1074 line or two of trace information, written on `stderr'. The trace
1075 messages tell you these things:
1076
1077 * Each time the parser calls `yylex', what kind of token was read.
1078
1079 * Each time a token is shifted, the depth and complete contents of
1080 the state stack (*note Parser States::).
1081
1082 * Each time a rule is reduced, which rule it is, and the complete
1083 contents of the state stack afterward.
1084
1085 To make sense of this information, it helps to refer to the listing
1086 file produced by the Bison `-v' option (*note Invoking Bison:
1087 Invocation.). This file shows the meaning of each state in terms of
1088 positions in various rules, and also what each state will do with each
1089 possible input token. As you read the successive trace messages, you
1090 can see that the parser is functioning according to its specification
1091 in the listing file. Eventually you will arrive at the place where
1092 something undesirable happens, and you will see which parts of the
1093 grammar are to blame.
1094
1095 The parser file is a C program and you can use C debuggers on it,
1096 but it's not easy to interpret what it is doing. The parser function
1097 is a finite-state machine interpreter, and aside from the actions it
1098 executes the same code over and over. Only the values of variables
1099 show where in the grammar it is working.
1100
1101 The debugging information normally gives the token type of each token
1102 read, but not its semantic value. You can optionally define a macro
1103 named `YYPRINT' to provide a way to print the value. If you define
1104 `YYPRINT', it should take three arguments. The parser will pass a
1105 standard I/O stream, the numeric code for the token type, and the token
1106 value (from `yylval').
1107
1108 Here is an example of `YYPRINT' suitable for the multi-function
1109 calculator (*note Declarations for `mfcalc': Mfcalc Decl.):
1110
1111 #define YYPRINT(file, type, value) yyprint (file, type, value)
1112
1113 static void
1114 yyprint (FILE *file, int type, YYSTYPE value)
1115 {
1116 if (type == VAR)
1117 fprintf (file, " %s", value.tptr->name);
1118 else if (type == NUM)
1119 fprintf (file, " %d", value.val);
1120 }
1121
1122 \1f
1123 File: bison.info, Node: Invocation, Next: Table of Symbols, Prev: Debugging, Up: Top
1124
1125 Invoking Bison
1126 **************
1127
1128 The usual way to invoke Bison is as follows:
1129
1130 bison INFILE
1131
1132 Here INFILE is the grammar file name, which usually ends in `.y'.
1133 The parser file's name is made by replacing the `.y' with `.tab.c'.
1134 Thus, the `bison foo.y' filename yields `foo.tab.c', and the `bison
1135 hack/foo.y' filename yields `hack/foo.tab.c'. It's is also possible, in
1136 case you are writting C++ code instead of C in your grammar file, to
1137 name it `foo.ypp' or `foo.y++'. Then, the output files will take an
1138 extention like the given one as input (repectively `foo.tab.cpp' and
1139 `foo.tab.c++'). This feature takes effect with all options that
1140 manipulate filenames like `-o' or `-d'.
1141
1142 For example :
1143
1144 bison -d INFILE.YXX
1145
1146 will produce `infile.tab.cxx' and `infile.tab.hxx'. and
1147
1148 bison -d INFILE.Y -o OUTPUT.C++
1149
1150 will produce `output.c++' and `outfile.h++'.
1151
1152 * Menu:
1153
1154 * Bison Options:: All the options described in detail,
1155 in alphabetical order by short options.
1156 * Environment Variables:: Variables which affect Bison execution.
1157 * Option Cross Key:: Alphabetical list of long options.
1158 * VMS Invocation:: Bison command syntax on VMS.
1159
1160 \1f
1161 File: bison.info, Node: Bison Options, Next: Environment Variables, Up: Invocation
1162
1163 Bison Options
1164 =============
1165
1166 Bison supports both traditional single-letter options and mnemonic
1167 long option names. Long option names are indicated with `--' instead of
1168 `-'. Abbreviations for option names are allowed as long as they are
1169 unique. When a long option takes an argument, like `--file-prefix',
1170 connect the option name and the argument with `='.
1171
1172 Here is a list of options that can be used with Bison, alphabetized
1173 by short option. It is followed by a cross key alphabetized by long
1174 option.
1175
1176 Operations modes:
1177 `-h'
1178 `--help'
1179 Print a summary of the command-line options to Bison and exit.
1180
1181 `-V'
1182 `--version'
1183 Print the version number of Bison and exit.
1184
1185 `-y'
1186 `--yacc'
1187 `--fixed-output-files'
1188 Equivalent to `-o y.tab.c'; the parser output file is called
1189 `y.tab.c', and the other outputs are called `y.output' and
1190 `y.tab.h'. The purpose of this option is to imitate Yacc's output
1191 file name conventions. Thus, the following shell script can
1192 substitute for Yacc:
1193
1194 bison -y $*
1195
1196 Tuning the parser:
1197
1198 `-S FILE'
1199 `--skeleton=FILE'
1200 Specify the skeleton to use. You probably don't need this option
1201 unless you are developing Bison.
1202
1203 `-t'
1204 `--debug'
1205 Output a definition of the macro `YYDEBUG' into the parser file, so
1206 that the debugging facilities are compiled. *Note Debugging Your
1207 Parser: Debugging.
1208
1209 `--locations'
1210 Pretend that `%locations' was specified. *Note Decl Summary::.
1211
1212 `-p PREFIX'
1213 `--name-prefix=PREFIX'
1214 Pretend that `%name-prefix="PREFIX"' was specified. *Note Decl
1215 Summary::.
1216
1217 `-l'
1218 `--no-lines'
1219 Don't put any `#line' preprocessor commands in the parser file.
1220 Ordinarily Bison puts them in the parser file so that the C
1221 compiler and debuggers will associate errors with your source
1222 file, the grammar file. This option causes them to associate
1223 errors with the parser file, treating it as an independent source
1224 file in its own right.
1225
1226 `-n'
1227 `--no-parser'
1228 Pretend that `%no-parser' was specified. *Note Decl Summary::.
1229
1230 `-k'
1231 `--token-table'
1232 Pretend that `%token-table' was specified. *Note Decl Summary::.
1233
1234 Adjust the output:
1235
1236 `-d'
1237 `--defines'
1238 Pretend that `%defines' was specified, i.e., write an extra output
1239 file containing macro definitions for the token type names defined
1240 in the grammar and the semantic value type `YYSTYPE', as well as a
1241 few `extern' variable declarations. *Note Decl Summary::.
1242
1243 `--defines=DEFINES-FILE'
1244 Same as above, but save in the file DEFINES-FILE.
1245
1246 `-b FILE-PREFIX'
1247 `--file-prefix=PREFIX'
1248 Pretend that `%verbose' was specified, i.e, specify prefix to use
1249 for all Bison output file names. *Note Decl Summary::.
1250
1251 `-v'
1252 `--verbose'
1253 Pretend that `%verbose' was specified, i.e, write an extra output
1254 file containing verbose descriptions of the grammar and parser.
1255 *Note Decl Summary::.
1256
1257 `-o FILENAME'
1258 `--output=FILENAME'
1259 Specify the FILENAME for the parser file.
1260
1261 The other output files' names are constructed from FILENAME as
1262 described under the `-v' and `-d' options.
1263
1264 `-g'
1265 Output a VCG definition of the LALR(1) grammar automaton computed
1266 by Bison. If the grammar file is `foo.y', the VCG output file will
1267 be `foo.vcg'.
1268
1269 `--graph=GRAPH-FILE'
1270 The behaviour of -GRAPH is the same than `-g'. The only difference
1271 is that it has an optionnal argument which is the name of the
1272 output graph filename.
1273
1274 \1f
1275 File: bison.info, Node: Environment Variables, Next: Option Cross Key, Prev: Bison Options, Up: Invocation
1276
1277 Environment Variables
1278 =====================
1279
1280 Here is a list of environment variables which affect the way Bison
1281 runs.
1282
1283 `BISON_SIMPLE'
1284 `BISON_HAIRY'
1285 Much of the parser generated by Bison is copied verbatim from a
1286 file called `bison.simple'. If Bison cannot find that file, or if
1287 you would like to direct Bison to use a different copy, setting the
1288 environment variable `BISON_SIMPLE' to the path of the file will
1289 cause Bison to use that copy instead.
1290
1291 When the `%semantic_parser' declaration is used, Bison copies from
1292 a file called `bison.hairy' instead. The location of this file can
1293 also be specified or overridden in a similar fashion, with the
1294 `BISON_HAIRY' environment variable.
1295
1296 \1f
1297 File: bison.info, Node: Option Cross Key, Next: VMS Invocation, Prev: Environment Variables, Up: Invocation
1298
1299 Option Cross Key
1300 ================
1301
1302 Here is a list of options, alphabetized by long option, to help you
1303 find the corresponding short option.
1304
1305 --debug -t
1306 --defines=DEFINES-FILE -d
1307 --file-prefix=PREFIX -b FILE-PREFIX
1308 --fixed-output-files --yacc -y
1309 --graph=GRAPH-FILE -d
1310 --help -h
1311 --name-prefix=PREFIX -p NAME-PREFIX
1312 --no-lines -l
1313 --no-parser -n
1314 --output=OUTFILE -o OUTFILE
1315 --token-table -k
1316 --verbose -v
1317 --version -V
1318