Grammar for expressions which disallows outer parentheses

て烟熏妆下的殇ゞ 提交于 2019-12-07 16:17:04

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36001979/grammar-for-expressions-which-disallows-outer-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!