[antlr-interest] backtrack=false and AST generation

John B. Brodie jbb at acm.org
Sun Apr 18 08:05:15 PDT 2010


Greetings!

On Sun, 2010-04-18 at 16:30 +0200, Giampaolo Tomassoni wrote:
> > You can pass trees from one rule to another as a parameter(s),
> > maybe that might help, something like (probably requires more
> > work to obtain the tree you are after):
> > 
> > protected
> > expression
> >     :	e=conditionalOrExpression conditionalExpression[$e.tree]
> >     ;
> > 
> > protected
> > conditionalExpression[CommonTree TheActualASTRoot]
> >     :	QMARK t=expression COMMA f=expression
> >             -> ^(ITE ${TheActualASTRoot} $t $f)
> >     |
> >     ;
> > 
> > Regards, Mark
> 
> Thank you Mark, for your clever reply.
> 
> May I ask if there is any way to do somthing like this:
> 
> protected
> expression
>     :	e=conditionalOrExpression c=conditionalExpression[$e] -> $c
>     ;
> 
> protected
> conditionalExpression[conditionalOrExpression e]
>     :	QMARK t=expression COMMA f=expression	-> ^(ITE $e $t $f)
>     |						-> $e
>     ;
> 
> It seems cleaner to me, since this way subrules are not going to "play
> dirty" with the root of their parents.
> 
> Unfortunately, this notation causes a "reference to undefined label in
> rewrite rule: $e" error. The point may be "e" is not of
> conditionalOrExpression type or, well, I don't really know why. Something
> like that works with non-AST generating combined parsers (with more
> classical actions, then). But it seems not to work with rewrite actions.
> 

I do not know why you get the undefined label error.

Have you considered not using a sub-rule for the then-else part?

Something like:

expression : 
    conditionalOrExpression (QMARK^ expression COMMA! expression) ?
  ;

or if you really want ITE as the root (instead of QMARK) perhaps:

expresssion :
    ( c=conditionalOrExpression -> $c )
        ( QMARK t=expression COMMA f=expression-> ^(ITE $c $t $f) )?
 ;


Hope this helps...
   -jbb
   



More information about the antlr-interest mailing list