Header Ads Widget

Ambiguity in Grammar

Ambiguity in Grammar

A grammar is said to be ambiguous if there exists more than one leftmost derivation or more than one rightmost derivation or more than one parse tree for the given input string. If the grammar is not ambiguous, then it is called unambiguous.

If the grammar has ambiguity, then it is not good for compiler construction. No method can automatically detect and remove the ambiguity, but we can remove ambiguity by re-writing the whole grammar without ambiguity.

Example 1:

Let us consider a grammar G with the production rule

E → I  

E → E + E  

E → E * E  

E → (E)  

I → Îµ | 0 | 1 | 2 | ... | 9  

Solution:

For the string "3 * 2 + 5", the above grammar can generate two parse trees by leftmost derivation:

Ambiguity in Grammar

Since there are two parse trees for a single string "3 * 2 + 5", the grammar G is ambiguous.

Example 2:

Check whether the given grammar G is ambiguous or not.

E → E + E  

E → E - E  

E → id  

Solution:

From the above grammar String "id + id - id" can be derived in 2 ways:

First Leftmost derivation

E → E + E  

   → id + E  

   → id + E - E  

   → id + id - E  

   → id + id- id  

Second Leftmost derivation

E → E - E  

   → E + E - E  

   → id + E - E  

   → id + id - E  

   → id + id - id  

Since there are two leftmost derivation for a single string "id + id - id", the grammar G is ambiguous.

Example 3:

Check whether the given grammar G is ambiguous or not.

S → aSb | SS  

S → Îµ  

Solution:

For the string "aabb" the above grammar can generate two parse trees

Ambiguity in Grammar

Since there are two parse trees for a single string "aabb", the grammar G is ambiguous.

Example 4:

Check whether the given grammar G is ambiguous or not.

A → AA  

A → (A)  

A → a  

Solution:

For the string "a(a)aa" the above grammar can generate two parse trees:

Ambiguity in Grammar

Since there are two parse trees for a single string "a(a)aa", the grammar G is ambiguous.

Post a Comment

0 Comments