Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    [The "BSD licence"]
    Copyright (c) 2003-2005 Terence Parr
    All rights reserved.
   
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
    1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products
      derived from this software without specific prior written permission.
  
   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
  package org.antlr.stringtemplate;
  
  import java.io.*;
  import java.util.*;
  
  import antlr.*;
A StringTemplate is a "document" with holes in it where you can stick values. StringTemplate breaks up your template into chunks of text and attribute expressions. StringTemplate ignores everything outside of attribute expressions, treating it as just text to spit out when you call StringTemplate.toString().
  
  public class StringTemplate {
  	public static final String VERSION = "3.2.1"// September 22, 2009
  
<@r()>
  
  	public static final int REGION_IMPLICIT = 1;
<@r>...<@end>
  
  	public static final int REGION_EMBEDDED = 2;

T.r:
) ::= "..." defined manually by coder
  
  	public static final int REGION_EXPLICIT = 3;

An automatically created aggregate of properties. I often have lists of things that need to be formatted, but the list items are actually pieces of data that are not already in an object. I need ST to do something like: Ter=3432 Tom=32234 .... using template: $items:{it.name$=$it.type$}$ This example will call getName() on the objects in items attribute, but what if they aren't objects? I have perhaps two parallel arrays instead of a single array of objects containing two fields. One solution is allow Maps to be handled like properties so that it.name would fail getName() but then see that it's a Map and do it.get("name") instead. This very clean approach is espoused by some, but the problem is that it's a hole in my separation rules. People can put the logic in the view because you could say: "go get bob's data" in the view: Bob's Phone: $db.bob.phone$ A view should not be part of the program and hence should never be able to go ask for a specific person's data. After much thought, I finally decided on a simple solution. I've added setAttribute variants that pass in multiple property values, with the property names specified as part of the name using a special attribute name syntax: "name.{propName1,propName2,...}". This object is a special kind of HashMap that hopefully prevents people from passing a subclass or other variant that they have created as it would be a loophole. Anyway, the ASTExpr.getObjectProperty() method looks for Aggregate as a special case and does a get() instead of getPropertyName.
  
  	public static final class Aggregate {
  		protected HashMap properties = new HashMap();
Allow StringTemplate to add values, but prevent the end user from doing so.
 
 		protected void put(String propNameObject propValue) {
 			.put(propNamepropValue);
 		}
 		public Object get(String propName) {
 			return .get(propName);
 		}
 		public String toString() {
 			return .toString();
 		}
 	}

Just an alias for ArrayList, but this way I can track whether a list is something ST created or it's an incoming list.
 
 	public static final class STAttributeList extends ArrayList {
 		public STAttributeList(int size) { super(size); }
 		public STAttributeList() { super(); }
 	}
 
 	public static final String ANONYMOUS_ST_NAME = "anonymous";

track probable issues like setting attribute that is not referenced.
 
 	static boolean lintMode = false;
 
 	protected List referencedAttributes = null;

What's the name of this template?
 
 	protected String name = ;
 
 	private static int templateCounter=0;
 	private static synchronized int getNextTemplateCounter() {
 		return ;
 	}
reset the template ID counter to 0; public so that testing routine can access but not really of interest to the user.
 
 	public static void resetTemplateCounter() {
 	}
 
 	protected int templateID = getNextTemplateCounter();

Enclosing instance if I'm embedded within another template. IF-subtemplates are considered embedded as well.
 
 	protected StringTemplate enclosingInstance = null;

If this template is an embedded template such as when you apply a template to an attribute, then the arguments passed to this template represent the argument context--a set of values computed by walking the argument assignment list. For example, <name:bold(item=name, foo="x")> would result in an argument context of {[item=name], [foo="x"]} for this template. This template would be the bold() template and the enclosingInstance would point at the template that held that <name:bold(...)> template call. When you want to get an attribute value, you first check the attributes for the 'self' template then the arg context then the enclosingInstance like resolving variables in pascal-like language with nested procedures. With multi-valued attributes such as <faqList:briefFAQDisplay()> attribute "i" is set to 1..n.
 
 	protected Map argumentContext = null;

If this template is embedded in another template, the arguments must be evaluated just before each application when applying template to a list of values. The "it" attribute must change with each application so that $names:bold(item=it)$ works. If you evaluate once before starting the application loop then it has a single fixed value. Eval.g saves the AST rather than evaluating before invoking applyListOfAlternatingTemplates(). Each iteration of a template application to a multi-valued attribute, these args are re-evaluated with an initial context of {[it=...], [i=...]}.
 
 	protected StringTemplateAST argumentsAST = null;

