[antlr-interest] SimpleCalc Tree Rewrite Rules
Matthew Bowman
matthew.bowman at sogotech.com
Mon Sep 17 01:31:32 PDT 2007
So I have the following grammar:
grammar SimpleCalcTree;
options { output=AST; }
tokens{ OP; NUM; }
expr : l=term (o=plus_minus r=term)* -> ^(OP $o $l $r);
term : l=factor (o=mult_divide r=factor)* -> ^(OP $o $l $r);
factor : NUMBER -> ^(NUM NUMBER);
plus_minus : PLUS | MINUS;
mult_divide : MULT | DIVIDE;
PLUS : '+';
MINUS : '-';
MULT : '*';
DIVIDE : '/';
NUMBER : '0'..'9'+;
And my problem is with the rewrite rules. I want it to only rewrite the
rule with (OP $o $l $r) if it actually matches 'term plus_minus term' or
'factor mult_divide factor' but if it only matches a term or factor I
want the subtree from factor.
Examples of what I'm trying to accomplish (and support order of
operations)...
Input: 2
Output: (NUM 2)
Input: 2 + 2
Output: (OP + (NUM 2) (NUM 2))
Input: 2 * 2 - 4
Output: (OP - (OP * (NUM 2) (NUM 2)) (NUM 4))
My real world example is much more complex but this if I can solve this
trivial case then I can adapt it to what I need.
Thanks in advance!
--
Matthew Bowman
More information about the antlr-interest
mailing list