Sub topic 9
Ambiguity and how to resolve it
This chapter assumes you can write a context-free grammar, derive strings from it, and draw a parse tree. It builds on leftmost and rightmost derivations. The goal is to recognize an ambiguous grammar, show that it is ambiguous, and fix it in the ways GATE questions expect.
What ambiguity means
A grammar is ambiguous if some string in its language has more than one parse tree. Equivalently, that string has more than one leftmost derivation, or more than one rightmost derivation. Counting plain derivations is not enough, because one parse tree can be reached by many derivation orders. Only the leftmost or rightmost form gives a one-to-one match with trees.
Ambiguity matters because the parse tree carries the meaning. If 2 + 3 * 4 can be parsed two ways, a compiler cannot decide whether the answer is 14 or 20.
Ambiguity is a property of the grammar, not of the language. Many languages have both an ambiguous and an unambiguous grammar. A few context-free languages are inherently ambiguous, which means every grammar for them is ambiguous. One example is { aⁱbʲcᵏ : i = j or j = k }.
The classic example
Consider this grammar for arithmetic:
E -> E + E | E * E | ( E ) | idThe string id + id * id has two leftmost derivations.
Derivation 1 (+ at the root):
E => E + E => id + E => id + E * E => id + id * E => id + id * id
Derivation 2 (* at the root):
E => E * E => E + E * E => id + E * E => id + id * E => id + id * idThe two derivations give two different trees.
The first tree groups id * id first, which is the usual meaning. The second tree groups id + id first, which is wrong for ordinary arithmetic.
Sources of ambiguity in expression grammars
Two separate problems hide in E -> E + E | E * E.
- Precedence is missing. The grammar does not say that
*binds tighter than+. - Associativity is missing. For
id + id + id, the grammar allows both(id + id) + idandid + (id + id).
A fix must address both. Fixing only one leaves the grammar ambiguous.
Fixing ambiguity by layering
The standard fix gives each precedence level its own nonterminal. Operators that bind tighter appear deeper in the tree, so they are evaluated first.
E -> E + T | T
T -> T * F | F
F -> ( E ) | idAssociativity comes from the side where the recursion occurs.
| Recursive rule | Recursion on | Associativity |
|---|---|---|
| `E -> E + T` | left | left |
| `E -> T + E` | right | right |
Left recursion groups to the left, so a - b - c becomes (a - b) - c. Right recursion groups to the right. Exponentiation is usually right-associative, so it uses P -> F ^ P | F.
The layered grammar is unambiguous. It is also left-recursive, so a top-down parser needs the transformation from the next chapter before it can use it.
The dangling else
A second famous case comes from if statements.
S -> if E then S
| if E then S else S
| otherThe string if E1 then if E2 then S1 else S2 has two parse trees. The else can belong to the inner if or the outer if. Most languages say that else matches the nearest unmatched then.
To enforce this in the grammar, split statements into matched and unmatched ones.
S -> Matched | Unmatched
Matched -> if E then Matched else Matched | other
Unmatched -> if E then S
| if E then Matched else UnmatchedA Matched statement has every if paired with an else. The only place an else may follow a then is after a Matched statement, so the else cannot skip over an unmatched inner if.
Resolving ambiguity without rewriting the grammar
Rewriting adds nonterminals and makes the parse tree deeper. Bottom-up parser generators such as Yacc and Bison offer another route: keep the ambiguous grammar and resolve the conflicts with declarations.
- Give each operator a precedence level and an associativity.
- When a shift-reduce conflict occurs, compare the precedence of the rule to be reduced with the lookahead token.
- If the lookahead has higher precedence, shift. If the rule has higher precedence, reduce.
- If the two are equal, associativity decides: left means reduce, right means shift.
For the dangling else, the default is to shift, which attaches else to the nearest if.
The ambiguous grammar is smaller, and its parse table has fewer states. The cost is that the disambiguation lives outside the grammar, so the grammar alone no longer documents the language.
Detecting ambiguity
There is no algorithm that decides whether an arbitrary context-free grammar is ambiguous. The problem is undecidable. In practice you use these tests.
- Find a witness. Search for a short string with two leftmost derivations. This proves ambiguity.
- Look for patterns. A nonterminal that can derive itself in two different ways, such as
E -> E + E, or a rule that is both left- and right-recursive is a strong sign. - Use a parser table. If an LR parser table has a conflict, the grammar is either ambiguous or just not in that class. A grammar with no conflicts in a valid LR table is unambiguous, because every LR(k) grammar is unambiguous. An LL(1) grammar is also unambiguous.
The converse fails. A conflict does not prove ambiguity. A grammar can be unambiguous and still produce conflicts in a weaker parser such as SLR(1).
Common errors
- Counting derivations instead of trees. Two derivations that differ only in the order of expansion give the same tree. Compare leftmost derivations.
- Fixing precedence but not associativity.
E -> E + E | Tis still ambiguous forid + id + id. - Using the wrong side for recursion.
E -> T + Emakes+right-associative. This changes the meaning of-and/. - Assuming a conflict means ambiguity. It might only mean the grammar is outside the parser class.
- Assuming every ambiguous language can be repaired. Inherently ambiguous languages cannot.
Quick check on a small grammar
Take S -> S S | a. The string aaa has two leftmost derivations.
S => S S => a S => a S S => a a S => a a a
S => S S => S S S => a S S => a a S => a a aIn the first, the right S splits into two. In the second, the left S splits into two. The grammar is ambiguous. The language is a⁺, which the grammar S -> a S | a generates unambiguously.
Exercise
The grammar S -> a S b S | b S a S | ε generates strings with equal numbers of a's and b's. Is it ambiguous? Justify your answer with a string, or explain how you would test it.
Show answer
Yes. Take the string abab. One leftmost derivation is S => a S b S => a b S => a b a S b S => a b a b S => abab (the first S inside a S b S becomes ε, and the second S expands again). Another starts S => a S b S, expands the first S as b S a S, and gets a b a b by choosing ε for the remaining S symbols, so the first S contributes "ba" and the second contributes nothing before the final b is matched. Because abab can be reached through two different choices for the first S, it has two distinct parse trees. The two trees differ in where the first a is paired with a b, so the grammar is ambiguous.
Exercise
Rewrite E -> E - E | E ^ E | id so that - is left-associative, ^ is right-associative, and ^ binds tighter than -.
Show answer
E -> E - T | T T -> F ^ T | F F -> id The E level handles - with left recursion, giving left associativity. The T level handles ^ with right recursion, giving right associativity. Because T is below E, ^ binds tighter. F covers the operands.