[antlr-interest] Rewrite Problem,
Craig Main
craig at palantir.co.za
Sun Jul 30 05:59:13 PDT 2006
Hi,
I am trying to get a tree with the operator as a root tree node, and then
the two operands, so with versions prior to 3 I would have used.
expression : lvalue=term ((operator=PLUS^|operator=MINUS^)
rvalue=term)* // note where the ^ is.
;
And now I try the following:
expression : lvalue=term ((operator=PLUS|operator=MINUS)
rvalue=term)* -> ^($operator $lvalue $rvalue)*
; // I also tried $operator $expression $expression,
which is actually more correct because it is a recursive structure.
All kinds of weird things are happening to the tree, sometimes there are no
nodes in the tree. It is just (nil)
I have pasted the whole grammar below.
How do I build an AST using the new rules that would match the following
(this is what I have in my version 2.7.6 tree):
expression
: #(PLUS l=expression r=expression);}
| #(MINUS l=expression r=expression)
{result=ExpressionOperation.Subtract(l,r);}
| #(MULTIPLY l=expression r=expression)
{result=ExpressionOperation.Multiply(l,r);}
| #(DIVIDE l=expression r=expression)
{result=ExpressionOperation.Divide(l,r);}
| result=term {log.Debug("term");}
;
My problem is that I don't know how to specify the expression properly.
I need something like ^($operator $expression $expression), and not $lvalue
and $rvalue, because they are actually expressions as well?
That results in a nil tree again.
A cog is not turning.
The whole grammar is as follows.
grammar RuleParser;
options {
output = AST;
ASTLabelType = CommonTree;
}
start : statement+;
statement : assign
;
assign : ID ASSIGN^ expression// -> ^(ASSIGN expression)
;
expression : lvalue=term ((operator=PLUS|operator=MINUS)
rvalue=term)* -> ^($operator $lvalue $rvalue)*
;
term : lvalue=factor ((operator=MULTIPLY^|operator=DIVIDE^)
rvalue=factor)* //-> ^($operator $lvalue $rvalue)*
;
factor : literal
;
literal : ID^
| FLOAT^
;
/* tokens */
ID : ('a'..'z'|'A'..'Z'|'_')
('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
;
ASSIGN : '=' ;
MULTIPLY : '*' ;
DIVIDE : '/' ;
PLUS : '+' ;
MINUS : '-' ;
DIGIT : '0'..'9' ;
FLOAT : (DIGIT)+ ('.' (DIGIT)*)?
;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20060730/4bbe153e/attachment.html
More information about the antlr-interest
mailing list