Ambiguity in Context Free Languages
Ambiguity in Context Free Languages
Languages
Ambiguity
E E E E a E a EE
a a E a a*a
E E
Rightmost derivation
a E E
a a
E E E | E E | (E) | a
a aa
E E a
a a
E E E | E E | (E) | a
a aa
E E E E
a E E E E a
a a a a
The grammar E E E | E E | ( E ) | a
is ambiguous:
E E
E E E E
a E E E E a
a a a a
The grammar E E E | E E | ( E ) | a
is ambiguous:
E E E a E a EE
a a E a a*a
a aa
take a 2
E E
E E E E
a E E E E a
a a a a
2 22
E E
E E E E
2 E E E E 2
2 2 2 2
2 22 6 2 22 8
6 8
E E
2 4 4 2
E E E E
2 2 2 2
2 E E E E 2
2 2 2 2
Correct result: 2 22 6
6
E
2 4
E E
2 2
2 E E
2 2
• Ambiguity is bad for programming languages
• We want to remove ambiguity
Chomsky Normal Form
Ensure that start variable doesn't appear on the right hand side of
any rule.
CFG CNF
2. Remove Epsilons
S S1 | S 2 S1 S1c | A S2 aS2 | B
A aAb | B bBc |
n n n
The string a b c
has two derivation trees
S S
S1 S2
S1 c a S2
Convert the CFG to CNF
• Let G be the grammar with productions
S AACD
A aAb |
C aC | a
D aDa | bDb |
• Let us go through each step of the conversion to CNF.
• Eliminate nullable -productions: The nullable variables are A and
D.
S AACD | ACD | AAC | CD | AC | C
A aAb | ab
C aC | a
D aDa | bDb | aa | bb
• Eliminate Unit Productions
• Here we may simply add the productions S → aC | a. and delete S → C.