这是错误:
12 shift/reduce conflicts
error: state 34: shift/reduce conflict (shift OR, reduce by rule 11)
error: state 34: shift/reduce conflict (shift AND, reduce by rule 11)
error: state 34: shift/reduce conflict (shift GE, reduce by rule 11)
error: state 34: shift/reduce conflict (shift GT, reduce by rule 11)
error: state 34: shift/reduce conflict (shift LE, reduce by rule 11)
error: state 34: shift/reduce conflict (shift LT, reduce by rule 11)
error: state 34: shift/reduce conflict (shift NEQ, reduce by rule 11)
error: state 34: shift/reduce conflict (shift EQ, reduce by rule 11)
error: state 34: shift/reduce conflict (shift DIVIDE, reduce by rule 11)
error: state 34: shift/reduce conflict (shift TIMES, reduce by rule 11)
error: state 34: shift/reduce conflict (shift MINUS, reduce by rule 11)
error: state 34: shift/reduce conflict (shift PLUS, reduce by rule 11)
这是语法:
program : exp ()
exp:
exp binop exp ()
| ID ()
| lvalue ()
| STRING ()
| INT ()
| NIL ()
| LPAREN expseq RPAREN ()
| lvalue ASSIGN exp ()
| ID LPAREN explist RPAREN ()
| LET declist IN expseq END ()
| IF exp THEN exp ELSE exp ()
| IF exp THEN exp ()
binop:
EQ ()
| NEQ ()
| LT ()
| GT ()
| LE ()
| GE ()
| AND ()
| OR ()
| PLUS ()
| MINUS ()
| TIMES ()
| DIVIDE ()
我该如何解决这个问题?我是否需要重新思考语法并找到另一种方法来描述这种语法?
我也尝试过声明偏好顺序(虽然我的使用经验很少),例如:
%nonassoc OR NEQ EQ LT LE GT GE AND
%right PLUS MINUS
%right TIMES DIVIDE
但没有。
答案 0 :(得分:1)
冲突都来自exp: exp binop exp
规则的宽容 - 像 a + b * c 这样的带有两个binop的输入可以被解析为(a + b) )* c 或 a +(b * c)。
要解决此问题,最简单的方法是为所涉及的规则设置标记 AND 的优先级。您已经为令牌执行了此操作,但尚未针对规则exp: exp binop exp
执行此操作。不幸的是,您只能为每个规则设置一个优先级,并且此规则需要不同的优先级,具体取决于与binop
匹配的令牌。最简单的解决方案是复制规则并摆脱binop
:
exp : exp EQ exp
| exp NEQ exp
| exp LE exp
| exp GT exp
| exp LE exp
| exp GE exp
| exp AND exp
| exp OR exp
| exp PLUS exp
| exp MINUS exp
| exp TIMES exp
| exp DIVIDE exp
现在每个令牌都有自己的规则版本,每个规则自动从其中的单个令牌获取优先级,因此您甚至不需要显式设置规则的优先级,yacc会为您执行此操作。