[antlr-interest] Concatenation in Tree Rewriting

Kay Röpke kroepke at classdump.org
Tue Aug 12 08:34:55 PDT 2008


On Aug 12, 2008, at 2:57 PM, Louis Rose wrote:

> Hi all,
>
> I was wondering if there's a more elegant way to write the  
> intentions of the following grammar rule:
>
> adjective
>      :   ADJECTIVE_PREFIX? NAME -> {new CommonTree(new  
> CommonToken(ADJECTIVE, ($ADJECTIVE_PREFIX.text == null ?  
> $NAME.text : $prefix.text + $NAME.text)))}
>      ;
>
> The ADJECTIVE token type is an imaginary token, and has been defined  
> in the tokens {} block.


Not directly, I think.

To avoid having the action in the rewrite rule, you could build up the  
prefix-name combination in a separate string.

grammar Imag;

options { output=AST; }
tokens { IMAG; }

PREFIX:	'foo::';
NAME:	'name';

rule
@init {
String name = new String();
}
	:	(PREFIX {name = $PREFIX.text;})? NAME {name += $NAME.text;} ->  
^(IMAG[name])
	;

Or even:

rule
	:	PREFIX? NAME -> ^(IMAG[($PREFIX.text == null ? "" : $PREFIX.text) +  
$NAME.text])
	;

Which I'm surprised is working :P The first  ?: is to work around  
having null turn to "null" when toString is called on it.
I would exactly do it, because it looks really ugly, but it works. I  
prefer the first version.

cheers,
-k

-- 
Kay Röpke
http://classdump.org/








More information about the antlr-interest mailing list