I want to create a simple criteria expression parser with antlr3
Updated: separate AND OR expression rules to support AND/OR different hierarchy, but got another problems: if the expression is something like: a = 1 and b = 2 and c = 3 The tree should be as following according to current implement:
= =
(a = 1)(b = 2)(c = 3)
But I want to generate it as follows:
= =
(a = 1)(b = 2)
(c = 3)
First "and" should be higher priority than another, because I want to parse all the expression as left exp and right exp.
I think I need to re-write the rule in the "subcond" To make a = 1 and b = 2 and c = 3 -> (a = 1 and b = 2) and c = 3
but tried many times with no luck. Has anybody got an idea how to achieve it? Thanks.
My goal is to parse some kind of SQL where clause style sentence, and build a AST to walk through.
For example:
a = 1 and (b = 2 or c = 3) //This one can parse correctly.
a = 1 and ((b = 2 or c = 3) or d = 4) //This one cannot parse correctly, missing last d = 4 in the tree.
//Tree is not correct.
My current grammar file cannot parse above complex condition. For I'm newbie for antlr, not sure how to modify my grammar to achieve above approach more correctly. Can someone help on this? !Any suggestions or comments are appreciate.
and my grammar as follows (Updated according to the comments. Warning issue resolved.):
grammar CriteriaExpression;
options {
output = AST;
ASTLabelType = CommonTree;
language = Java;
}
tokens {
AND = 'and';
OR = 'or';
LPAREN = '(';
RPAREN = ')';
}
@lexer::header {
package com.antlr;
}
@parser::header {
package com.antlr;
}
eval
:
expression
;
expression : andExp (OR^ andExp)* ;
andExp : subcond (AND^ subcond)* ;
subcond : LPAREN expression RPAREN |atom ;
atom
:
EXPR OPERATOR EXPR
;
OPERATOR
:
'='| '<>'| '!='| '<='| '!>'| '<'| '>='| '!<'| '>'| 'like'
;
EXPR
:
('a'..'z'| 'A'..'Z'| '0'..'9')+
;
WILDCARD
:
'%'
;
WS
:
('\t'| ' '| '\r'| '\n'| '\u000C')*
{$channel = HIDDEN;}
;
((a=1))
a = 1 and ((b = 2 or c = 3) or d = 4)