如何在yacc语法中删除shift-reduce冲突?

时间:2016-03-24 00:43:57

标签: yacc shift-reduce-conflict

我有以下语法:

Expression
    : SimpleExpression {$$ = $1;};
    | SimpleExpression LTnum SimpleExpression
        { MkLeftC($1, $2); $$ = MkRightC($3, $2); }
    | SimpleExpression LEnum SimpleExpression
        { MkLeftC($1, $2); $$ = MkRightC($3, $2); }
    | SimpleExpression EQnum SimpleExpression
        { MkLeftC($1, $2); $$ = MkRightC($3, $2); }
    | SimpleExpression NEnum SimpleExpression
        { MkLeftC($1, $2); $$ = MkRightC($3, $2); }
    | SimpleExpression GEnum SimpleExpression
        { MkLeftC($1, $2); $$ = MkRightC($3, $2); }
    | SimpleExpression GTnum SimpleExpression
        { MkLeftC($1, $2); $$ = MkRightC($3, $2); }
    ;

SimpleExpression
    : PLUSnum Term op_terms
        { $$ = MakeTree(AddOp,$3,$2); }
    | MINUSnum Term op_terms
        { $$ = MakeTree(SubOp,$3,$2); }
    ;

op_terms
    : PLUSnum Term
        { $$ = MakeTree(AddOp,NullExp(),$2); }
    | PLUSnum Term op_terms
        { $$ = MakeTree(AddOp,$3,$2); }
    | MINUSnum Term
        { $$ = MakeTree(SubOp,NullExp(),$2); }
    | MINUSnum Term op_terms
        { $$ = MakeTree(SubOp,$3,$2); }
    | ORnum Term
        { $$ = MakeTree(OrOp,NullExp(),$2); }
    | ORnum Term op_terms
        { $$ = MakeTree(OrOp,$3,$2); }
    ;

我在y.output文件中得到以下shift-reduce冲突:

51: shift/reduce conflict (shift 74, reduce 57) on GTnum
51: shift/reduce conflict (shift 75, reduce 57) on NEnum
51: shift/reduce conflict (shift 76, reduce 57) on EQnum
51: shift/reduce conflict (shift 77, reduce 57) on GEnum
51: shift/reduce conflict (shift 78, reduce 57) on LEnum
51: shift/reduce conflict (shift 79, reduce 57) on LTnum
state 51
    Expression : SimpleExpression .  (57)
    Expression : SimpleExpression . LTnum SimpleExpression  (58)
    Expression : SimpleExpression . LEnum SimpleExpression  (59)
    Expression : SimpleExpression . EQnum SimpleExpression  (60)
    Expression : SimpleExpression . NEnum SimpleExpression  (61)
    Expression : SimpleExpression . GEnum SimpleExpression  (62)
    Expression : SimpleExpression . GTnum SimpleExpression  (63)

我需要帮助来消除这些冲突。我在这做错了什么?我试图设置优先级规则,但它们似乎在某种程度上似乎不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

奇怪的语法。它应该是这种形式:

Expression
    : SimpleExpression {$$ = $1;};
    | Expression LTnum SimpleExpression
    | Expression LEnum SimpleExpression
    | Expression EQnum SimpleExpression
    | Expression NEnum SimpleExpression
    | Expression GEnum SimpleExpression
    | Expression GTnum SimpleExpression
    ;

即。使用左递归。

奇怪的树也。它应该是一般形式:

$$ = MkBinaryNode($1,$2,$3);