Search code examples
parsingexpressiongrammarcontext-free-grammarbnf

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 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?


Solution

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