When templates are defined in a group file format, the attribute list is provided including information about attribute cardinality such as present, optional, ... When this information is available, rawSetAttribute should do a quick existence check as should the invocation of other templates. So if you ref bold(item="foo") but item is not defined in bold(), then an exception should be thrown. When actually rendering the template, the cardinality is checked. This is a Map<String,FormalArgument>.
 
How many formal arguments to this template have default values specified?
 
 	protected int numberOfDefaultArgumentValues = 0;

Normally, formal parameters hide any attributes inherited from the enclosing template with the same name. This is normally what you want, but makes it hard to invoke another template passing in all the data. Use notation now: <otherTemplate(...)> to say "pass in all data". Works great. Can also say <otherTemplate(foo="xxx",...)>
 
 	protected boolean passThroughAttributes = false;

What group originally defined the prototype for this template? This affects the set of templates I can refer to. super.t() must always refer to the super of the original group. group base; t ::= "base"; group sub; t ::= "super.t()2" group subsub; t ::= "super.t()3"
 
This template was created as part of what group? Even if this template was created from a prototype in a supergroup, its group will be the subgroup. That's the way polymorphism works.
 
 	protected StringTemplateGroup group;


If this template is defined within a group file, what line number?
 
 	protected int groupFileLine;

Where to report errors
 
The original, immutable pattern/language (not really used again after initial "compilation", setup/parsing).
 
 	protected String pattern;

Map an attribute name to its value(s). These values are set by outside code via st.setAttribute(name, value). StringTemplate is like self in that a template is both the "class def" and "instance". When you create a StringTemplate or setTemplate, the text is broken up into chunks (i.e., compiled down into a series of chunks that can be evaluated later). You can have multiple
 
 	protected Map attributes;

A Map<Class,Object> that allows people to register a renderer for a particular kind of object to be displayed in this template. This overrides any renderer set for this template's group. Most of the time this map is not used because the StringTemplateGroup has the general renderer map for all templates in that group. Sometimes though you want to override the group's renderers.
 
 	protected Map attributeRenderers;

A list of alternating string and ASTExpr references. This is compiled to when the template is loaded/defined and walked to write out a template instance.
 
 	protected List chunks;

If someone refs <@r()> in template t, an implicit

T.r:
) ::= "" is defined, but you can overwrite this def by defining your own. We need to prevent more than one manual def though. Between this var and isEmbeddedRegion we can determine these cases.
 
 	protected int regionDefType;

Does this template come from a <@region>...<@end> embedded in another template?
 
 	protected boolean isRegion;

Set of implicit and embedded regions for this template
 
 	protected Set regions;
 
 	public static StringTemplateGroup defaultGroup =
 		new StringTemplateGroup("defaultGroup"".");

Create a blank template with no pattern and no attributes
 
 	public StringTemplate() {
 		 = // make sure has a group even if default
 	}

Create an anonymous template. It has no name just chunks (which point to this anonymous template) and attributes.
 
 	public StringTemplate(String template) {
 		this(nulltemplate);
 	}
 
 	public StringTemplate(String templateClass lexer) {
 		this();
 		setGroup(new StringTemplateGroup("defaultGroup"lexer));
 		setTemplate(template);
 	}

Create an anonymous template with no name, but with a group
 
 	public StringTemplate(StringTemplateGroup groupString template) {
 		this();
 		if ( group!=null ) {
 			setGroup(group);
 		}
 		setTemplate(template);
 	}
 
 						  String template,
 						  HashMap attributes)
 	{
 		this(group,template);
 		this. = attributes;
 	}

Make the 'to' template look exactly like the 'from' template except for the attributes. This is like creating an instance of a class in that the executable code is the same (the template chunks), but the instance data is blank (the attributes). Do not copy the enclosingInstance pointer since you will want this template to eval in a context different from the examplar.
 
 	protected void dup(StringTemplate fromStringTemplate to) {
 		to.attributeRenderers = from.attributeRenderers;
 		to.pattern = from.pattern;
 		to.chunks = from.chunks;
 		to.formalArguments = from.formalArguments;
 		to.numberOfDefaultArgumentValues = from.numberOfDefaultArgumentValues;
 		to.name = from.name;
 		to.group = from.group;
 		to.nativeGroup = from.nativeGroup;
 		to.listener = from.listener;
 		to.regions = from.regions;
 		to.isRegion = from.isRegion;
 		to.regionDefType = from.regionDefType;
 	}

