[antlr-interest] How to create binary AST with multiple operators?
Maciej Pilichowski
bluedzins at op.pl
Thu Aug 9 10:33:45 PDT 2012
Hello all,
I try to build entire AST with custom nodes, so for example my unary
expressions look like this:
-----------------------------------------------------------
not_expr : term
| op='not' ex=not_expr -> { new UnaryExpression($op,
$ex.tree) };
unary_expr : not_expr
| op='-' ex=unary_expr -> { new UnaryExpression(op,
$ex.tree) }
| '+'! unary_expr;
-----------------------------------------------------------
I had first problems when tackling binary expression -- power (like 2
^ 5). But thanks it is single operator, I could write method which
takes entire list of operands, and creates nested binary tree. And so
the rule is simple:
-----------------------------------------------------------
pow_expr : ex+=unary_expr (op='^' ex+=unary_expr)*
-> { BinaryExpression.createRightTree(op,$ex) };
-----------------------------------------------------------
However when I came to multi-operator binary expression I am lost --
now I try to handle multiplication and division at the same time.
This is my try:
-----------------------------------------------------------
mult_expr : exl=pow_expr { retval.tree = $exl.tree; } (
op=('*'|'/'|'mod'|'div') exr=pow_expr -> { new
BinaryExpression(op,$exl.tree,$exr.tree) }
)*;
-----------------------------------------------------------
First thing I don't like the start of it -- there is too much hackery
for my taste for the initial value (retval...), second -- there is no
mechanism which "glues" consecutive expressions (like 5*3*2), and
third -- it does not work at all.
So the question is -- how to do it?
Thank you in advance,
More information about the antlr-interest
mailing list