[英]Grammar for expressions which disallows outer parentheses
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 eg ((3 + 4) * 2)
. 这似乎工作正常,但不完全符合我的需要,因为它允许外括号,例如
((3 + 4) * 2)
。
How can I change the grammar to disallow outer parentheses, while still allowing them within expressions eg (3 + 4) * 2
, even redundantly eg (3 * 4) + 2
? 如何更改语法以禁止外括号,同时仍允许它们在表达式中,例如
(3 + 4) * 2
,甚至冗余,例如(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. 并使用top_level,你想要没有外部parens的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.