Make an instance of this template; it contains an exact copy of everything (except the attributes and enclosing instance pointer). So the new template refers to the previously compiled chunks of this template but does not have any attribute values.
 
 		StringTemplate t = null;
 		if ( !=null ) {
 			// create a template using the native group for this template
 			// but it's "group" is set to this.group by dup after creation so
 			// polymorphism still works.
 		}
 		else {
 		}
 		dup(thist);
 		return t;
 	}
 
 	}
 
 		if ( !=null ) {
 		}
 		return this;
 	}
 
 	public void setEnclosingInstance(StringTemplate enclosingInstance) {
 		if ( this==enclosingInstance ) {
 			throw new IllegalArgumentException("cannot embed template "+getName()+" in itself");
 		}
 		// set the parent for this template
 		this. = enclosingInstance;
 	}
 
 	public Map getArgumentContext() {
 		return ;
 	}
 
 	public void setArgumentContext(Map ac) {
 	}
 
 		return ;
 	}
 
 	public void setArgumentsAST(StringTemplateAST argumentsAST) {
 		this. = argumentsAST;
 	}
 
 	public String getName() {
 		return ;
 	}
 
 	public String getOutermostName() {
 		if ( !=null ) {
 		}
 		return getName();
 	}
 
 	public void setName(String name) {
 		this. = name;
 	}
 
 		return ;
 	}
 
 	public void setGroup(StringTemplateGroup group) {
 		this. = group;
 	}
 
 		return ;
 	}
 
 	public void setNativeGroup(StringTemplateGroup nativeGroup) {
 		this. = nativeGroup;
 	}

Return the outermost template's group file line number
 
 	public int getGroupFileLine() {
 		if ( !=null ) {
 		}
 		return ;
 	}
 
 	public void setGroupFileLine(int groupFileLine) {
 		this. = groupFileLine;
 	}
 
 	public void setTemplate(String template) {
 		this. = template;
 	}
 
 	public String getTemplate() {
 		return ;
 	}
 
 	public void setErrorListener(StringTemplateErrorListener listener) {
 		this. = listener;
 	}
 
 		if ( ==null ) {
 		}
 		return ;
 	}
 
 	public void reset() {
 		 = new HashMap(); // just throw out table and make new one
 	}
 
 	public void setPredefinedAttributes() {
 		if ( !inLintMode() ) {
 			return// only do this method so far in lint mode
 		}
 	}
 
 	public void removeAttribute(String name) {
 		if ( !=null ) .remove(name);
 	}

Set an attribute for this template. If you set the same attribute more than once, you get a multi-valued attribute. If you send in a StringTemplate object as a value, it's enclosing instance (where it will inherit values from) is set to 'this'. This would be the normal case, though you can set it back to null after this call if you want. If you send in a List plus other values to the same attribute, they all get flattened into one List of values. This will be a new list object so that incoming objects are not altered. If you send in an array, it is converted to an ArrayIterator.
 
 	public void setAttribute(String nameObject value) {
 		if ( value==null || name==null ) {
 			return;
 		}
 		if ( name.indexOf('.')>=0 ) {
 			throw new IllegalArgumentException("cannot have '.' in attribute names");
 		}
 		if ( ==null ) {
 			 = new HashMap();
 		}
 
 		if ( value instanceof StringTemplate ) {
 		}
 		else {
 			// convert value if array
 			value = ASTExpr.convertArrayToList(value);
 		}
 
 		// convert plain collections
 		// get exactly in this scope (no enclosing)
 		Object o = this..get(name);
 		if ( o==null ) { // new attribute
 			rawSetAttribute(this.namevalue);
 			return;
 		}
 		// it will be a multi-value attribute
 		//System.out.println("exists: "+name+"="+o);
 		STAttributeList v = null;
 		if ( o.getClass() == STAttributeList.class ) { // already a list made by ST
 			v = (STAttributeList)o;
 		}
 		else if ( o instanceof List ) { // existing attribute is non-ST List
 			// must copy to an ST-managed list before adding new attribute
 			List listAttr = (List)o;
 			v = new STAttributeList(listAttr.size());
 			v.addAll(listAttr);
 			rawSetAttribute(this.namev); // replace attribute w/list
 		}
 		else {
 			// non-list second attribute, must convert existing to ArrayList
 			v = new STAttributeList(); // make list to hold multiple values
 			// make it point to list now
 			rawSetAttribute(this.namev); // replace attribute w/list
 			v.add(o);  // add previous single-valued attribute
 		}
 		if ( value instanceof List ) {
 			// flatten incoming list into existing
 			if ( v!=value ) { // avoid weird cyclic add
 				v.addAll((List)value);
 			}
 		}
 		else {
 			v.add(value);
 		}
 	}

Convenience method to box ints
 
 	public void setAttribute(String nameint value) {
 		setAttribute(namenew Integer(value));
 	}

