Sub topic 7
Ambiguity and How to Resolve It
Assume you know context-free grammars, derivations, parse trees, and basic predictive parsing. This chapter focuses on recognizing when a grammar gives more than one structure to the same input and on changing the grammar or parser rules to remove that uncertainty.
What ambiguity means
A context-free grammar is ambiguous if at least one string in its language has two distinct parse trees. Equivalently, that string has two different leftmost derivations or two different rightmost derivations.
Consider this grammar:
E -> E + E | E * E | idThe string id + id * id has two possible structures:
(id + id) * idid + (id * id)
These structures produce different values when + and * have their usual meanings. The grammar does not state that multiplication has higher precedence than addition, so it is ambiguous.
Different derivation orders do not necessarily indicate ambiguity. A single parse tree can have both a leftmost and a rightmost derivation. The important question is whether the resulting trees differ.
| Question | Meaning |
|---|---|
| Same string, two parse trees | The grammar is ambiguous |
| Same tree, different derivation order | The grammar is not necessarily ambiguous |
Encoding precedence and associativity
A common solution is to use separate nonterminals for each precedence level:
E -> E + T | T
T -> T * F | F
F -> ( E ) | idHere, E handles addition, T handles multiplication, and F handles operands and parentheses. Because T appears inside E, multiplication must be grouped before addition.
The left recursion in E and T also gives left associativity. Thus, id - id - id would group as (id - id) - id when subtraction is represented similarly. For a right-associative operator such as exponentiation, a right-recursive rule is usually appropriate:
P -> F ^ P | FGrammar design must match the intended semantics. Removing left recursion for a recursive-descent parser is a separate transformation. It changes the grammar's shape, but it does not automatically fix ambiguity.
The dangling-else problem
This grammar is ambiguous:
S -> if E then S
| if E then S else S
| otherFor a nested conditional without an else at the inner level, the else could belong to either conditional. Most languages resolve this by assigning an else to the nearest unmatched if.
A grammar can encode that rule by separating matched and unmatched statements:
S -> M | U
M -> if E then M else M | other
U -> if E then S | if E then M else UThe exact grammar may vary, but the distinction makes the intended ownership explicit.
Exercise
Why does the grammar E -> E + E | E E | id assign two parse trees to id + id id, and what change gives multiplication higher precedence?
Show answer
The grammar permits either operator to be reduced first. Introduce levels such as E -> E + T | T and T -> T * F | F, so multiplication is nested inside terms and is grouped first.