关于BNF的问题
我用 BNF 写了这个语法。如何将其转换为 + 优先于 * 并强制 + 为右关联?
<assign> -> id = <expr>
<id> -> A | B | C
<expr> -> <expr> + term | <term>
<term> -> <term> * <factor> | <factor>
<factor> -> ( <expr> ) | <id>
这是我的解决方案:
<assign> -> id = <expr>
<id> -> A | B | C
<expr> -> <expr> * term | <term>
<term> -> <term> + <factor> | <factor>
<factor> -> ( <expr> ) | <id>
如何检查给定语法的正确性?有什么想法吗?
谢谢,
I have this grammar written in BNF. How do I convert it to give + precedence over * and force + to be right associative?
<assign> -> id = <expr>
<id> -> A | B | C
<expr> -> <expr> + term | <term>
<term> -> <term> * <factor> | <factor>
<factor> -> ( <expr> ) | <id>
This is my solution:
<assign> -> id = <expr>
<id> -> A | B | C
<expr> -> <expr> * term | <term>
<term> -> <term> + <factor> | <factor>
<factor> -> ( <expr> ) | <id>
How could I check the correctness of a given grammar? Any idea?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来很奇怪,你想要恢复乘法相对于加法的优先级,但无论如何,如果你需要这种语法,那么正确的 BNF 将是(你在第三个产生式上犯了一个拼写错误),
这对于 LR 解析器来说是正确的(底部-向上)。
对于 LL 解析器(自上而下),上述语法将导致
和
上的左递归。要解决此问题,您应该对 LL 解析器使用以下语法:
Looks strange that you want to revert the precedence of multiplication over addition, but anyway if you need the grammar that way, then the correct BNF would be (you made a typo on the third production)
Which is right for an LR parser (bottom-up).
For a LL parser (top-down), the above grammar will cause left recursion on
<expr>
and<term>
.To workaround this issue, you should use this grammar for LL parsers: