Updated: Is there any way to re-use the rule in the parser grammer? Maybe my understanding of ANTLR tree parser is not correct. I think ANTLR tree parser is another kind of parser. I still need to create the right rule to meet my request. If so, what is the propose of AST? I already generate the right AST structure, but seems useless in the tree parser.
Why
^(OR first=andExp other=andExp*)
cannot be wrtten into
andExp ( OR^ andExp)*
in the tree parser ? I think I didn't get the key point to write the tree parser.
I want to write a SQL style criteria expression parser with Antlr3. It need support something like
a = 1 and b = 2 and c = 3
I already complete the Lexer and Parser, but I got problem when I create Tree Parser according to the AST.
Currently only support 2 nodes of the express like a = 1 and b = 2
but cannot support a = 1 and b = 2 and c = 3
Looks like ^(OR first=andExp other=andExp*)
is not correct, but I have no idea how to modify it. Since I'm newbie in ANTLR, so I checked a lot of example to complete my tree parser, but still have no clue how to express multiple nodes in ANTLR tree parser. Can someone help me to address it? Any comments are appreciated.
My lexer and parser can be found in following URLs.
simple criteria expression parser with antlr3
Here is my Tree Parser:
tree grammar CriteriaExpressionEval;
options {
language = Java;
tokenVocab = CriteriaExpression;
ASTLabelType = CommonTree;
}
@header {package com.antlr;}
eval
:
expression
;
expression returns[String expStr]
: ^(OR first=andExp other=andExp*)
{
$expStr = $first.addExpStr + " " + $OR.text + " " + $other.addExpStr;
System.out.println("expression -- ^(OR first=andExp other=andExp*) [" + $expStr + "]");
}
|andExp
{
$expStr = $andExp.addExpStr;
System.out.println("expression -- andExp [" + $expStr + "]");
}
;
andExp returns[String addExpStr]
: ^(AND left=subcond right=subcond*)
{
$addExpStr = $left.subCondStr + " " + $AND + " " + $right.subCondStr;
System.out.println("andExp -- ^(AND left=subcond right=subcond*) [" + $addExpStr + "]");
}
|subcond
{
$addExpStr = $subcond.subCondStr;
System.out.println("andExp -- subcond [" + $addExpStr + "]");
}
;
subcond returns[String subCondStr]
: LPAREN expression RPAREN
{
$subCondStr = "(" + $expression.expStr + ")";
System.out.println("subcond -- LPAREN expression RPAREN [" + $subCondStr + "]");
}
|atom
{
$subCondStr = $atom.atomStr;
System.out.println("subcond -- atom [" + $subCondStr + "]");
}
;
atom returns[String atomStr]
:
prop=EXPR OPERATOR val=EXPR { $atomStr = $prop.text + $OPERATOR.text + $val.text; }
;