开发者

Question regarding BNF

开发者 https://www.devze.com 2023-02-08 22:31 出处:网络
I have this grammar written in BNF. How do I convert it to give + precedence 开发者_C百科over * and force + to be right associative?

I have this grammar written in BNF. How do I convert it to give + precedence 开发者_C百科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,


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)

<assign> -> id = <expr>
<id>     -> A | B | C
<expr>   -> <expr> * <term> | <term>
<term>   -> <term> + <factor> | <factor>
<factor> -> ( <expr> ) | <id>

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:

<assign> -> id = <expr>
<id>     -> A | B | C
<expr>   -> <term> * <expr> | <term>
<term>   -> <factor> + <term> | <factor>
<factor> -> ( <expr> ) | <id>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号