如何解决 YACC 移位/减少后增量运算符的冲突?
我正在用 YACC(实际上是 Bison)编写语法,并且遇到了移位/归约问题。 它是包含后缀递增和递减运算符的结果。 这是语法的精简版本:
%token NUMBER ID INC DEC
%left '+' '-'
%left '*' '/'
%right PREINC
%left POSTINC
%%
expr: NUMBER
| ID
| expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| INC expr %prec PREINC
| DEC expr %prec PREINC
| expr INC %prec POSTINC
| expr DEC %prec POSTINC
| '(' expr ')'
;
%%
Bison 告诉我有 12 个移位/归约冲突,但如果我注释掉后缀增量和减量的行,它就可以正常工作。 有谁知道如何解决这个冲突? 此时,我正在考虑转向 LL(k) 解析器生成器,这使得它变得更容易,但 LALR 语法看起来总是写起来更自然。 我也在考虑 GLR,但我不知道有什么好的 C/C++ GLR 解析器生成器。
I'm writing a grammar in YACC (actually Bison), and I'm having a shift/reduce problem. It results from including the postfix increment and decrement operators. Here is a trimmed down version of the grammar:
%token NUMBER ID INC DEC
%left '+' '-'
%left '*' '/'
%right PREINC
%left POSTINC
%%
expr: NUMBER
| ID
| expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| INC expr %prec PREINC
| DEC expr %prec PREINC
| expr INC %prec POSTINC
| expr DEC %prec POSTINC
| '(' expr ')'
;
%%
Bison tells me there are 12 shift/reduce conflicts, but if I comment out the lines for the postfix increment and decrement, it works fine. Does anyone know how to fix this conflict? At this point, I'm considering moving to an LL(k) parser generator, which makes it much easier, but LALR grammars have always seemed much more natural to write. I'm also considering GLR, but I don't know of any good C/C++ GLR parser generators.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您在选项部分指定
%glr-parser
,Bison/Yacc 可以生成 GLR 解析器。Bison/Yacc can generate a GLR parser if you specify
%glr-parser
in the option section.试试这个:
关键是将后缀运算符声明为非关联。 否则你将能够
括号也需要被赋予优先级以最小化移位/减少警告
Try this:
The key is to declare postfix operators as non associative. Otherwise you would be able to
The parenthesis also need to be given a precedence to minimize shift/reduce warnings
我喜欢定义更多的项目。 你不应该需要 %left、%right、%prec 的东西。
尝试一下这种方法。
I like to define more items. You shouldn't need the %left, %right, %prec stuff.
Play around with this approach.
这个基本问题是您没有
INC
和DEC
标记的优先级,因此它不知道如何解决涉及前瞻的歧义INC
或DEC
。 如果您在优先级列表的末尾添加(您希望一元的优先级更高,后缀的优先级高于前缀),它会修复它,您甚至可以删除所有
PREINC
/POSTINC
的东西,因为它是无关紧要的。This basic problem is that you don't have a precedence for the
INC
andDEC
tokens, so it doesn't know how to resolve ambiguities involving a lookahead ofINC
orDEC
. If you addat the end of the precedence list (you want unaries to be higher precedence and postfix higher than prefix), it will fix it, and you can even get rid of all the
PREINC
/POSTINC
stuff, as it's irrelevant.前增量和后增量运算符具有非关联性,因此在优先级部分和规则中定义,通过使用
%prec
使这些运算符的优先级较高preincrement and postincrement operators have nonassoc so define that in the precedence section and in the rules make the precedence of these operators high by using
%prec