简体   繁体   English

Antlr4语法围绕字符串可选括号

[英]Antlr4 grammar optional brackets around string

I am trying to write a grammar to evaluate an equation which may or may not be surrounded by brackets. 我正在尝试编写一个语法来评估一个方程式,该方程式可能会或可能不会被括号括起来。 ex - 前 -

  1. (NOT str1 matches 'hello') (不是str1匹配'你好')
  2. NOT (str1 matches 'hello') NOT(str1匹配'hello')
  3. (NOT (str1 matches 'hello')) (NOT(str1匹配'hello'))
  4. NOT str1 matches 'hello' NOT str1匹配'hello'

In my rules, I have 在我的规则中,我有

clause
: expression EOF
;

expression
 :
   LPAREN expression RPAREN                            #parenExpression
 | isNumeric                                     #isNumericExpression
 | leftSide IS NOT? NULL                               #nullExpression
 | compare                                           #comparatorExpression
 | NOT                                                 #notExpression

;


compare : NOT? LPAREN? NOT? leftSide op=comparator rightSide RPAREN? ;

Now, there are a couple of problems with this. 现在,这有几个问题。

  1. I don't check whether left and right brackets match. 我不检查左右括号是否匹配。
  2. There is at most ONE NOT in the clause. 条款中最多只有一个。

Any help on how to write grammar for these rules would be super helpful. 任何有关如何为这些规则编写语法的帮助都会非常有用。

Thanks in advance! 提前致谢!

Conceptually, expression are (typically) either complex, ie , recursive, or simple: 从概念上讲,表达为(典型地)或者复合物, ,递归的,或简单的:

expression
   : LPAREN expression RPAREN                 #parenExpression
   | NOT expression                           #notExpression
   | simpleExpression                         
   ;

simpleExpression
   : isNumeric                                #isNumericExpression
   | leftSide IS NOT? NULL                    #nullExpression
   | leftSide op rightSide                    #comparatorExpression
   ;

The first complex alt allows any level of balanced parenthesis around an expression. 第一个复合alt允许表达式周围的任何级别的平衡括号。 The second allows one or more NOT s to precede any expression. 第二个允许一个或多个NOT s在任何表达式之前。

The simple alts represent the most basic forms of an expression. 简单的alts代表表达式的最基本形式。

So, (NOT (str1 matches 'hello')) will be matched by 所以, (NOT (str1 matches 'hello'))将匹配

parenExpression -> notExpression -> parenExpression -> comparatorExpression . parenExpression - > notExpression - > parenExpression - > comparatorExpression

Of course, the two rules could be combined into one. 当然,这两条规则可以合二为一。

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

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