[antlr-interest] Re: Building trees with the correct associativity

lgcraymer lgc at mail1.jpl.nasa.gov
Wed Dec 1 20:52:34 PST 2004



--- In antlr-interest at yahoogroups.com, "Paul J. Lucas"
<pauljlucas at m...> wrote:
> On Thu, 2 Dec 2004, lgcraymer wrote:
> 
> > I'm not at all sure of that.  I think that the observation that the
> > normal tree construction here (via ^ annotation) is left associative.
> > That's not an obvious point.
> 
> 	Ignoring for the moment whether that's true, the reason I'm
> 	doing what I'm doing is because if I do ^, then, in my
> 	treeparser, I need two seperate yet almost identicle rules to
> 	handle PLUS and MINUS, i.e.:
> 
> 		plusExpr: #( PLUS e1=expr e2=expr ) ;
> 
> 		minusExpr: #( MINUS e1=expr e2=expr ) ;

Actually, I'd do these as subrules:

addExpr
    :
    #( PLUS expr expr )
    |   #(MINUS expr expr )
    ;

But it is hard to avoid having the alternatives since they need to
generate different action code.  Well, I suppose that you could negate
the second expr and use only PLUS, but that isn't really useful.

> 	If I do a setType() in the parser, then which operator was used
> 	is lost.  Hence, I have one ADD_EXPR that contains a child node
> 	that is the actual operator.
> 
> 	Now, back to the problem at hand....
> 
> 	OK, I just tried it and -- you're right!  :-O  You're also right
> 	about it not being an obvious point.  OK, I suppose I could
> 	have yet another level in the tree by allowing PLUS or MINUS to
> 	be a local root.
> 
> 	Is there any way to get left-associativity when not using ^ and
> 	constructing the tree yourself?

How about

addExpr
{ AST el = null; }
    :
    m1:mulExpr { el = m1 }
    (    a:addOp b:mulExpr
         { ## = #([ADD_EXPR,"ADD_EXPR", e1, a b); e1 = ##; }
    )

That is truly ugly--I really need to push on getting 2.8 out the door.

--Loring

> 	- Paul





 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
    antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 





More information about the antlr-interest mailing list