为什么我的三元运算符会导致移位归约冲突?

sda*_*das 2 compiler-construction grammar parsing shift-reduce-conflict

以下是我的语法:

arithmetic_expression : expression + expression
                      | expression - expression

expression            : constant
                      | ID
                      | arithmetic_expression
                      | ternary

ternary               : expression ? expression : expression
Run Code Online (Sandbox Code Playgroud)

我在这种状态下收到移位减少错误:

state 126

    (19) ternary -> expression QUESTION_MARK expression COLON expression .
    (27) arithmetic_exp -> expression . PLUS expression
    (28) arithmetic_exp -> expression . MINUS expression
    (19) ternary -> expression . QUESTION_MARK expression COLON expression

  ! shift/reduce conflict for PLUS resolved as shift
  ! shift/reduce conflict for MINUS resolved as shift
  ! shift/reduce conflict for QUESTION_MARK resolved as shift

    PLUS            shift and go to state 86
    MINUS           shift and go to state 88
    QUESTION_MARK   shift and go to state 85

  ! PLUS            [ reduce using rule 19 (ternary -> expression QUESTION_MARK expression COLON expression .) ]
  ! MINUS           [ reduce using rule 19 (ternary -> expression QUESTION_MARK expression COLON expression .) ]
  ! QUESTION_MARK   [ reduce using rule 19 (ternary -> expression QUESTION_MARK expression COLON expression .) ]
Run Code Online (Sandbox Code Playgroud)

我相信冲突在于

true ? 1 : false ? 3 : 2
Run Code Online (Sandbox Code Playgroud)

可以解释为true ? 1 : (false ? 3 : 2)(true ? 1 : false) ? 3 : 2

+我已将、 和 的优先级设置为-左关联性且级别高于?(我将其设置为右关联性)。

我究竟做错了什么?

ric*_*ici 5

如果我理解正确的话,您执行了以下操作:

%left '+' '-'
%right '?'

%%

arithmetic_expression : expression + expression
                      | expression - expression
                      ;
ternary               : expression ? expression : expression
                      ;
Run Code Online (Sandbox Code Playgroud)

这是行不通的,因为你还没有告诉 bison 生产的优先级ternary是什么。

为了解决移位-归约冲突,bison 将可能被归约的产生式的优先级与可能被移位的终端的优先级进行比较。您已声明了终结符 '+'、'-' 和 '?' 的优先级,以及 中两个产生式的优先级arithmetic_expression,但未声明 中产生式的优先级ternary

引用野牛手册,强调补充说:

每个规则从组件中提到的最后一个终端符号获取其优先级。

这是非常微妙的,你不会是第一个没有注意到的人。

解决方案:要么声明终端的优先级:,要么添加%prec '?'到 中的产生式中ternary