7-Parsing and Ambiguity-16-09-2024
7-Parsing and Ambiguity-16-09-2024
S S
a S b
a S b a S b
b S a
S
S S
A
A B A B
A A Many others
A A b B A A b possible.
A A A b
a a b a A b
a A b
a
a
Ambiguous context-free grammars
• A context-free grammar is said to be AMBIGUOUS if there exists a
string w є L(G) that has at least two distinct derivation trees or at
least two rightmost/ leftmost derivations for the same string w.
• Else, the grammar is unambiguous.
a S c S S b S a
a a a a
Sample Parse Tree
• Sample parse tree for the palindrome CFG for
1110111:
P
P | 0 | 1 | 0P0 | 1P1
1 P 1
This grammar is not ambiguous
1 P 1
HOMEWORK:
1 P 1
Check the ambiguity of the CFG
G = ({S, A}, {0,1}, P, S) where
P = {S → A00, A → | AA | 0 | 1} 0
Show that the following grammars
are ambiguous
1.S -> SS | a | b
2.S -> ABA;
A -> aA | e; B -> bB | e
3. S -> aSb | aaSb | e
4. S -> aSb | abS | e
5. S → A00, A → | AA | 0 | 1
Unambiguous context-free grammars
• A context-free grammar is said to be UNAMBIGUOUS if for
every string w є L(G), there exists a unique derivation tree
(upto isomorphism).
• S → S1 | S 2
• S1 → aS1b | C
• C → cC | c
• S2 → A | bS2c Ambiguous for the string abc
• A → aA | a