Compiler Unit 2 ...5
Compiler Unit 2 ...5
Ambiguous Grammars
अनिनितता
A grammar is ambiguous if there exists a
string w that can be derived by at least two
different parse trees.
Ambiguous Grammars
E ® E + E | E * E | (E) | a
a + a*a
E E Þ E + E Þ a+ E Þ a+ E*E
Þ a + a* E Þ a + a*a
E + E
leftmost derivation
a E * E
a a
Learn Compiler Design From B K Sharma
Ambiguous Grammars
E ® E + E | E * E | (E) | a
a + a*a
E Þ E*E Þ E + E*E Þ a+ E*E E
Þ a + a*E Þ a + a*a
E * E
leftmost derivation
E + E a
a a
Learn Compiler Design From B K Sharma
Ambiguous Grammars
E Þ E + E Þ a+ E Þ a+ E*E
Þ a + a* E Þ a + a*a
E Þ E*E Þ E + E*E Þ a+ E*E
Þ a + a*E Þ a + a*a
Learn Compiler Design From B K Sharma
Ambiguous Grammars
E + E E * E
a E * E E + E a
a a a a
Learn Compiler Design: From B. K. Sharma
E + E E * E
a E * E E + E a
a a a a
Learn Compiler Design From B K Sharma
2 + 2*2
E E
E + E E * E
2 E * E E + E 2
2 2 2 2
Learn Compiler Design From B K Sharma
2 2 2 2
Learn Compiler Design From B K Sharma
2 2
Learn Compiler Design From B K Sharma
G2’ E → E – P
| P
P → P * Q
| Q
Q → R ^ Q
| R
R → id
Learn Compiler Design: From B. K. Sharma
G3’ id + id * id
And see the
difference between
G3 and G3’?
Learn Compiler Design: From B. K. Sharma
addminus
multdiv
Learn Compiler Design: From B. K. Sharma
G3’ id - id + id
And see the
difference between
G3 and G3’?
Learn Compiler Design: From B. K. Sharma
addminus
addminus
Learn Compiler Design From B K Sharma
E → E – P
id -id - id
G4’ E → P take id=3
P → id
G5 E→ E^E | id
AKA
Executed
One may associate else with first if.
Learn Compiler Design From B K Sharma
Executed
E1 if-stmt S2 E1 if-stmt
E2 S1 E2 S1 S2
Learn Compiler Design From B K Sharma
Desired semantics
matched-stmt matched-stmt
unmatched-stmt
matched-stmt
unmatched-stmt
if E1 then matched-stmt
else unmatched-stmt
unmatched-stmt
unmatched-stmt if expr then matched-stmt else unmatched-stmt
if-stmt
unmatched-stmt if expr then if-stmt(both)
Learn Compiler Design From B K Sharma
umatched-stmt
if-stmt
expr then
if
E1