Set an aggregate attribute with two values. The attribute name must have the format: "name.{propName1,propName2}".
 
 	public void setAttribute(String aggrSpecObject v1Object v2) {
 		setAttribute(aggrSpecnew Object[] {v1,v2});
 	}
 
 	public void setAttribute(String aggrSpecObject v1Object v2Object v3) {
 		setAttribute(aggrSpecnew Object[] {v1,v2,v3});
 	}
 
 	public void setAttribute(String aggrSpecObject v1Object v2Object v3Object v4) {
 		setAttribute(aggrSpecnew Object[] {v1,v2,v3,v4});
 	}
 
 	public void setAttribute(String aggrSpecObject v1Object v2Object v3Object v4Object v5) {
 		setAttribute(aggrSpecnew Object[] {v1,v2,v3,v4,v5});
 	}

Create an aggregate from the list of properties in aggrSpec and fill with values from values array. This is not publically visible because it conflicts semantically with setAttribute("foo",new Object[] {...});
 
 	protected void setAttribute(String aggrSpecObject[] values) {
 		List properties = new ArrayList();
 		String aggrName = parseAggregateAttributeSpec(aggrSpecproperties);
 		if ( values==null || properties.size()==0 ) {
 			throw new IllegalArgumentException("missing properties or values for '"+aggrSpec+"'");
 		}
 		if ( values.length != properties.size() ) {
 			throw new IllegalArgumentException("number of properties in '"+aggrSpec+"' != number of values");
 		}
 		Aggregate aggr = new Aggregate();
 		for (int i = 0; i < values.lengthi++) {
 			Object value = values[i];
 			if ( value instanceof StringTemplate ) {
 			}
 			else {
 				value = ASTExpr.convertArrayToList(value);
 			}
 			aggr.put((String)properties.get(i), value);
 		}
 		setAttribute(aggrNameaggr);
 	}

Split "aggrName.{propName1,propName2}" into list [propName1,propName2] and the aggrName. Space is allowed around ','.
 
 	protected String parseAggregateAttributeSpec(String aggrSpecList properties) {
 		int dot = aggrSpec.indexOf('.');
 		if ( dot<=0 ) {
 			throw new IllegalArgumentException("invalid aggregate attribute format: "+
 					aggrSpec);
 		}
 		String aggrName = aggrSpec.substring(0, dot);
 		String propString = aggrSpec.substring(dot+1, aggrSpec.length());
 		boolean error = true;
 		StringTokenizer tokenizer = new StringTokenizer(propString"{,}"true);
 		match:
 		if ( tokenizer.hasMoreTokens() ) {
 			String token = tokenizer.nextToken(); // advance to {
 			token = token.trim();
 			if ( token.equals("{") ) {
 				token = tokenizer.nextToken();    // advance to first prop name
 				token = token.trim();
 				properties.add(token);
 				token = tokenizer.nextToken();    // advance to a comma
 				token = token.trim();
 				while ( token.equals(",") ) {
 					token = tokenizer.nextToken();    // advance to a prop name
 					token = token.trim();
 					properties.add(token);
 					token = tokenizer.nextToken();    // advance to a "," or "}"
 					token = token.trim();
 				}
 				if ( token.equals("}") ) {
 					error = false;
 				}
 			}
 		}
 		if ( error ) {
 			throw new IllegalArgumentException("invalid aggregate attribute format: "+
 					aggrSpec);
 		}
 		return aggrName;
 	}

Map a value to a named attribute. Throw NoSuchElementException if the named attribute is not formally defined in self's specific template and a formal argument list exists.
 
 	protected void rawSetAttribute(Map attributes,
 								   String name,
 								   Object value)
 	{
 			getFormalArgument(name)==null )
 		{
 			// a normal call to setAttribute with unknown attribute
 			throw new NoSuchElementException("no such attribute: "+name+
 											 " in template context "+
 		}
 		if ( value == null ) {
 			return;
 		}
 		attributes.put(namevalue);
 	}

