• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
July 21, 2022 |22.6K Views

Ambiguous Grammar in Compiler Design

  Share   Like
Description
Discussion

In this video, we will try to understand what is ambiguous grammar with the help of an example. 
Any grammar can be said as ambiguous grammar if there are multiple leftmost or rightmost derivative available for it. Also, any grammar is ambiguous grammar if multiple parse trees are possible for any given string. Any grammar that isn’t ambiguous, it is known as unambiguous grammar. 

Ambiguous grammar and unambiguous grammar, both are the types of context-free grammar. In case of any unambiguous grammar, every valid string should be having unique leftmost derivative or unique parse tree. Ambiguous grammar, is not good for the construction of compiler as it is generating more than one parse tree for same string and thus resulting in confusion. 
So, it’s always recommendable to eliminate ambiguity from any grammar. But unfortunately, there are no specific methods available to convert ambiguous grammar into unambiguous. 

Infact, there is no way by which we can automatically detect the ambiguity present in any grammar. Ambiguous grammar is generating parse tree of smaller size compared to unambiguous grammar. Ambiguous grammar is capable of generating parse tree faster. 

Try to disambiguate given grammar i.e., rewrite grammar in such a way that there’s only one parse tree possible for any string that can be represented by the grammar. Ambiguous grammar can be converted to the unambiguous grammar, by applying the below rules: 

In case the left associative operators i.e. +, -, / or * are utilized in production, then you should apply left recursion in given production rule so that the parse tree will grow on left side only. 
Similarly, in case the right associative operators i.e. ^ is utilized in production, then you should apply right recursion in given production rule so that the parse tree will grow on right side only. 

Ambiguous grammar: https://www.geeksforgeeks.org/ambiguous-grammar/