[antlr-interest] Rewrite a list to a set of trees

Gary R. Van Sickle g.r.vansickle at att.net
Thu May 21 22:58:44 PDT 2009


> Hello,
> 
> To make checking and generating easier, I would like to parse 
> lines like the
> following:
> node n1, n2, n3;
> 
> And turn them into trees like this:
> (VAR 'node' 'n1')
> (VAR 'node' 'n2')
> (VAR 'node' 'n3')
> 
> At the moment I'm using the following rules to parse, but 
> this obviously does not generate the result I would like to have:
> var_declaration : var_type id_list -> ^(VAR var_type id_list) ;
> 
> id_list : IDENTIFIER (COMMA! id_list)? ;
> 
> Obviously, this generates trees like this:
> (VAR 'node' 'n1' 'n2' 'n3')
> 
> Could anyone point me in a direction that allows me to end up 
> with trees like I described above? If this is at all possible ;)
> 
> Thanks a lot!
> 
> Olaf Keijsers 

As long as you're not trying to do anything more complex than exactly what
you describe, this is fairly trivial to do with a rule that looks something
like this:

var_decl_list
	: TYPENAME ids+=IDENTIFIER (',' ids+=IDENTIFIER)* -> ^(VAR_DECL
TYPENAME IDENTIFIER)+
	;

If your rule can't be reduced to a one-liner like that though (e.g. C
declarations), things quickly get complicated, and I've yet to determine a
good, general way of handling it.  You'll probably want to look into ANTLR's
rule parameters and return values in that case.

-- 
Gary R. Van Sickle
 



More information about the antlr-interest mailing list