Argument evaluation such as foo(x=y), x must be checked against foo's argument list not this's (which is the enclosing context). So far, only eval.g uses arg self as something other than "this".
 
 	public void rawSetArgumentAttribute(StringTemplate embedded,
 										Map attributes,
 										String name,
 										Object value)
 	{
 		if ( embedded.formalArguments!=. &&
 			 embedded.getFormalArgument(name)==null )
 		{
 			throw new NoSuchElementException("template "+embedded.getName()+
 											 " has no such attribute: "+name+
 											 " in template context "+
 		}
 		if ( value == null ) {
 			return;
 		}
 		attributes.put(namevalue);
 	}
 
 	public Object getAttribute(String name) {
 		Object v = get(this,name);
         if ( v==null ) {
             checkNullAttributeAgainstFormalArguments(thisname);
         }
         return v;
 	}

Walk the chunks, asking them to write themselves out according to attribute values of 'this.attributes'. This is like evaluating or interpreting the StringTemplate as a program using the attributes. The chunks will be identical (point at same list) for all instances of this template.
 
 	public int write(StringTemplateWriter outthrows IOException {
 		}
 		int n = 0;
         boolean missing = true;
 		for (int i=0; !=null && i<.size(); i++) {
 			Expr a = (Expr).get(i);
 			int chunkN = a.write(thisout);
 			// expr-on-first-line-with-no-output NEWLINE => NEWLINE
 			if ( chunkN<=0 && i==0 && (i+1)<.size() &&
 				 .get(i+1) instanceof NewlineRef )
 			{
 				//System.out.println("found pure first-line-blank \\n pattern");
 				i++; // skip next NEWLINE;
 				continue;
 			}
 			// NEWLINE expr-with-no-output NEWLINE => NEWLINE
 			// Indented $...$ have the indent stored with the ASTExpr
 			// so the indent does not come out as a StringRef
 			if ( chunkN<=0 &&
 				(i-1)>=0 && .get(i-1) instanceof NewlineRef &&
 				(i+1)<.size() && .get(i+1) instanceof NewlineRef )
 			{
 				//System.out.println("found pure \\n blank \\n pattern");
 				i++; // make it skip over the next chunk, the NEWLINE
 			}
             if ( chunkN!=. ) {
                 n += chunkN;
                 missing = false;
             }
 		}
 		}
 		if (  ) checkForTrouble();
 		if ( missing && !=null && .size()>0 ) return .;
         return n;
 	}

Resolve an attribute reference. It can be in four possible places: 1. the attribute list for the current template 2. if self is an embedded template, somebody invoked us possibly with arguments--check the argument context 3. if self is an embedded template, the attribute list for the enclosing instance (recursively up the enclosing instance chain) 4. if nothing is found in the enclosing instance chain, then it might be a map defined in the group or the its supergroup etc... Attribute references are checked for validity. If an attribute has a value, its validity was checked before template rendering. If the attribute has no value, then we must check to ensure it is a valid reference. Somebody could reference any random value like $xyz$; formal arg checks before rendering cannot detect this--only the ref can initiate a validity check. So, if no value, walk up the enclosed template tree again, this time checking formal parameters not attributes Map. The formal definition must exist even if no value. To avoid infinite recursion in toString(), we have another condition to check regarding attribute values. If your template has a formal argument, foo, then foo will hide any value available from "above" in order to prevent infinite recursion. This method is not static so people can override functionality.
 
 	public Object get(StringTemplate selfString attribute) {
         /*
 		System.out.println("### get("+self.getEnclosingInstanceStackString()+", "+attribute+")");
 		System.out.println("attributes="+(self.attributes!=null?self.attributes.keySet().toString():"none"));
 		*/
 		if ( self==null ) {
 			return null;
 		}
 
 		if (  ) {
 			self.trackAttributeReference(attribute);
 		}
 
 		// is it here?
 		Object o = null;
 		if ( self.attributes!=null ) {
 			o = self.attributes.get(attribute);
 		}
 
 		// nope, check argument context in case embedded
 		if ( o==null ) {
 			Map argContext = self.getArgumentContext();
 			if ( argContext!=null ) {
 				o = argContext.get(attribute);
 			}
 		}
 
 		if ( o==null &&
 			 !self.passThroughAttributes &&
 			 self.getFormalArgument(attribute)!=null )
 		{
 			// if you've defined attribute as formal arg for this
 			// template and it has no value, do not look up the
 			// enclosing dynamic scopes.  This avoids potential infinite
 			// recursion.
 			return null;
 		}
 
 		// not locally defined, check enclosingInstance if embedded
 		if ( o==null && self.enclosingInstance!=null ) {
             /*
             System.out.println("looking for "+getName()+"."+attribute+" in super="+
                     enclosingInstance.getName());
              */
 			Object valueFromEnclosing = get(self.enclosingInstanceattribute);
             /*
 			if ( valueFromEnclosing==null ) {
 				checkNullAttributeAgainstFormalArguments(self, attribute);
 			}
 			*/
 			o = valueFromEnclosing;
 		}
 
 		// not found and no enclosing instance to look at
 		else if ( o==null && self.enclosingInstance==null ) {
 			// It might be a map in the group or supergroup...
 			o = self.group.getMap(attribute);
 		}
 
 		return o;
 	}

