[antlr-interest] adding content at end ofrulewithTokenRewriteStream

David Holroyd dave at badgers-in-foil.co.uk
Sun Feb 25 09:25:23 PST 2007


On Fri, Feb 23, 2007 at 07:48:48PM +0100, Jean Marc Vanel wrote:
> Jean Marc Vanel wrote:
> ....
> > > name_or_pointer
> > > @init {
> > >     tokens = (TokenRewriteStream)input;
> > > }
> > >     	:	NAME (star='*')?
> > > 		{ tokens.insertAfter( star.stop, " == after '*' ===" ); }
> > > 	;
[snip]
> [Jean-Marc Vanel] But if there are many places where this rule appears,
> I don't want to paste the same thing in many places.
> Indeed, there are tokens for that rule, it's just that in the action
> language I can't get hold on the last token.

How about abusing the rewrite syntax a bit, just so that you can access
the result tree for the rule,

  name_or_pointer
	:	(NAME STAR? -> NAME STAR?)
		{ tokens.insertAfter( $name_or_pointer.tree.stop, "blah" ); }
	;

I didn't test the code above, but I think I've done something like that
in the past.

The problem is (I think) that ANTLR doesn't normally set the stop-token
for the result tree until *after* the rule and all its actions have
executed, which makes it tricky for the rule itself to get at this
information.

Actually, all ANTLR does to set the stop-token is to assign the value
from input.LT(-1), so maybe you could just use that,

  name_or_pointer
	:	NAME STAR? { tokens.insertAfter(input.LT(-1), "blah"); }
	;

(again, untested code)


ta,
dave

-- 
http://david.holroyd.me.uk/


More information about the antlr-interest mailing list