Sub topic 5
Ambiguous grammars and inherently ambiguous languages
This chapter assumes you can write a context-free grammar, derive strings with it, and draw a parse tree. It also assumes you know the difference between leftmost and rightmost derivations. Here you learn what it means for a grammar to be ambiguous, how to remove ambiguity, and why some languages cannot be fixed.
What ambiguity means
A context-free grammar G is ambiguous if some string in L(G) has two or more distinct parse trees. These conditions are equivalent, and any one of them can serve as the definition:
- The string has two different parse trees.
- The string has two different leftmost derivations.
- The string has two different rightmost derivations.
A single parse tree corresponds to exactly one leftmost and one rightmost derivation. Two different derivations that differ only in the order of expansion (for example, one leftmost and one rightmost for the same tree) do not show ambiguity.
Ambiguity is a property of a grammar. A language is not ambiguous in itself. Many languages have both ambiguous and unambiguous grammars.
Example: the expression grammar
Consider E -> E + E | E E | id. The string `id + id id` has two parse trees.
Tree 1: + at the root Tree 2: * at the root
E E
/ | \ / | \
E + E E * E
| /|\ /|\ |
id E * E E + E id
| | | |
id id id idTree 1 means id + (id id). Tree 2 means (id + id) id. A compiler that builds trees from this grammar could compute two different values, so ambiguity here is a real defect.
Fixing ambiguity by encoding precedence and associativity
The usual repair makes each precedence level its own variable and makes recursion go on one side only.
E -> E + T | T
T -> T * F | F
F -> id*binds tighter because it appears deeper in the tree (under T, below E).- Recursion on the left of
+and*makes both operators left-associative. - Putting the recursion on the right (E -> T + E) would give right-associativity instead.
The ambiguous grammar is still a valid grammar for the same language. The rewrite keeps the language and removes the extra trees.
Counting parse trees
This program counts parse trees for a token list under the ambiguous grammar E -> E + E | E * E | id. A count above 1 shows ambiguity.
from functools import lru_cache
def count_trees(tokens):
"""Number of parse trees of E -> E+E | E*E | id for the token tuple."""
tokens = tuple(tokens)
@lru_cache(maxsize=None)
def c(i, j): # trees for E deriving tokens[i:j]
total = 1 if (j - i == 1 and tokens[i] == "id") else 0
for k in range(i + 1, j - 1):
if tokens[k] in ("+", "*"):
total += c(i, k) * c(k + 1, j)
return total
return c(0, len(tokens))
print(count_trees(["id"])) # 1
print(count_trees(["id", "+", "id", "*", "id"])) # 2
print(count_trees(["id", "+", "id", "+", "id"])) # 2
print(count_trees(["id", "+", "id", "+", "id", "+", "id"])) # 5The counts follow the Catalan numbers (1, 1, 2, 5, ...) because every operator can be the root. The second + example shows that ambiguity comes from associativity as well as precedence.
Other common ambiguous grammars
- S -> S S | a: the string
aaahas the trees (aa)a and a(aa). - Dangling else: in
stmt -> if expr then stmt | if expr then stmt else stmt | other, the stringif e then if e then s else scan attachelseto eitherif. Languages resolve it by the rule "else matches the nearest unmatched if", which is a grammar rewrite using separate matched and unmatched statement variables. - S -> aS | Sb | a:
ab... checkaab? The stringabis not generated. For a clear case, the stringaabcan be derived by applying aS first or Sb first, giving two trees.
A grammar such as S -> aSa | bSb | a | b | ε (palindromes) is unambiguous, because the first and last symbols decide the production uniquely.
Inherent ambiguity
A language is inherently ambiguous if every context-free grammar for it is ambiguous. No rewrite can help.
The standard example is
L = { a^i b^j c^k | i = j or j = k }
A natural grammar is:
S -> X C | A Y
X -> a X b | ε
C -> c C | ε
A -> a A | ε
Y -> b Y c | εX Cgenerates a^i b^i c^k, so it covers the case i = j.A Ygenerates a^i b^j c^j, so it covers the case j = k.- A string a^n b^n c^n satisfies both conditions, so it has two parse trees, one from each branch.
The proof that no grammar avoids this uses Ogden's lemma, a stronger form of the pumping lemma. You do not need to reproduce it for GATE. You need to recognise the shape: a union of two context-free languages whose "counting conditions" overlap on infinitely many strings.
Relationships to other topics
| Statement | True or false | Column | Column | Column | Column |
|---|---|---|---|---|---|
| Every regular language has an unambiguous CFG | True | ||||
| Every deterministic CFL (DCFL) has an unambiguous CFG | True | ||||
| Every unambiguous CFG generates a DCFL | False. Palindromes S -> aSa \ | bSb \ | a \ | b \ | ε are unambiguous but not deterministic |
| Every CFL has an unambiguous CFG | False. Inherently ambiguous languages exist | ||||
| Ambiguity of an arbitrary CFG is decidable | False. It is undecidable |
The undecidability result means no algorithm takes any grammar and answers "ambiguous?" correctly every time. You can still prove ambiguity of a specific grammar by exhibiting one string with two trees. Proving unambiguity needs an argument, such as showing that each derivation step is forced.
Common errors
- Treating two derivations as different when they only differ in expansion order. Compare parse trees, or compare leftmost derivations.
- Saying a language is ambiguous when you mean a grammar is. Only the word "inherently" applies to languages.
- Assuming unambiguous means deterministic. Deterministic PDAs capture a smaller class.
- Concluding a grammar is unambiguous because one string has one tree. You need all strings to have one tree.
- Forgetting that ε-productions and unit productions can create ambiguity on their own, for example S -> A | B with A -> a and B -> a.
GATE patterns
- "Which grammar is unambiguous?" Test each option with a short string that can be parsed two ways, usually length 3 to 5.
- "Which language is inherently ambiguous?" Look for a union of two counting conditions that overlap, such as i = j or j = k.
- "Is ambiguity decidable?" The answer is no.
Exercise
Show that S -> S S | a is ambiguous, then name an unambiguous grammar for the same language L = a^+.
Show answer
The string aaa has two parse trees. One uses S -> S S with the left S deriving aa and the right S deriving a. The other has the left S deriving a and the right S deriving aa. So the grammar is ambiguous. The language a^+ is generated by the unambiguous grammar S -> a S | a, where each string has exactly one derivation.
Exercise
Is the grammar S -> A | B, A -> a, B -> a ambiguous? Give the evidence.
Show answer
Yes. The string a has two leftmost derivations: S => A => a and S => B => a. They give two different parse trees, so the grammar is ambiguous. The language {a} is not inherently ambiguous, since S -> a generates it unambiguously.
Exercise
Is L = { a^i b^j c^k | i = j or j = k } context-free, and is it inherently ambiguous?
Show answer
It is context-free, since it is the union of two context-free languages, { a^n b^n c^k } and { a^i b^n c^n }. It is inherently ambiguous: strings a^n b^n c^n satisfy both conditions for infinitely many n, and a proof with Ogden's lemma shows every grammar must give them two parse trees.