Walk a template, breaking it into a list of chunks: Strings and actions/expressions.
 
 	protected void breakTemplateIntoChunks() {
 		//System.out.println("parsing template: "+pattern);
 		if ( ==null ) {
 			return;
 		}
 		try {
 			// instead of creating a specific template lexer, use
 			// an instance of the class specified by the user.
 			// The default is DefaultTemplateLexer.
 			// The only constraint is that you use an ANTLR lexer
 			// so I can use the special ChunkToken.
 			Class lexerClass = .getTemplateLexerClass();
 			Constructor ctor =
 					lexerClass.getConstructor(
 						new Class[] {StringTemplate.class,Reader.class}
 					);
 			CharScanner chunkStream =
 						new Object[] {this,new StringReader()}
 					);
 			chunkStream.setTokenObjectClass("org.antlr.stringtemplate.language.ChunkToken");
 			TemplateParser chunkifier = new TemplateParser(chunkStream);
 			chunkifier.template(this);
 			//System.out.println("chunks="+chunks);
 		}
 		catch (Exception e) {
 			String name = "<unknown>";
 			String outerName = getOutermostName();
 			if ( getName()!=null ) {
 				name = getName();
 			}
 			if ( outerName!=null && !name.equals(outerName) ) {
 				name = name+" nested in "+outerName;
 			}
 			error("problem parsing template '"+name+"'"e);
 		}
 	}
 
 	public ASTExpr parseAction(String action) {
 		//System.out.println("parse action "+action);
 		ActionLexer lexer =
 			new ActionLexer(new StringReader(action.toString()));
 		ActionParser parser =
 			new ActionParser(lexerthis);
 		parser.setASTNodeClass("org.antlr.stringtemplate.language.StringTemplateAST");
 		lexer.setTokenObjectClass("org.antlr.stringtemplate.language.StringTemplateToken");
 		ASTExpr a = null;
 		try {
 			Map options = parser.action();
 			AST tree = parser.getAST();
 			if ( tree!=null ) {
 				if ( tree.getType()==. ) {
 					a = new ConditionalExpr(this,tree);
 				}
 				else {
 					a = new ASTExpr(this,tree,options);
 				}
 			}
 		}
 		catch (RecognitionException re) {
 			error("Can't parse chunk: "+action.toString(), re);
 		}
 		catch (TokenStreamException tse) {
 			error("Can't parse chunk: "+action.toString(), tse);
 		}
 		return a;
 	}
 
 	public int getTemplateID() {
 		return ;
 	}
 
 	public Map getAttributes() {
 		return ;
 	}

Get a list of the strings and subtemplates and attribute refs in a template.
 
 	public List getChunks() {
 		return ;
 	}
 
 	public void addChunk(Expr e) {
 		if ( ==null ) {
 			 = new ArrayList();
 		}
 		.add(e);
 	}
 
 	public void setAttributes(Map attributes) {
 		this. = attributes;
 	}
 
 	// F o r m a l  A r g  S t u f f
 
 	public Map getFormalArguments() {
 		return ;
 	}
 
 	public void setFormalArguments(LinkedHashMap args) {
 		 = args;
 	}

Set any default argument values that were not set by the invoking template or by setAttribute directly. Note that the default values may be templates. Their evaluation context is the template itself and, hence, can see attributes within the template, any arguments, and any values inherited by the template. Default values are stored in the argument context rather than the template attributes table just for consistency's sake.
 
 	public void setDefaultArgumentValues() {
         //System.out.println("setDefaultArgumentValues; "+name+": argctx="+argumentContext+", n="+numberOfDefaultArgumentValues);
 			return;
 		}
 		if ( ==null ) {
 		}
             //System.out.println("formal args="+formalArguments.keySet());
 			Set argNames = .keySet();
 			for (Iterator it = argNames.iterator(); it.hasNext();) {
 				String argName = (Stringit.next();
 				// use the default value then
 				if ( arg.defaultValueST!=null ) {
                     //System.out.println("default value="+arg.defaultValueST.chunks);
                     //System.out.println(getEnclosingInstanceStackString()+": get "+argName+" argctx="+argumentContext);
 					Object existingValue = getAttribute(argName);
                     //System.out.println("existing value="+existingValue);
 					if ( existingValue==null ) { // value unset?
                         Object defaultValue = arg.defaultValueST;
 						// if no value for attribute, set arg context
 						// to the default value.  We don't need an instance
 						// here because no attributes can be set in
 						// the arg templates by the user.
                         int nchunks = arg.defaultValueST.chunks.size();
                         if ( nchunks==1 ) {
                             // If default arg is template with single expression
                             // wrapped in parens, x={<(...)>}, then eval to string
                             // rather than setting x to the template for later
                             // eval.
                             Object a = arg.defaultValueST.chunks.get(0);
                             if ( a instanceof ASTExpr ) {
                                 ASTExpr e = (ASTExpr)a;
                                 if ( e.getAST().getType()==. ) {
                                     defaultValue = e.evaluateExpression(thise.getAST());
                                 }
                             }
                         }
                         .put(argNamedefaultValue);
 					}
 				}
 			}
 		}
 	}

