表达式的语法不允许外括号

表达式的语法不允许外括号

本文介绍了表达式的语法不允许外括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



$ $ $ $ $ $ $ $ $ $ code> expression:expression BITWISE_OR xor_expression
| xor_expression
xor_expression:xor_expression BITWISE_XOR and_expression
| and_expression
and_expression:and_expression BITWISE_AND shift_expression
| shift_expression
shift_expression:shift_expression LEFT_SHIFT arith_expression
| shift_expression RIGHT_SHIFT arith_expression
| arith_expression
arith_expression:arith_expression PLUS项
| arith_expression MINUS项
|期限
期限:期限TIMES因子
|期限DIVIDE因子
|因子
因子:NUMBER
| LPAREN表达式RPAREN

这似乎工作正常,但不符合我的需要,因为它允许外部括号例如((3 + 4)* 2)



如何更改语法以禁止外括号,而仍然允许他们在表达中,例如(3 + 4)* 2 ,甚至冗余例如(3 * 4)+ 2

解决方案

将此规则添加到你的语法:

  top_level:expression BITWISE_OR xor_expression 
| xor_expression BITWISE_XOR and_expression
| and_expression BITWISE_AND shift_expression
| shift_expression LEFT_SHIFT arith_expression
| shift_expression RIGHT_SHIFT arith_expression
| arith_expression术语
| arith_expression MINUS项
|期限TIMES因子
|期限DIVIDE因子
| NUMBER

,并使用top_level,您想要没有外括号的表达式。


I have the following grammar for expressions involving binary operators (| ^ & << >> + - * /):

expression       : expression BITWISE_OR xor_expression
                 | xor_expression
xor_expression   : xor_expression BITWISE_XOR and_expression
                 | and_expression
and_expression   : and_expression BITWISE_AND shift_expression
                 | shift_expression
shift_expression : shift_expression LEFT_SHIFT arith_expression
                 | shift_expression RIGHT_SHIFT arith_expression
                 | arith_expression
arith_expression : arith_expression PLUS term
                 | arith_expression MINUS term
                 | term
term             : term TIMES factor
                 | term DIVIDE factor
                 | factor
factor           : NUMBER
                 | LPAREN expression RPAREN

This seems to work fine, but doesn't quite match my needs because it allows outer parentheses e.g. ((3 + 4) * 2).

How can I change the grammar to disallow outer parentheses, while still allowing them within expressions e.g. (3 + 4) * 2, even redundantly e.g. (3 * 4) + 2?

解决方案

Add this rule to your grammar:

top_level : expression BITWISE_OR xor_expression
          | xor_expression BITWISE_XOR and_expression
          | and_expression BITWISE_AND shift_expression
          | shift_expression LEFT_SHIFT arith_expression
          | shift_expression RIGHT_SHIFT arith_expression
          | arith_expression PLUS term
          | arith_expression MINUS term
          | term TIMES factor
          | term DIVIDE factor
          | NUMBER

and use top_level where you want expressions without outer parens.

这篇关于表达式的语法不允许外括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:22