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