From this template upward in the enclosing template tree, recursively look for the formal parameter.
 
 		if ( arg==null && !=null ) {
 		}
 		return arg;
 	}
	public void defineFormalArgument(String name) {
	public void defineFormalArguments(List names) {
		if ( names==null ) {
			return;
		for (int i = 0; i < names.size(); i++) {
			String name = (Stringnames.get(i);
	public void defineFormalArgument(String nameStringTemplate defaultValue) {
        /*
        System.out.println("define formal arg "+this.name+"."+name+
                           ", def value="+(defaultValue!=null?defaultValue.chunks:"null"));
                           */
		if ( defaultValue!=null ) {
		FormalArgument a = new FormalArgument(name,defaultValue);
	}

Normally if you call template y from x, y cannot see any attributes of x that are defined as formal parameters of y. Setting this passThroughAttributes to true, will override that and allow a template to see through the formal arg list to inherited values.
	public void setPassThroughAttributes(boolean passThroughAttributes) {
		this. = passThroughAttributes;
	}

Specify a complete map of what object classes should map to which renderer objects.
	public void setAttributeRenderers(Map renderers) {
		this. = renderers;
	}

Register a renderer for all objects of a particular type. This overrides any renderer set in the group for this class type.
	public void registerRenderer(Class attributeClassTypeAttributeRenderer renderer) {
		if ( ==null ) {
		.put(attributeClassTyperenderer);
	}

What renderer is registered for this attributeClassType for this template. If not found, the template's group is queried.
	public AttributeRenderer getAttributeRenderer(Class attributeClassType) {
		AttributeRenderer renderer = null;
		if ( !=null ) {
			renderer = (AttributeRenderer).get(attributeClassType);
		if ( renderer!=null ) {
			// found it!
			return renderer;
		// we have no renderer overrides for the template or none for class arg
		// check parent template if we are embedded
		if ( !=null ) {
			return .getAttributeRenderer(attributeClassType);
		// else check group
		return .getAttributeRenderer(attributeClassType);
	// U T I L I T Y  R O U T I N E S
	public void error(String msg) {
		error(msgnull);
	public void warning(String msg) {
		if ( getErrorListener()!=null ) {
		else {
			..println("StringTemplate: warning: "+msg);
	public void error(String msgThrowable e) {
		if ( getErrorListener()!=null ) {
		else {
			if ( e!=null ) {
				..println("StringTemplate: error: "+msg+": "+e.toString());
				if ( e instanceof InvocationTargetException ) {
			else {
				..println("StringTemplate: error: "+msg);
	}

Make StringTemplate check your work as it evaluates templates. Problems are sent to error listener. Currently warns when you set attributes that are not used.
	public static void setLintMode(boolean lint) {
	public static boolean inLintMode() {
		return ;
	}

Indicates that 'name' has been referenced in this template.
	protected void trackAttributeReference(String name) {
		if ( ==null ) {
	}

Look up the enclosing instance chain (and include this) to see if st is a template already in the enclosing instance chain.
	public static boolean isRecursiveEnclosingInstance(StringTemplate st) {
		if ( st==null ) {
			return false;
		StringTemplate p = st.enclosingInstance;
		if ( p==st ) {
			return true// self-recursive
		// now look for indirect recursion
		while ( p!=null ) {
			if ( p==st ) {
				return true;
			p = p.enclosingInstance;
		return false;
		StringBuffer buf = new StringBuffer();
		Set seen = new HashSet();
		StringTemplate p = this;
		while ( p!=null ) {
			if ( seen.contains(p) ) {
				buf.append(" (start of recursive cycle)");
				buf.append("\n");
				buf.append("...");
				break;
			seen.add(p);
			if ( p.attributes!=null ) {
				buf.append(", attributes=[");
				int i = 0;
				for (Iterator iter = p.attributes.keySet().iterator(); iter.hasNext();) {
					String attrName = (Stringiter.next();
					if ( i>0 ) {
						buf.append(", ");
					i++;
					buf.append(attrName);
					Object o = p.attributes.get(attrName);
					if ( o instanceof StringTemplate ) {
						buf.append("=");
						buf.append("<");
						buf.append(st.getName());
						buf.append("()@");
						buf.append(String.valueOf(st.getTemplateID()));
						buf.append(">");
					else if ( o instanceof List ) {
						buf.append("=List[..");
						List list = (List)o;
						int n=0;
						for (int j = 0; j < list.size(); j++) {
							Object listValue = list.get(j);
							if ( listValue instanceof StringTemplate ) {
								if ( n>0 ) {
									buf.append(", ");
								n++;
								StringTemplate st = (StringTemplate)listValue;
								buf.append("<");
								buf.append(st.getName());
								buf.append("()@");
								buf.append(String.valueOf(st.getTemplateID()));
								buf.append(">");
						buf.append("..]");
				buf.append("]");
			if ( p.referencedAttributes!=null ) {
				buf.append(", references=");
				buf.append(p.referencedAttributes);
			buf.append(">\n");
			p = p.enclosingInstance;
		/*
				if ( enclosingInstance!=null ) {
				buf.append(enclosingInstance.getEnclosingInstanceStackTrace());
				*/
		return buf.toString();
		StringBuffer buf = new StringBuffer();
		buf.append("<");
		buf.append("(");
		buf.append(")@");
		buf.append(">");
		return buf.toString();
	protected String getTemplateHeaderString(boolean showAttributes) {
		if ( showAttributes ) {
			StringBuffer buf = new StringBuffer();
			if ( !=null ) {
			return buf.toString();
		return getName();
	}

Find "missing attribute" and "cardinality mismatch" errors. Excecuted before a template writes its chunks out. When you find a problem, throw an IllegalArgumentException. We must check the attributes as well as the incoming arguments in argumentContext. protected void checkAttributesAgainstFormalArguments() { Set args = formalArguments.keySet(); /* if ( (attributes==null||attributes.size()==0) && (argumentContext==null||argumentContext.size()==0) && formalArguments.size()!=0 ) { throw new IllegalArgumentException("missing argument(s): "+args+" in template "+getName()); } Iterator iter = args.iterator(); while ( iter.hasNext() ) { String argName = (String)iter.next(); FormalArgument arg = getFormalArgument(argName); int expectedCardinality = arg.getCardinality(); Object value = getAttribute(argName); int actualCardinality = getActualArgumentCardinality(value); // if intersection of expected and actual is empty, mismatch if ( (expectedCardinality&actualCardinality)==0 ) { throw new IllegalArgumentException("cardinality mismatch: "+ argName+"; expected "+ FormalArgument.getCardinalityName(expectedCardinality)+ " found cardinality="+getObjectLength(value)); } } }
A reference to an attribute with no value, must be compared against the formal parameter to see if it exists; if it exists all is well, but if not, throw an exception. Don't do the check if no formal parameters exist for this template; ask enclosing.
			String attribute)
			// bypass unknown arg lists
			if ( self.enclosingInstance!=null ) {
						self.enclosingInstance,
						attribute);
			return;
		FormalArgument formalArg = self.lookupFormalArgument(attribute);
		if ( formalArg == null ) {
			throw new NoSuchElementException("no such attribute: "+attribute+
											 " in template context "+getEnclosingInstanceStackString());
	}

Executed after evaluating a template. For now, checks for setting of attributes not reference.
	protected void checkForTrouble() {
		// we have table of set values and list of values referenced
		// compare, looking for SET BUT NOT REFERENCED ATTRIBUTES
		if ( ==null ) {
			return;
		Set names = .keySet();
		Iterator iter = names.iterator();
		// if in names and not in referenced attributes, trouble
		while ( iter.hasNext() ) {
			String name = (String)iter.next();
			if ( !=null &&
				warning(getName()+": set but not used: "+name);
		// can do the reverse, but will have lots of false warnings :(
	}

If an instance of x is enclosed in a y which is in a z, return a String of these instance names in order from topmost to lowest; here that would be "[z y x]".
		List names = new LinkedList();
		StringTemplate p = this;
		while ( p!=null ) {
			String name = p.getName();
			names.add(0,name+(p.passThroughAttributes?"(...)":""));
			p = p.enclosingInstance;
		return names.toString().replaceAll(",","");
	public boolean isRegion() {
		return ;
	public void setIsRegion(boolean isRegion) {
		this. = isRegion;
	public void addRegionName(String name) {
		if ( ==null ) {
			 = new HashSet();
	}

Does this template ref or embed region name?
	public boolean containsRegionName(String name) {
		if ( ==null ) {
			return false;
		return .contains(name);
	public int getRegionDefType() {
	public void setRegionDefType(int regionDefType) {
		this. = regionDefType;
	public String toDebugString() {
		StringBuffer buf = new StringBuffer();
		buf.append("template-"+getTemplateDeclaratorString()+":");
		buf.append("chunks=");
		if ( !=null ) {
		buf.append("attributes=[");
		if ( !=null ) {
			Set attrNames = .keySet();
			int n=0;
			for (Iterator iter = attrNames.iterator(); iter.hasNext();) {
				if ( n>0 ) {
					buf.append(',');
				String name = (Stringiter.next();
				buf.append(name+"=");
				Object value = .get(name);
				if ( value instanceof StringTemplate ) {
				else {
					buf.append(value);
				n++;
			buf.append("]");