[antlr-interest] proposed enhancement to ANTLR v3 ST integration

Terence Parr parrt at cs.usfca.edu
Fri Jan 6 15:24:00 PST 2006


[Added to blog http://www.antlr.org/blog/antlr3/rewrite.tml ]

I've been resisting the temptation to introduce a new symbol to  
handle templates.  For example, to avoid adding a new special symbol,  
I introduced $templates::foo(args) as the template constructor to  
build foo, which translates to:

st = templateLib.getInstanceOf("foo");
st.setAttribute("arg1", ...);

With other template libs, you'd do $Java::method(...) etc...  Now I'm  
finding real situations where ST integration can be improved.  The  
ctor problem is reasonably solved, but setting attributes still  
sucks: st.setAttribute("arg1", e1); is repeated many times all over.   
A better notation would be $st.arg1 = e1; but that is highly  
ambiguous with the $x.y notation.  Anyway, after looking at a number  
of real examples now, I find the urge to introduce a new symbol to  
help the human brain separate rule/scope attribute references from  
template syntactic sugar.  I propose the following (developed in  
collaboration with Jean Bovet and influenced by Hartmut Kocher's  

   %foo(...)     ctor (even shorter than $templates::foo(...))
   %(...)        anonymous template from string expr
   %x.y = z;         set template attribute y of x (always set never  
get attr) to z
			[languages like python without ';' must still use the ';' which the
			code generator is free to remove during code gen]
   %(expr).y = z;     template attribute y of StringTemplate-typed  
expr to z

   what about other template scopes?

   %Java::method(...)         scoped constructor
   %CPP::method...)	...

Make sense?  Objections?  hard to tell until you see a real  
example ;)  I see a lot of

a : ID -> {new StringTemplate($ID.text)} ;

which would be now

a : ID -> {%($ID.text)} ;

or even simpler:

a : ID -> %($ID.text) ;

I see lots of setAttribute stuff like:

a[int foo] : ID
	StringTemplate x = $templates::foo();
	x.setAttribute("arg1", $ID.text);
	x.setAttribute("arg2", $a.foo);
	$st = x;

Now it would be:

a[int foo] : ID
	StringTemplate x = %foo();
	%x.arg1 = $ID.text;
	%x.arg2 = $foo;
	$st = x;

So x is just a variable like you expect; to use shortcut access to ST  
stuff, you need the %.  Note how the $ stuff is now clearly separated  
from the % template stuff.

Look ok?


More information about the antlr-interest mailing list