2
votes

This is a part of a grammar which implemented with YACC.

%right NOT
%left TIME DIV REALDIV MOD
%left LT LE
%left GT GE
%left EQ NE
%left AND OR
%right ASSIGN
%%
expression: expression EQ expression {}; 
|expression PLUS expression {};
| expression TIME expression{};
| PLUS expression {};
| variable PLUS PLUS {};
| variable {};

It has 9 shift reduce conflict. How to fix conflicts without changing the language? (the string which is generated with this grammar)

1

1 Answers

1
votes

As written, the grammar is ambiguous because there is no way to distinguish the operator ++ from two instances of +.

Normally, this problem is resolved in the lexical scanner using the "maximal munch" rule, so that the expression a+++b would broken into the lexical items ID PLUSPLUS PLUS ID, resulting in the parse (a++) + b. In that case, if the user really meant a + (+ (+b))) and didn't want to use parentheses, they could simply split the tokens up with whitespace, writing a+ + +b. (In your grammar, <= is apparently scanned as a single lexical token, rather than the tokens < and =, so the inputs a < = b and a <= b result in different parses -- one of which is invalid. That's more or less expected. So there's no obvious reason why + + should be a permitted spelling of the increment operator ++.)

Making that change will change the language slightly. In your grammar, a++b can be interpreted as a+(+b); if ++ were lexically scanned as a single token, the resulting expression would be a syntax error. If that's a problem it can be resolved but I don't think the resulting complexity is worthwhile.