Open In App

Parsing ambiguous grammars using LR parser

LR parser can be used to parse ambiguous grammars. LR parser resolves the conflicts (shift/reduce or reduce/reduce) in parsing table of ambiguous grammars based on certain rules (precedence and/or associativity of operators) of the grammar. 

Example: 
Lets take the following ambiguous grammar: 
 



E -> E+E
E -> E*E
E -> id 

Lets assume, the precedence and associativity of the operators (+ and *) of the grammar are as follows: 
 

If we use LALR(1) parser, the LR(1) item DFA will be: 



 

From the LR(1) item DFA we can see that there are shift/reduce conflicts in the state I5 and I6. So the parsing table is as follows: 

 

There are both shift and reduce moves in I5 and I6 on “+ and “*”. To resolve this conflict, that is to determine which move to keep and which to discard from the table we shall use the precedence and associativity of the operators. 
Consider the input string: 
 

id + id + id 

Lets look at the parser moves till the conflict state according to the above parsing table. 

 

 

Similarly, Taking shift move of I5 state on symbol “*” will give “*” higher precedence over “+”, as “*” will be reduced before “+”. Taking reduce move of I5 state on symbol “*” will give “+” higher precedence over “*”, as “+” will be reduced before “*”. Similar to I5, conflicts from I6 can also be resolved. 

According to the precedence and associativity of our example, the conflict is resolved as follows, 
 

Generally, the parser generator tool YAAC resolves conflicts due to ambiguous grammars as follows, 
 

Related GATE questions: 
 

 

Article Tags :