20.06.2014 Views

Ambiguous Grammars - ByteLABS

Ambiguous Grammars - ByteLABS

Ambiguous Grammars - ByteLABS

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Ambiguous</strong> <strong>Grammars</strong><br />

Definitions<br />

• If a grammar has more than one leftmost derivation for a<br />

single sentential form, the grammar is ambiguous<br />

• If a grammar has more than one rightmost derivation for a<br />

single sentential form, the grammar is ambiguous<br />

• The leftmost and rightmost derivations for a sentential<br />

form may differ, even in an unambiguous grammar<br />

— However, they must have the same parse tree!<br />

Classic example — the if-then-else problem<br />

Stmt → if Expr then Stmt<br />

| if Expr then Stmt else Stmt<br />

| … other stmts …<br />

This ambiguity is entirely grammatical in nature<br />

COMP 412, Fall 2002 16<br />

Comp 412 Fall 2005


Ambiguity<br />

This sentential form has two derivations<br />

if Expr 1<br />

then if Expr 2<br />

then Stmt 1<br />

else Stmt 2<br />

if<br />

if<br />

E 1<br />

then<br />

else<br />

E 1<br />

then<br />

if<br />

S 2<br />

E 2<br />

then<br />

if<br />

E 2<br />

then else<br />

S 1<br />

S 1<br />

S 2<br />

production 2,<br />

then production 1<br />

production 1,<br />

then production 2<br />

COMP 412, Fall 2002 17<br />

Comp 412 Fall 2005


Ambiguity<br />

Removing the ambiguity<br />

• Must rewrite the grammar to avoid generating the problem<br />

• Match each else to innermost unmatched if (common sense rule)<br />

1<br />

Stmt<br />

→<br />

if Expr then Stmt<br />

2<br />

⏐<br />

if Expr then WithElse else Stmt<br />

3<br />

⏐<br />

Other Statements<br />

4<br />

WithElse<br />

→<br />

if Expr then WithElse else WithElse<br />

5<br />

⏐<br />

Other Statements<br />

With this grammar, example has only one rightmost derivation<br />

Intuition: once into WithElse, we cannot generate an unmatched else<br />

… a final if without an else can only come through rule 2 …<br />

COMP 412, Fall 2002 18<br />

Comp 412 Fall 2005


Ambiguity<br />

if Expr 1 then if Expr 2 then Stmt 1 else Stmt 2<br />

Rule Sentential Form<br />

— Stmt<br />

1 if Expr then Stmt<br />

2 if Expr then if Expr then WithElse else Stmt<br />

3 if Expr then if Expr then WithElse else S 2<br />

5 if Expr then if Expr then S 1 else S 2<br />

? if Expr then if E 2 then S 1 else S 2<br />

? if E 1 then if E 2 then S 1 else S 2<br />

some other production<br />

This grammar has only one rightmost derivation for the example<br />

COMP 412, Fall 2002 19<br />

Comp 412 Fall 2005

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!