【问题标题】:Shift Reduce Conflict for arithmetic expressions in yaccyacc中算术表达式的Shift减少冲突
【发布时间】:2017-11-22 11:27:35
【问题描述】:

尽管指定了运算符的优先级,但这个语法给了我冲突。即使在 Dragon book 中,它也以这种方式解决(实现方式为下面的前 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 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)

【问题讨论】:

标签: compiler-construction bison yacc lex


【解决方案1】:

由于执行冲突解决的方式,您不能像刚才那样考虑运算符。因为您要指定规则和标记之间的优先级,所以您需要区分不能以相同方式处理的规则之间的区别。而且您不想将exp: exp "+" exp 视为等同于exp: exp "*" exp

所以保留四个规则,每个操作员一个。

如果您真的想要考虑某些因素,您可以为每个优先级定义一个规则,但恕我直言,这将更加复杂,因为没有真正的附加值。

适当的工具应该告诉您,您的优先指令(%right 等)在这里没有用。这是冲突解决不能使用它们的提示(因为您编写语法的方式)。我冒险野牛会警告。

你也应该看看那里:

【讨论】:

    【解决方案2】:

    如果您想避免警告,您需要指定运算符关联性,或者您需要构造语法,使“arthlogicexpr”不在运算符的两侧。

    给定输入

    a + b - c
    

    你的语法对于这是否意味着模棱两可

    arthlogicexpr (arthlogicexpr (a, +, b), -, c)

    或 arthlogicexpr (a, +, arthlogicexpr (b, -, c))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多