繁体   English   中英

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

[英]Grammar for expressions which disallows outer parentheses

对于涉及二元运算符的表达式,我有以下语法(| ^&<< >> + - * /):

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

这似乎工作正常,但不完全符合我的需要,因为它允许外括号,例如((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 PLUS term
          | arith_expression MINUS term
          | term TIMES factor
          | term DIVIDE factor
          | NUMBER

并使用top_level,你想要没有外部parens的表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM