如何在简单的语法中添加括号作为最高优先级? [英] How can I add parentheses as the highest level of precedence in a simple grammar?

查看:118
本文介绍了如何在简单的语法中添加括号作为最高优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在语法中添加2项内容:

I'm trying to add 2 things to my grammar:

  1. 一元减号,即'-'和

  1. Unary minus sign, i.e. '-', and

身体感觉

到目前为止,这是我的语法:

Here's my grammar so far:

<comp>  ::= <expr> | <comp> <op0> <expr>
<expr>  ::= <term> | <expr> <op1> <term>
<term>  ::= <darg> | <term> <op2> <darg>
<darg>  ::= <digit> | <darg> <digit>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<op0>   ::= > | < | =< | => | =
<op1>   ::= + | -
<op2>   ::= * | /

我已经尝试了所有方法,但无法解决.如何使一元减号处于最高优先级,然后再加上括号,然后再描述其余的运算符?

I've tried everything and can't figure this out. How can I make the unary minus sign be at the highest level of precedence, followed by parentheses next and then the remaining operators as they are described?

推荐答案

我要在当前语法中添加一个名为<new> 的新变量,该变量具有三个新的生产规则,以添加Unary minus signParentheses:

I am adding a new variable named <new> with three new production rules in your present grammar in question to add Unary minus sign and Parentheses:

<comp>  ::= <expr>   | <comp> <op0> <expr>
<expr>  ::= <term>   | <expr> <op1> <term>
<term>  ::= <new>    | <term> <op2> <darg>
<new>   ::= (<comp>) | -<darg> | <darg> 
<darg>  ::= <digit>  |  <darg> <digit>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<op0>   ::= > | < | =< | => | =
<op1>   ::= + | -
<op2>   ::= * | /

通过添加括号,您在语法{ (, ) }

此外,如果要生成类似(-7)(7)((6+7))的表达式,则可以添加<new> ::= ( <new> ).(这些是有效的表达式)

Also, you can add <new> ::= ( <new> ) if you want to generate (-7), (7) and ((6+7)) like expressions.(these are valid expressions)

我想通知您,如果您正在编写编译器,请改用歧义语法,并在YACC工具中添加运算符优先级,以实现高效解析

编辑:

如果要添加像-(7)这样的表达式,那是一个有效的表达式.所以<new> ::= -<new>而不是<new> ::= <drag>

If you wants to add expression like -(7) and that is a valid expression. So <new> ::= -<new> instead of <new> ::= <drag>

这篇关于如何在简单的语法中添加括号作为最高优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