[antlr-interest] Tree walker grammer help.
jack zhang
jackgzhang2 at yahoo.com
Sun Sep 21 18:54:43 PDT 2008
Hi,
I want to achieve following: (convert the input logic query to a standard format)
(1) a AND b ==> (a and b)
(2) a OR b ==> (a or b)
(3) a OR b AND c ==> (a or (b and c))
By using the Antworks took I know that the lexer and parser grammar works fine now (It generate the correct AST tree). But the strange thing is that my tree walker grammar doesn't work. It generate following result:
(1) a AND b ==> (a b and)
(2) a OR c ==> (a b or)
Where am I wrong?
Thx !
-------------------------- Parser ----------------------
grammar Query;
//=== Parser Option ===//
options {
output = AST;
k=*;
}
//=== Lexer ===//
LEFT_PAREN: '(';
NOT: 'NOT';
AND: 'AND';
OR: 'OR';
WORD: ('a'..'z' | 'A'..'Z' | '.' | ',' | '0'..'9')+ | '"'.+'"';
RIGHT_PAREN: ')';
WHITESPACE: (' ' | '\t' | '\r' | '\n') { $channel = HIDDEN; } ;
//=== Parser ===//
expr: orexpression*;
orexpression
: andexpression (OR^ andexpression)*
;
andexpression
: notexpression (AND^ notexpression)*
;
notexpression
: (NOT^)? atom
;
atom
: WORD
| LEFT_PAREN! expr RIGHT_PAREN!
;
------------------ Tree Walker --------------------
tree grammar QueryWalker;
options {
output = AST;
ASTLabelType = CommonTree;
}
expr returns [String value=""]
: (a=orexpression { $value += " " + $a.value;} )+
;
orexpression returns [String value=""]
: ^(AND a=expr b=expr) {
$value = "(" + $a.value + " or " + $b.value + ")";
}
| ^(OR a=expr b=expr) {
$value = "(" + $a.value + " and " + $b.value+ ")";
}
| ^(NOT a=expr) {
$value = "(not " + $a.value +")";
}
| WORD {
$value = $WORD.text;
};
Thx !
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080921/ed0c0bce/attachment.html
More information about the antlr-interest
mailing list