[antlr-interest] Tree Recursion (matching problem).

Craig Main craig at palantir.co.za
Sat Jun 17 11:07:36 PDT 2006


Hi,

I have built a simple tree parser that parses, producing the following AST.

( RULESET ( = b ( + 40 ( * 2 1 ) ) ) )

I am having trouble with the recursive part of the process.
My rule is as follows:

expression
returns [object result]            {log.Debug(null); result = null;object
l,r;}                                   
                                 : #(PLUS l=term r=term)
{result=ExpressionOperation.Add(l,r);}
                                 | #(MINUS l=term r=term)
{result=ExpressionOperation.Subtract(l,r);}
                                 | #(MULTIPLY l=term r=term)
{result=ExpressionOperation.Multiply(l,r);}
                                 | #(DIVIDE l=term r=term)
{result=ExpressionOperation.Divide(l,r);}                                 
                                 | result=term {log.Debug("term");}
                                 ;

term
returns [object result]            {log.Debug(null); result = null; object
expr = null;}
                                 : result=literal
                                 ;

literal
returns [object result]            {log.Debug(null); result = null; object
expr = null;}
                                 : id:ID { result = id.getText(); }
                                 | fl:FLOAT { result =
double.Parse(fl.getText()); }
                                 | li:LITERAL { result = li.getText(); }
                                 | #(LPAREN expression)
                                 | #(m:METHOD_CALL #(ELIST (expr=expression
{log.Info(string.Format("e{0}",expr));})*)) {log.Info(string.Format("method
call {0}", m.getText()));}
                                 ;

The problem with the above is that the following works, an expression of 
a = 40 + 2

If I add another term, the matching breaks
a = 40 + 2 * 1
The tree parser fails on the multiplication.

As you can see, the tree is built correctly! I am just not matching
correctly.
What am I doing wrong?

Regards
Craig





More information about the antlr-interest mailing list