You are on page 1of 11

Ambiguous Grammars

Ambiguous Grammars
A CFG is ambiguous if there is at least one string in the language that is the yield of two or more parse trees. Similarly
1. If there is a string in the language that has two different leftmost derivations. 2. If there is a string in the language that has two different rightmost derivations.

Example
E

EpE+E EpE-E EpE*E EpE/E Ep a

E a

+ E

E * a E a

E E E a + * E a E a

Solution
1. Precedence
An operator with higher precedence should be done before one with lower precedence. An operator with higher precedence is placed in a rule (logically) farther from the start symbol.

2. Associativity
If an operator is right-associative (or left-associative), an operand in between 2 operators is associated to the operator to the right (left).
 Right-associated : W + (X + (Y + Z)) Left-associated : ((W + X) + Y) + Z

1. Precedence
EpE+E EpE-E EpF FpF*F FpF/F Fpa
E E F a F a + E F * F a

2. Associativity
The conventional approach for operators is the grouping from left (left-associative)
EpE+F EpE-F EpF FpF*H FpF/H FpH Hpa

Note: If you find any problem with the grammar, please do inform me.

Example
Homework: construct CFG for balanced parentheses and if ambiguous, then remove the ambiguity by designing an unambiguous CFG.

Inherently Ambiguous
L = { aibickdk | i,k >=1} U {aibkckdi | i,k >=1}
S p AB | C A p aAb | ab B p cBd | cd C p aCd | aDd D p bDc | bc Construct Parse tree for aabbccdd

Designing of CFG
First technique
Many CFLs are the union of simpler CFLs. If we can break the large CFL into simpler small pieces/CFLs (like divideand-conquer) then by combining the individual grammars for each piece will result into CFG for the large CFL using

S p S1 | S2 |

.. | Sk

Where S1, S2, .., Sk are the start variable of individual grammars For example: L = { w | w = 0n1n or 0n10n ,where n>=0} L1 = { 0n1n | n>=0 } L2 = { 0n10n | n>=0 } L = L1 U L2

Designing of CFG
Second technique
If the language is regular, then CFG is easy to construct. First construct DFA for that language then convert the DFA into an equivalent CFG as follows
For each state of DFA there should be a variable, For transition (qi ,a) = qj , add the rule Ri p aRj For each accept state add Ri p For start state q0 , make R0 as the start variable

Big Picture
Every regular language is a CFL. The class of regular languages is a proper subclass of CFLs.
CFL

RL

You might also like