【问题标题】:yacc shift/reduce in parser解析器中的 yacc 移位/减少
【发布时间】:2025-12-28 10:00:09
【问题描述】:

我正在一项作业中为编译器编写解析器,并且当我运行命令时

$ bison --yacc -v --defines -o parser.c parser.y
parser.y: warning: 8 shift/reduce conflicts [-Wconflicts-sr]
$

除了预期的 if/else shift/reduce 冲突之外,我在以下状态下会遇到 parser.output 文件冲突,

状态 34

 35 term: lvalue . PLUSPLUS
 37     | lvalue . MINUSMINUS
 39 assignexpr: lvalue . ASSIGN expr
 40 primary: lvalue .
 49 member: lvalue . FULLSTOP IDENTIFIER
 50       | lvalue . LEFTSQUARE expr RIGHTSQUARE
 54 call: lvalue . callsuffix

ASSIGN      shift, and go to state 88
PLUSPLUS    shift, and go to state 89
MINUSMINUS  shift, and go to state 90
LEFTSQUARE  shift, and go to state 91
FULLSTOP    shift, and go to state 92
LEFTPAR     shift, and go to state 93

PLUSPLUS    [reduce using rule 40 (primary)]
MINUSMINUS  [reduce using rule 40 (primary)]
LEFTSQUARE  [reduce using rule 40 (primary)]
LEFTPAR     [reduce using rule 40 (primary)]
$default    reduce using rule 40 (primary)

callsuffix  go to state 94
normcall    go to state 95
methodcall  go to state 96

状态 36

 41 primary: call .
 51 member: call . FULLSTOP IDENTIFIER
 52       | call . LEFTSQUARE expr RIGHTSQUARE
 53 call: call . LEFTPAR elist RIGHTPAR

LEFTSQUARE  shift, and go to state 97
FULLSTOP    shift, and go to state 98
LEFTPAR     shift, and go to state 99

LEFTSQUARE  [reduce using rule 41 (primary)]
LEFTPAR     [reduce using rule 41 (primary)]
$default    reduce using rule 41 (primary)

状态 52

 16 expr: expr . PLUS expr
 17     | expr . MINUS expr
 18     | expr . MUL expr
 19     | expr . DIV expr
 20     | expr . MOD expr
 21     | expr . GREATER expr
 22     | expr . GREATER_EQUAL expr
 23     | expr . LESS expr
 24     | expr . LESS_EQUAL expr
 25     | expr . EQUAL expr
 26     | expr . NOTEQUAL expr
 27     | expr . AND expr
 28     | expr . OR expr
 95 returnstmt: RETURN expr .

PLUS           shift, and go to state 74
MINUS          shift, and go to state 75
MUL            shift, and go to state 76
DIV            shift, and go to state 77
MOD            shift, and go to state 78
EQUAL          shift, and go to state 79
NOTEQUAL       shift, and go to state 80
OR             shift, and go to state 81
AND            shift, and go to state 82
GREATER        shift, and go to state 83
LESS           shift, and go to state 84
GREATER_EQUAL  shift, and go to state 85
LESS_EQUAL     shift, and go to state 86

MINUS     [reduce using rule 95 (returnstmt)]
$default  reduce using rule 95 (returnstmt)

知道怎么解决吗?

【问题讨论】:

    标签: parsing bison yacc


    【解决方案1】:

    由于您没有展示完整的语法,因此很难说出问题所在。由于上下文或规则的组合方式,冲突通常是由于语法中的其他规则(而不是冲突状态中显示的规则)造成的。

    • 状态 34/36: 看起来您在 primarylvaluecall 的规则之间存在某种循环歧义。这些(完整的)规则是什么?如何期望知道左值和主值之间的区别?

    • 状态 52:这里看起来像是 returnstmt 和以下以 MINUS 开头的表达式之间的歧义。您好像没有语句终止符/分隔符?

    这些都可能是同一个潜在问题——解析器无法确定一个语句在哪里结束,下一个语句从哪里开始......

    【讨论】: