简体   繁体   中英

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) .

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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