Compiler construction 移位减少yacc中算术表达式的冲突
尽管指定了运算符的优先级,但该语法仍给了我冲突。即使在《龙之书》中,它也是以这样的方式解决的(如下面的前7行所述),但它仍然存在冲突! 下面是在yacc中实现的代码Compiler construction 移位减少yacc中算术表达式的冲突,compiler-construction,bison,yacc,lex,Compiler Construction,Bison,Yacc,Lex,尽管指定了运算符的优先级,但该语法仍给了我冲突。即使在《龙之书》中,它也是以这样的方式解决的(如下面的前7行所述),但它仍然存在冲突! 下面是在yacc中实现的代码 %right THEN_KW %right ELSE_KW %left XOR_KW OR_KW %right '=' %left AND_KW ALSO_KW %left EQ_KW LT_KW GT_KW LE_KW GE_KW %left PLUS_KW MINUS_KW %left MULT_KW DIV_KW MOD_KW
%right THEN_KW
%right ELSE_KW
%left XOR_KW OR_KW
%right '='
%left AND_KW ALSO_KW
%left EQ_KW LT_KW GT_KW LE_KW GE_KW
%left PLUS_KW MINUS_KW
%left MULT_KW DIV_KW MOD_KW
%right NOT_KW
arthlogicexpr -> operand | arthlogicexpr arthop arthlogicexpr
arthop -> '+' | '-' | '*' | '/' |'%'
operand -> variable
variable -> IDENTIFIER
parser.output中的错误为:
state 141
78 arthlogicexpr: arthlogicexpr . arthop arthlogicexpr
78 | arthlogicexpr arthop arthlogicexpr .
'+' shift, and go to state 103
'-' shift, and go to state 104
'*' shift, and go to state 105
'/' shift, and go to state 106
'%' shift, and go to state 107
'+' [reduce using rule 78 (arthlogicexpr)]
'-' [reduce using rule 78 (arthlogicexpr)]
'*' [reduce using rule 78 (arthlogicexpr)]
'/' [reduce using rule 78 (arthlogicexpr)]
'%' [reduce using rule 78 (arthlogicexpr)]
$default reduce using rule 78 (arthlogicexpr)
arthop go to state 109
有关其他州的更多信息:
state 103
79 arthop: '+' .
$default reduce using rule 79 (arthop)
state 104
80 arthop: '-' .
$default reduce using rule 80 (arthop)
state 105
81 arthop: '*' .
$default reduce using rule 81 (arthop)
state 106
82 arthop: '/' .
$default reduce using rule 82 (arthop)
state 107
83 arthop: '%' .
$default reduce using rule 83 (arthop)
如果要避免警告,需要指定运算符关联性,或者需要构造语法,使“arthlogicexpr”不在运算符的两侧 给定输入
a + b - c
你的语法不清楚这是否意味着
arthlogicexpr(arthlogicexpr(a,+,b),-,c)
或
arthlogicexpr(a,+,arthlogicexpr(b,,,c))由于冲突解决的执行方式,您不能像刚才那样考虑运算符。因为您要指定规则和标记之间的先例,所以需要区分不能以相同方式处理的规则之间的差异。您不希望将
exp:exp“+”exp
视为等同于exp:exp“*”exp
所以要遵守四条规则,每个操作员一条
如果你真的想考虑一些事情,你可以为每个优先级定义一个规则,但对于没有真正附加值的IMHO来说,这将更加复杂
一个合适的工具应该告诉您您的优先指令(%right
等)在这里是无用的。这暗示冲突解决不能使用它们(因为您编写语法的方式)。我敢说野牛会发出警告
你也应该看看那里: