Sub topic 5
Ambiguous Grammars and Inherently Ambiguous Languages
Assume you know context-free grammars (CFGs), derivations, and parse trees. A grammar is ambiguous if at least one string in its language has two distinct parse trees. This distinction matters in compilers because different parse trees can produce different meanings.
Finding ambiguity
Consider the grammar:
E -> E + E | E * E | idThe string id + id * id has two possible structures:
(id + id) * idid + (id * id)
The grammar does not state whether + or * has priority. It also does not state how operators associate. Therefore, the string has two distinct parse trees.
A pair of different derivations is useful evidence, but the formal definition uses parse trees. Two derivations can differ only in the order in which variables are expanded and still represent the same parse tree.
A worked derivation
For the grammar above, two leftmost derivations are:
E => E * E
=> E + E * E
=> id + E * E
=> id + id * E
=> id + id * id
E => E + E
=> id + E
=> id + E * E
=> id + id * E
=> id + id * idThe first derivation places * at the root of the parse tree. The second places + at the root. Thus, the grammar is ambiguous.
Removing ambiguity
To make * bind more tightly than +, separate expression levels:
E -> E + T | T
T -> T * F | F
F -> idHere, E handles addition, T handles multiplication, and F handles operands. The grammar also makes both operators left-associative because the recursive variable appears on the left.
For example, id + id * id must be grouped as id + (id * id). A grammar can often remove ambiguity by adding nonterminals for precedence levels and associativity.
> callout note > Ambiguous grammar and ambiguous language are different concepts. A language is inherently ambiguous when every CFG that generates it is ambiguous. Finding one ambiguous grammar does not prove that the language itself is inherently ambiguous.
Common errors
- Showing two derivations without checking whether their parse trees differ.
- Assuming that different expansion orders imply ambiguity.
- Confusing an ambiguous grammar with a language that has no unambiguous grammar.
- Forgetting that a grammar may be ambiguous even when the intended meaning seems obvious.
Inherently ambiguous context-free languages exist. A standard example is the union of two languages that require incompatible equal-count relationships, such as strings that satisfy either one counting condition or another. Proving inherent ambiguity usually requires showing that every possible grammar must create a structural conflict, which is harder than finding two trees for one grammar.
Exercise
Is the grammar E -> E + E | id ambiguous? Give a reason.
Show answer
No. Every generated string contains only id operands joined by +, and the grammar gives the same binary grouping rule for a fixed number of operands only if associativity is not distinguished. In fact, for id + id + id, it has two parse trees, so it is ambiguous.