if elsif else 语句解析
我一直在使用 lex 和 yacc 开发命令式语言的编译器,今天我完成了语法,问题是我一直在网上读到每个语法都应该有一些移位/减少冲突,特别是如果它有 if/else 语句,通常称为悬空 if-else,而我的确实有 if/elsif/else 语句,但编译时不会引发任何冲突,问题是
“这是否意味着该语法有缺陷”只是因为它不会引发任何转变/减少冲突?我没有太多这样做的经验,但我找不到任何问题
如果您想要更多信息,此语法中 if/elsif/else 语句的产生式如下所示:
statement -> ...
------------| initial_conditional_stmt
initial_conditional_stmt: conditional_stmt
-----------------------| conditional_stmt 'else' block
conditional_stmt -> 'if' '(' expression ')' block
------------------| conditional_stmt elsif '(' expression ')' block
block 只是内部语句的列表括号{}
i've been working on a compiler for an imperative language using lex and yacc, and today i finished the grammar, the thing is that i've been reading on the web that every grammar is expected to have a few shift/reduce conflicts, specially if it has if/else statements, that's often known as dangling if-else, and mine does have if/elsif/else statements yet it doesn't throw any conflict when compiled, the question is
¿does that means this grammar has flaws just because it doesn't throw any shift/reduce conflicts? i dont have much experience doing this but i can't find any problem with it
In case you want some more information the productions for the if/elsif/else statements in this grammar are something like this:
statement -> ...
------------| initial_conditional_stmt
initial_conditional_stmt: conditional_stmt
-----------------------| conditional_stmt 'else' block
conditional_stmt -> 'if' '(' expression ')' block
------------------| conditional_stmt elsif '(' expression ')' block
block is just a list of statements inside brackets {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有shift/reduce冲突意味着你的语言设计做得非常好而且从来都不含糊。
干得好,拍拍自己的背,放松一下,去冰箱里拿杯啤酒。
No shift/reduce conflicts means you did a really good job of your language design and it's never ambiguous.
Well done, give yourself a pat on the back, relax, go grab a beer from the fridge.
您在这里没有得到悬空 else 的原因是因为您使用的是块而不是普通语句。
对于您的语法,您不能这样做
您必须这样做
每个嵌套的 if 语句必须位于匹配的 { } 内。在您的情况下,这消除了悬而未决的 else,但代价是语法有点奇怪。与“正常”语法相比,“块”将是“语句”,它也可能是另一个 if 语句,从而导致经典的移位/归约冲突。
The reason you are not getting the dangling else here is because you're using a block instead of the normal statement.
For your grammar you cannot do
You would have to do this
Every nested if statement must be inside matching { }. This in your case eliminates the dangling else at the expense of a bit stranger syntax. Compared to a "normal" grammar "block" would be "statement" which could also be another if statement, thus causing the classical shift/reduce conflict.
您最好按如下方式使用这些代码:
这是一种改变 if 和 else 之间的优先级冲突的方法。
希望有帮助。
You may better to use these code as following:
That is a way to change precedence conflict between if and else.
Hope it helps.