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

Craig Main craig at palantir.co.za
Sat Jun 17 23:35:33 PDT 2006


Hi all,

I apologise in advance for having a conversation with myself in the mailing
list, but I figured out the problem and thought I would respond in to avoid
wasting anyone's precious time.

The problem was that I had stupidly specified:
expression : #(PLUS l=term r=term) // goes too deep to recurse later on?

Instead of:
expression : #(PLUS l=expression r=expression) // correct children.

Thanks
Regards
Craig

-----Original Message-----
From: antlr-interest-bounces at antlr.org
[mailto:antlr-interest-bounces at antlr.org] On Behalf Of Craig Main
Sent: 17 June 2006 08:08 PM
To: antlr-interest at antlr.org
Subject: [antlr-interest] Tree Recursion (matching problem).

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