Ambiguity in Context-Free Grammars



If a context free grammar G has more than one derivation tree for some string w ∈ L(G), it is called an ambiguous grammar. There exist multiple right-most or left-most derivations for some string generated from that grammar.

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

Example 1

Check whether the grammar G with production rules −

X → X+X | X*X |X| a

is ambiguous or not.

Solution

Lets find out the derivation tree for the string "a+a*a". It has two leftmost derivations.

Derivation 1X → X+X → a +X → a+ X*X → a+a*X → a+a*a

Parse tree 1

Parse Tree 1

Derivation 2X → X*X → X+X*X → a+ X*X → a+a*X → a+a*a

Parse tree 2

Parse Tree 2

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

Example 2

Let us consider a grammar with production rules, as shown below −

$$\mathrm{E \:=\: I}$$

$$\mathrm{E \:=\: E \:+\: E}$$

$$\mathrm{E \:=\: E \: \times \: E}$$

$$\mathrm{E \:=\: (E)}$$

$$\mathrm{E \:=\: \epsilon \: |0|1|2|3 \:\dotso \:9}$$

Let's consider a string "3*2+5"

If the above grammar generates two parse trees by using Left most derivation (LMD) then, we can say that the given grammar is ambiguous grammar.

Ambiguity in Grammar in TOC1

Ambiguity in Grammar in TOC2

Since there are two parse trees for a single string, then we can say the given grammar is ambiguous grammar.

Example 3

Consider another example,

Check whether the grammar is ambiguous or not.

$$\mathrm{A \: \rightarrow \:AA}$$

$$\mathrm{A \: \rightarrow \:(A)}$$

$$\mathrm{A \: \rightarrow \:a}$$

For the string "a(a)(a)a" the above grammar can generate two parse trees, as given below −

Ambiguity in Grammar in TOC3
Advertisements