2016-03-18 53 views
0

這是錯誤:關於12移進/歸約涉及EXP衝突ML-Yacc的錯誤 - > EXP BINOP EXP

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 

,但沒有。

回答

1

衝突的所有來自exp: exp binop exp規則的ambuguity - 等的輸入的+ B * C具有兩個binops可以被解析爲任一(A + B)* C一個+(b *的c)

要解決此問題,最簡單的方法是設置標記涉及的規則的優先順序。你已經完成了令牌的操作,但是沒有按照規則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會爲你做。