簡體   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