Manual
Manual
Manual
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 5: The Bison Parser Algorithm 73<br />
The conflict exists because the grammar as written is ambiguous: either parsing of the<br />
simple nested if-statement is legitimate. The established convention is that these ambiguities<br />
are resolved by attaching the else-clause to the innermost if-statement; this is what Bison<br />
accomplishes by choosing to shift rather than reduce. (It would ideally be cleaner to write an<br />
unambiguous grammar, but that is very hard to do in this case.) This particular ambiguity<br />
was first encountered in the specifications of Algol 60 and is called the “dangling else”<br />
ambiguity.<br />
To avoid warnings from Bison about predictable, legitimate shift/reduce conflicts, use<br />
the %expect n declaration. There will be no warning as long as the number of shift/reduce<br />
conflicts is exactly n. See Section 3.7.8 [Suppressing Conflict Warnings], page 57.<br />
The definition of if_stmt above is solely to blame for the conflict, but the conflict<br />
does not actually appear without additional rules. Here is a complete Bison input file that<br />
actually manifests the conflict:<br />
%token IF THEN ELSE variable<br />
%%<br />
stmt: expr<br />
| if_stmt<br />
;<br />
if_stmt:<br />
IF expr THEN stmt<br />
| IF expr THEN stmt ELSE stmt<br />
;<br />
expr:<br />
;<br />
variable<br />
5.3 Operator Precedence<br />
Another situation where shift/reduce conflicts appear is in arithmetic expressions. Here<br />
shifting is not always the preferred resolution; the Bison declarations for operator precedence<br />
allow you to specify when to shift and when to reduce.<br />
5.3.1 When Precedence is Needed<br />
Consider the following ambiguous grammar fragment (ambiguous because the input<br />
‘1 - 2 * 3’ can be parsed in two different ways):<br />
expr:<br />
expr ’-’ expr<br />
| expr ’*’ expr<br />
| expr ’