Compiler Design Ambiguous Grammar and Making Them Unmbiguous
Compiler Design Ambiguous Grammar and Making Them Unmbiguous
Types of Grammar
On the basis of number of derivation trees, grammars are classified as-
1.Ambiguous Grammar
2.Unambiguous Grammar
1. Ambiguous Grammar-
Since two syntax trees exist for string w, therefore the grammar is ambiguous.
Reason-03:
Let us consider a string w generated by the grammar-
w = id + id x id
Now, let us write the leftmost derivations for this string w.
Since two leftmost derivations exist for string w, therefore the grammar is ambiguous.
Reason-04:
Since two rightmost derivations exist for string w, therefore the grammar is ambiguous.
2. Unambiguous Grammar-
A grammar is said to unambiguous if for every string generated by it, it produces exactly one-
• Parse tree
• Or derivation tree
• Or syntax tree
• Or leftmost derivation
• Or rightmost derivation
Example-
Consider the following grammar-
E → E + T / T
T → T x F / F
F → id
Unambiguous Grammar
This grammar is an example of unambiguous grammar.
Grammar Ambiguity-
There exists no algorithm to check whether any given grammar is
ambiguous or not.
• This general decision problem is undecidable-
“Whether a grammar is ambiguous or not?”
• This is because it can be shown that this problem is equivalent to Post
Correspondence Problem.
General Approach To Check Grammar Ambiguity-
To check whether a given grammar is ambiguous or not, we follow the following steps-
Step-01:
We try finding a string from the Language of Grammar such that for the string
there exists more than one-
• parse tree
• or derivation tree
• or syntax tree
• or leftmost derivation
• or rightmost derivation
Step-02:
• If there exists at least one such string, then the grammar is ambiguous otherwise
unambiguous.
PROBLEMS BASED ON CHECKING WHETHER GRAMMAR IS
AMBIGUOUS-
Problem-01:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Problem-02:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Problem-03:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Problem-04:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Problem-05:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Problem-06:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Problem-08:
Since two different parse trees exist for string w, therefore the given grammar is ambiguous.
Removing Ambiguity | Ambiguous to Unambiguous
Problem-01:
Convert the following ambiguous grammar into unambiguous
grammar-
R → R + R / R . R / R* / a / b