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