simple criteria expression parser with antlr3

故事扮演 提交于 2019-12-06 10:36:44

One flaw in your grammar is the rule

expression
  :
  LPAREN* subcond RPAREN* (( AND | OR )^ LPAREN* subcond RPAREN*)
  ;

Since you can have any number of LPAREN or RPAREN, there is no guarantee they are matched. I suggest using somehting like

expression
  : subcond (( AND | OR ) subcond)?
  | subcond
  ;

and for subcond

subcond
  : atom (( AND | OR )^ atom)*
  | LPAREN expression RPAREN
  ;

Ideally, you should also have separate rules for AND and OR expressions to have the correct precedence in your parse tree.

Update: In your updated grammar, again you are using LPAREN* and RPAREN* which won't give you properly balanced trees. You need to model multiple parens like ((a = 1)) with recursion, like I described in my example above. This would give a tree like

((a = 1))
  ^---^--- ATOM
 ^-----^-- Subcond -> Expression
^-------^- Subcond -> Expression

So the tree would be like that:

Expression "((a = 1))"
^
Subcond "(a = 1)"
^
Expression "(a = 1)"
^
Subcond "a = 1"
^
ATOM "a = 1"

May be I'm wrong butI think you problem connected with this thing LPAREN* something RPAREN* you can write comething like this ((something ) and antlr think that this write because LParent and Rparent have not connected to each other so may be use something like this

COMPLEX:
    LPARENT (COMPLEX|subcond) RPARENT;

But I will say it again, maybe I'm wrong

UPDATE

change this:

subcond
  : 
  //atom (( AND | OR )^ atom)*
  LPAREN* atom RPAREN*
  ;

to this:

subcond
  : 
  LPAREN (subcond|atom) RPAREN
  ;

using this you can now write something like this ((a=1))

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